@runtypelabs/persona 3.30.0 → 3.31.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -2602
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-B_Qazlm4.d.cts → types-quh7NmYD.d.cts} +9 -0
- package/dist/animations/{types-B_Qazlm4.d.ts → types-quh7NmYD.d.ts} +9 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +3 -3
- package/dist/index.cjs +46 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +52 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.global.js +77 -80
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +45 -45
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +50 -0
- package/dist/smart-dom-reader.d.ts +50 -0
- package/dist/theme-editor.cjs +39 -39
- package/dist/theme-editor.d.cts +50 -0
- package/dist/theme-editor.d.ts +50 -0
- package/dist/theme-editor.js +39 -39
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.js +1 -1
- package/dist/webmcp-polyfill.js +4 -0
- package/dist/widget.css +19 -0
- package/package.json +4 -3
- package/src/client.ts +6 -0
- package/src/components/approval-bubble.test.ts +52 -0
- package/src/components/approval-bubble.ts +20 -0
- package/src/components/panel.ts +7 -1
- package/src/defaults.ts +14 -0
- package/src/generated/runtype-openapi-contract.ts +4 -0
- package/src/index-global.ts +39 -0
- package/src/session.test.ts +62 -0
- package/src/session.ts +27 -0
- package/src/styles/widget.css +19 -0
- package/src/theme-reference.ts +1 -1
- package/src/types.ts +50 -0
- package/src/ui.scroll.test.ts +383 -0
- package/src/ui.ts +390 -40
- package/src/utils/auto-follow.test.ts +91 -0
- package/src/utils/auto-follow.ts +68 -0
- package/src/version.ts +5 -2
- package/src/webmcp-bridge.test.ts +60 -0
- package/src/webmcp-bridge.ts +34 -1
- package/src/webmcp-polyfill.ts +16 -0
package/dist/index.cjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
"use strict";var Tg=Object.create;var Na=Object.defineProperty;var Eg=Object.getOwnPropertyDescriptor;var Mg=Object.getOwnPropertyNames;var kg=Object.getPrototypeOf,Lg=Object.prototype.hasOwnProperty;var Pg=(e,t)=>{for(var n in t)Na(e,n,{get:t[n],enumerable:!0})},Qp=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Mg(t))!Lg.call(e,s)&&s!==n&&Na(e,s,{get:()=>t[s],enumerable:!(r=Eg(t,s))||r.enumerable});return e};var Yp=(e,t,n)=>(n=e!=null?Tg(kg(e)):{},Qp(t||!e||!e.__esModule?Na(n,"default",{value:e,enumerable:!0}):n,e)),Ig=e=>Qp(Na({},"__esModule",{value:!0}),e);var Fb={};Pg(Fb,{ASK_USER_QUESTION_TOOL_NAME:()=>Sl,AgentWidgetClient:()=>Oo,AgentWidgetSession:()=>ds,AttachmentManager:()=>jo,DEFAULT_COMPONENTS:()=>al,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ni,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Yn,DEFAULT_PALETTE:()=>ol,DEFAULT_SEMANTIC:()=>sl,DEFAULT_WIDGET_CONFIG:()=>$t,PRESETS:()=>Ql,PRESET_FULLSCREEN:()=>Xl,PRESET_MINIMAL:()=>Gl,PRESET_SHOP:()=>Jl,THEME_ZONES:()=>Pu,VERSION:()=>Jo,WEBMCP_TOOL_PREFIX:()=>_r,WebMcpBridge:()=>is,accessibilityPlugin:()=>rg,animationsPlugin:()=>og,applyThemeVariables:()=>uo,attachHeaderToContainer:()=>Uo,brandPlugin:()=>sg,buildComposer:()=>fs,buildDefaultHeader:()=>gl,buildHeader:()=>qr,buildHeaderWithLayout:()=>gs,buildMinimalHeader:()=>fl,collectEnrichedPageContext:()=>eg,componentRegistry:()=>Kr,createActionManager:()=>ba,createAgentExperience:()=>ji,createAskUserQuestionBubble:()=>um,createBestAvailableVoiceProvider:()=>ei,createBubbleWithLayout:()=>Qu,createCSATFeedback:()=>Fi,createComboButton:()=>yi,createComponentMiddleware:()=>Hm,createComponentStreamParser:()=>Bi,createDefaultSanitizer:()=>Zi,createDemoCarousel:()=>Sg,createDirectivePostprocessor:()=>ru,createDropdownMenu:()=>ho,createFlexibleJsonStreamParser:()=>pu,createIconButton:()=>Vt,createImagePart:()=>yu,createJsonStreamParser:()=>Va,createLabelButton:()=>ca,createLocalStorageAdapter:()=>Hi,createMarkdownProcessor:()=>zs,createMarkdownProcessorFromConfig:()=>Bo,createMessageActions:()=>vl,createNPSFeedback:()=>$i,createPlainTextParser:()=>qa,createPlugin:()=>lg,createRegexJsonParser:()=>za,createStandardBubble:()=>hs,createTextPart:()=>Js,createTheme:()=>us,createThemeObserver:()=>ai,createToggleGroup:()=>da,createTypingIndicator:()=>qo,createVoiceProvider:()=>_o,createWidgetHostLayout:()=>ya,createXmlParser:()=>Ka,default:()=>pg,defaultActionHandlers:()=>Ko,defaultJsonActionParser:()=>ha,defaultParseRules:()=>Vl,detectColorScheme:()=>Zs,directivePostprocessor:()=>ou,ensureAskUserQuestionSheet:()=>ws,escapeHtml:()=>Do,extractComponentDirectiveFromMessage:()=>Oi,fileToImagePart:()=>xu,formatEnrichedContext:()=>tg,generateAssistantMessageId:()=>Fo,generateCodeSnippet:()=>bg,generateMessageId:()=>mu,generateStableSelector:()=>Kl,generateUserMessageId:()=>cs,getActiveTheme:()=>ms,getColorScheme:()=>ll,getDisplayText:()=>fu,getHeaderLayout:()=>hl,getImageParts:()=>bu,getPreset:()=>dg,hasComponentDirective:()=>Ni,hasImages:()=>hu,headerLayouts:()=>xi,highContrastPlugin:()=>ig,initAgentWidget:()=>jl,isAskUserQuestionMessage:()=>zr,isComponentDirectiveType:()=>Rm,isDockedMountMode:()=>ln,isVoiceSupported:()=>Xs,isWebMcpToolName:()=>po,listRegisteredStreamAnimations:()=>Uu,markdownPostprocessor:()=>Yi,mergeWithDefaults:()=>ri,normalizeContent:()=>gu,parseAskUserQuestionPayload:()=>Vr,pluginRegistry:()=>fa,reducedMotionPlugin:()=>ag,registerStreamAnimationPlugin:()=>_u,removeAskUserQuestionSheet:()=>xo,renderComponentDirective:()=>Di,renderLoadingIndicatorWithFallback:()=>xl,renderLucideIcon:()=>we,resolveDockConfig:()=>mr,resolveSanitizer:()=>as,resolveTokens:()=>oi,stripWebMcpPrefix:()=>Fa,themeToCssVariables:()=>si,unregisterStreamAnimationPlugin:()=>ju,validateImageFile:()=>vu,validateTheme:()=>il});module.exports=Ig(Fb);var eu=require("marked"),Wg=e=>{if(e)return e},zs=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new eu.Marked({gfm:(s=t==null?void 0:t.gfm)!=null?s:!0,breaks:(o=t==null?void 0:t.breaks)!=null?o:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),r=Wg(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},Bo=e=>e?zs({markedOptions:e.options,renderer:e.renderer}):zs(),Rg=zs(),Yi=e=>Rg(e),Do=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),tu=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Zp=e=>`%%FORM_PLACEHOLDER_${e}%%`,nu=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Zp(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=Zp(t.length);return t.push({token:o,type:s}),o}),n},ru=e=>{let t=Bo(e);return n=>{let r=[],s=nu(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${tu(i)}"></div>`;o=o.replace(d,p)}),o}},ou=e=>{let t=[],n=nu(e,t),r=Yi(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${tu(o)}"></div>`;r=r.replace(a,d)}),r};var su=Yp(require("dompurify"),1),Hg={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"]},Bg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Zi=()=>{let e=(0,su.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:")&&!Bg.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Hg)},as=e=>e===!1?null:typeof e=="function"?e:Zi();var _r="webmcp:",el=new Map,au=e=>{var t;el.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&el.set(n.name,r)}},tl=e=>el.get(Fa(e)),Oa={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function lu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Dg(t.join(""))}`}function iu(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Dg(e){let t=iu(e,0).toString(36),n=iu(e,2654435761).toString(36);return`${t}.${n}`}var is=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return Oa.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}au(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Og(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return Sr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let v=typeof document!="undefined"&&!!document.modelContext;return Sr(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 o=Fa(t),a;try{a=await s.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return Sr(`Failed to read WebMCP registry: ${x}`)}au(a);let i=a.find(v=>v.name===o);if(!i)return Sr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return Sr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return Sr("Aborted by cancel()");let d=tl(o),l={toolName:o,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Sr("User declined the tool call.");if(r!=null&&r.aborted)return Sr("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 s.executeTool(i,jg(n),{signal:p.signal});return Fg(v)}catch(v){if(u)return Sr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return Sr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return Sr(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{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Oa.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,Oa.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:$g;try{return await n(t)}catch(s){return Oa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>Ng(t,r))}},Fa=e=>e.startsWith(_r)?e.slice(_r.length):e,po=e=>e.startsWith(_r),Ng=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Og=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Fg=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:Ug(t)}]}},Sr=e=>({isError:!0,content:[{type:"text",text:e}]}),$g=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=_g(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Tu=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),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?`
|
|
2
2
|
|
|
3
3
|
Arguments:
|
|
4
4
|
${t}`:"")+(e.description?`
|
|
5
5
|
|
|
6
|
-
${e.description}`:"");return window.confirm(n)},
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
8
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},No=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},qa=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},za=()=>{var t;let e=Vg();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)}},Va=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=(0,jr.parse)(n,jr.STR|jr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?$a(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=$a(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},pu=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?$a(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?$a(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=(0,jr.parse)(o,jr.STR|jr.OBJ),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Ka=()=>{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 Ja=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Kg="https://api.runtype.com/v1/dispatch",Ga="https://api.runtype.com";function Jg(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var rl=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 Gg(e){switch(e){case"json":return Va;case"regex-json":return za;case"xml":return Ka;default:return qa}}var uu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Xg(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=uu(n);if(!uu(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=No(e);return No(t)!==null&&a===null?t:e}var Oo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Kg,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Gg(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new is(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$/,""))||Ga}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/client/feedback`}async sendFeedback(t){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let P=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:P}),P}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(rl).map(P=>{var W,S,I;return{id:P.id,role:P.role,content:(I=(S=(W=P.contentParts)!=null?W:P.llmContent)!=null?S:P.rawContent)!=null?I:P.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?lu(f):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,w=m&&x&&this.lastSentClientToolsFingerprint===v,T=!1,B=null,k;for(let P=0;;P++){let S={...u,...m&&(T||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:r.signal}),k.status===409&&P===0&&m){let I=await k.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}B=I!=null?I:{error:"Chat request failed"}}break}if(!k.ok){let P=B!=null?B:await k.json().catch(()=>({error:"Chat request failed"}));if(k.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(k.status===429){let S=new Error(P.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let W=new Error(P.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!k.body){let P=new Error("No response body received");throw n({type:"error",error:P}),P}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 s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ga}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(rl).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(t){var o;let r={messages:t.slice().filter(rl).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=u,s(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,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var gn,Bn,er,Ue;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=F=>{let Ee=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,De=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Ne=F.tools?F.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...F,reasoning:Ee,toolCall:De,tools:Ne}},u=F=>{if(F.role!=="assistant"||F.variant)return!0;let Ee=Array.isArray(F.contentParts)&&F.contentParts.length>0,De=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||Ee||De||!!F.stopReason},f=F=>{u(F)&&n({type:"message",message:p(F)})},m=null,v=null,x={current:null},w={current:null},T=!1,B=new Map,k=new Map,P=new Map,W=new Map,S={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},$=(F,Ee,De="")=>`${F}::${Ee}::${De}`,D=(F,Ee)=>`${F}::${Ee}::`,R=(F,Ee,De,Ne)=>{let _e=$(F,Ee,De),mt=P.get(_e);if(mt)return mt;let at=De?`-${De}`:"",It={id:`nested-${F}-${Ee}${at}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Ne,parentToolId:F,parentStepId:Ee}};return P.set(_e,It),f(It),It},q=F=>{if(F==null)return null;try{return String(F)}catch{return null}},K=F=>{var Ee,De,Ne,_e,mt;return q((mt=(_e=(Ne=(De=(Ee=F.stepId)!=null?Ee:F.step_id)!=null?De:F.step)!=null?Ne:F.parentId)!=null?_e:F.flowStepId)!=null?mt:F.flow_step_id)},se=F=>{var Ee,De,Ne,_e,mt,at,It;return q((It=(at=(mt=(_e=(Ne=(De=(Ee=F.callId)!=null?Ee:F.call_id)!=null?De:F.requestId)!=null?Ne:F.request_id)!=null?_e:F.toolCallId)!=null?mt:F.tool_call_id)!=null?at:F.stepId)!=null?It:F.step_id)},Re=r,Ge=!1,Ce=()=>{if(m)return m;let F;return!Ge&&Re?(F=Re,Ge=!0):Re&&w.current?F=`${Re}_${w.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},He=(F,Ee)=>{S.lastId=Ee,F&&S.byStep.set(F,Ee)},be=(F,Ee)=>{var mt;let De=(mt=F.reasoningId)!=null?mt:F.id,Ne=K(F);if(De){let at=String(De);return He(Ne,at),at}if(Ne){let at=S.byStep.get(Ne);if(at)return S.lastId=at,at}if(S.lastId&&!Ee)return S.lastId;if(!Ee)return null;let _e=`reason-${l()}`;return He(Ne,_e),_e},Be=F=>{let Ee=B.get(F);if(Ee)return Ee;let De={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return B.set(F,De),f(De),De},Pe=(F,Ee)=>{I.lastId=Ee,F&&I.byCall.set(F,Ee)},J=new Set,ue=new Map,V=new Set,de=new Map,le=F=>{if(!F)return!1;let Ee=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ee==="emit_artifact_markdown"||Ee==="emit_artifact_component"},ae=(F,Ee)=>{var mt;let De=(mt=F.toolId)!=null?mt:F.id,Ne=se(F);if(De){let at=String(De);return Pe(Ne,at),at}if(Ne){let at=I.byCall.get(Ne);if(at)return I.lastId=at,at}if(I.lastId&&!Ee)return I.lastId;if(!Ee)return null;let _e=`tool-${l()}`;return Pe(Ne,_e),_e},Se=F=>{let Ee=k.get(F);if(Ee)return Ee;let De={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return k.set(F,De),f(De),De},ze=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let Ee=Number(F);if(!Number.isNaN(Ee)&&Number.isFinite(Ee))return Ee;let De=Date.parse(F);if(!Number.isNaN(De))return De}return Date.now()},Y=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},ne=new Map,ce=new Map,xe=new Map,me=new Map,oe=null,Ze=(F,Ee,De)=>{var It;let Ne=xe.get(F);Ne||(Ne=[],xe.set(F,Ne));let _e=0,mt=Ne.length;for(;_e<mt;){let Kt=_e+mt>>>1;Ne[Kt].seq<Ee?_e=Kt+1:mt=Kt}((It=Ne[_e])==null?void 0:It.seq)===Ee?Ne[_e]={seq:Ee,text:De}:Ne.splice(_e,0,{seq:Ee,text:De});let at="";for(let Kt=0;Kt<Ne.length;Kt++)at+=Ne[Kt].text;return at},We=(F,Ee)=>{let De=Y(Ee),Ne=ce.get(F.id),_e=Xg(Ne,De);F.rawContent=_e;let mt=ne.get(F.id),at=et=>{var re;let _t=(re=F.content)!=null?re:"";et.trim()!==""&&(_t.trim().length===0||et.startsWith(_t)||et.trimStart().startsWith(_t.trim()))&&(F.content=et)},It=()=>{var et;if(mt){let _t=(et=mt.close)==null?void 0:et.call(mt);_t instanceof Promise&&_t.catch(()=>{})}ne.delete(F.id),ce.delete(F.id),F.streaming=!1,f(F)};if(!mt){at(De),It();return}let Kt=No(_e);if(Kt!==null&&Kt.trim()!==""){at(Kt),It();return}let z=et=>{var ve;let _t=typeof et=="string"?et:(ve=et==null?void 0:et.text)!=null?ve:null;if(_t!==null&&_t.trim()!=="")return _t;let re=mt.getExtractedText();return re!==null&&re.trim()!==""?re:De},qt;try{qt=mt.processChunk(_e)}catch{at(De),It();return}if(qt instanceof Promise){qt.then(et=>{at(z(et)),It()}).catch(()=>{at(De),It()});return}at(z(qt)),It()},fe=[],X=!1,$e,Ht=()=>{X||(X=!0,queueMicrotask(()=>{X=!1,$e()}))},he=new Ja((F,Ee)=>{fe.push({payloadType:F,payload:Ee}),Ht()}),pe=null,Pn=new Map,Ut=(gn=this.config.iterationDisplay)!=null?gn:"separate";for($e=()=>{var F,Ee,De,Ne,_e,mt,at,It,Kt,z,qt,et,_t,re,ve,Et,Jt,nn,Cn,Wt,kt,wt,At,Gt,ot,Dn,tr,An,Nn,bt,Er,On,Co,In,Go,Gr,Wr,St,Fn,$n,Sn,Lt,nr,rr,_n,Xr,Rr,Qr,jn,Dt,Tn,or,Yr,Hr,Zr,Mr,Un,hr,xt,Qt,Yt,qn,eo,sr,br,zn,_,ar,ye,Vn,ir,yr,Ts,xr,vr,wr,Br,Ao,va,Es,wa,Xo,yt,Ms,lr,Wn,Ca,Aa,Qo,Dr,Sa,So,ks,Nr,Ls,to,no,Ta,Ea,Xi,To,ro,Ma,Ps,oo,ka,Is,so,Ws,La,Or,Pa,ao,Nt,Yo,Zo,Rs,kr,Ia,Hs,Bs,Wa,es,ts,Eo,Ra,Ha,Ds,Ns,Os,Fs,En,Kn,Fr,ct,$s,Mo,Cr;for(let ns=0;ns<fe.length;ns++){let Je=fe[ns].payloadType,A=fe[ns].payload;if(Je==="reason_start"){let j=(F=be(A,!0))!=null?F:`reason-${l()}`,M=Be(j);M.reasoning=(Ee=M.reasoning)!=null?Ee:{id:j,status:"streaming",chunks:[]},M.reasoning.startedAt=(Ne=M.reasoning.startedAt)!=null?Ne:ze((De=A.startedAt)!=null?De:A.timestamp),M.reasoning.completedAt=void 0,M.reasoning.durationMs=void 0,M.streaming=!0,M.reasoning.status="streaming",f(M)}else if(Je==="reason_delta"||Je==="reason_chunk"){let j=(mt=(_e=be(A,!1))!=null?_e:be(A,!0))!=null?mt:`reason-${l()}`,M=Be(j);M.reasoning=(at=M.reasoning)!=null?at:{id:j,status:"streaming",chunks:[]},M.reasoning.startedAt=(Kt=M.reasoning.startedAt)!=null?Kt:ze((It=A.startedAt)!=null?It:A.timestamp);let Z=(et=(qt=(z=A.reasoningText)!=null?z:A.text)!=null?qt:A.delta)!=null?et:"";if(Z&&A.hidden!==!0){let ie=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(ie!==void 0){let G=Ze(j,ie,String(Z));M.reasoning.chunks=[G]}else M.reasoning.chunks.push(String(Z))}if(M.reasoning.status=A.done?"complete":"streaming",A.done){M.reasoning.completedAt=ze((_t=A.completedAt)!=null?_t:A.timestamp);let ie=(re=M.reasoning.startedAt)!=null?re:Date.now();M.reasoning.durationMs=Math.max(0,((ve=M.reasoning.completedAt)!=null?ve:Date.now())-ie)}M.streaming=M.reasoning.status!=="complete",f(M)}else if(Je==="reason_complete"){let j=(Jt=(Et=be(A,!1))!=null?Et:be(A,!0))!=null?Jt:`reason-${l()}`,M=B.get(j);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=ze((nn=A.completedAt)!=null?nn:A.timestamp);let ie=(Cn=M.reasoning.startedAt)!=null?Cn:Date.now();M.reasoning.durationMs=Math.max(0,((Wt=M.reasoning.completedAt)!=null?Wt:Date.now())-ie),M.streaming=!1,f(M)}let Z=K(A);Z&&S.byStep.delete(Z)}else if(Je==="tool_start"){let j=(kt=ae(A,!0))!=null?kt:`tool-${l()}`,M=(wt=A.toolName)!=null?wt:A.name;if(le(M)){J.add(j);continue}let Z=Se(j),ie=(At=Z.toolCall)!=null?At:{id:j,status:"pending"};ie.name=M!=null?M:ie.name,ie.status="running",A.args!==void 0?ie.args=A.args:A.parameters!==void 0&&(ie.args=A.parameters),ie.startedAt=(ot=ie.startedAt)!=null?ot:ze((Gt=A.startedAt)!=null?Gt:A.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,Z.toolCall=ie,Z.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(Z.agentMetadata={executionId:(Dn=G==null?void 0:G.executionId)!=null?Dn:A.executionId,iteration:(tr=G==null?void 0:G.iteration)!=null?tr:A.iteration}),f(Z)}else if(Je==="tool_chunk"||Je==="tool_delta"){let j=(Nn=(An=ae(A,!1))!=null?An:ae(A,!0))!=null?Nn:`tool-${l()}`;if(J.has(j))continue;let M=Se(j),Z=(bt=M.toolCall)!=null?bt:{id:j,status:"running"};Z.startedAt=(On=Z.startedAt)!=null?On:ze((Er=A.startedAt)!=null?Er:A.timestamp);let ie=(Go=(In=(Co=A.text)!=null?Co:A.delta)!=null?In:A.message)!=null?Go:"";ie&&(Z.chunks=(Gr=Z.chunks)!=null?Gr:[],Z.chunks.push(String(ie))),Z.status="running",M.toolCall=Z,M.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(M.agentMetadata=(Fn=M.agentMetadata)!=null?Fn:{executionId:(Wr=G==null?void 0:G.executionId)!=null?Wr:A.executionId,iteration:(St=G==null?void 0:G.iteration)!=null?St:A.iteration}),f(M)}else if(Je==="tool_complete"){let j=(Sn=($n=ae(A,!1))!=null?$n:ae(A,!0))!=null?Sn:`tool-${l()}`;if(J.has(j)){J.delete(j);continue}let M=Se(j),Z=(Lt=M.toolCall)!=null?Lt:{id:j,status:"running"};Z.status="complete",A.result!==void 0&&(Z.result=A.result),typeof A.duration=="number"&&(Z.duration=A.duration),Z.completedAt=ze((nr=A.completedAt)!=null?nr:A.timestamp);let ie=(rr=A.duration)!=null?rr:A.executionTime;if(typeof ie=="number")Z.durationMs=ie;else{let Fe=(_n=Z.startedAt)!=null?_n:Date.now();Z.durationMs=Math.max(0,((Xr=Z.completedAt)!=null?Xr:Date.now())-Fe)}M.toolCall=Z,M.streaming=!1;let G=A.agentContext;(G||A.executionId)&&(M.agentMetadata=(jn=M.agentMetadata)!=null?jn:{executionId:(Rr=G==null?void 0:G.executionId)!=null?Rr:A.executionId,iteration:(Qr=G==null?void 0:G.iteration)!=null?Qr:A.iteration}),f(M);let ke=se(A);ke&&I.byCall.delete(ke)}else if(Je==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let j=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,M=(Dt=j!=null?j:A.toolId)!=null?Dt:`local-${l()}`,Z=Se(M),ie=A.toolName,G=po(ie),ke=(Tn=Z.toolCall)!=null?Tn:{id:M,status:"pending"};ke.name=ie,ke.args=A.parameters,ke.status=G?"running":"complete",ke.chunks=(or=ke.chunks)!=null?or:[],ke.startedAt=(Hr=ke.startedAt)!=null?Hr:ze((Yr=A.startedAt)!=null?Yr:A.timestamp),G?(ke.completedAt=void 0,ke.duration=void 0,ke.durationMs=void 0):ke.completedAt=(Zr=ke.completedAt)!=null?Zr:ke.startedAt,Z.toolCall=ke,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(Un=A.executionId)!=null?Un:(Mr=Z.agentMetadata)==null?void 0:Mr.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},f(Z)}else if(Je==="text_start"){if((hr=A.toolContext)!=null&&hr.toolId)continue;let j=A.partId;if(j!==void 0&&w.current!==null&&j!==w.current){let M=m;M&&(M.streaming=!1,f(M),oe=M,m=null,T=!0)}j!==void 0&&(w.current=j)}else if(Je==="text_end"){if((xt=A.toolContext)!=null&&xt.toolId)continue;let j=m;j&&(j.streaming=!1,f(j),oe=j,m=null,T=!0)}else if(Je==="step_chunk"||Je==="step_delta"){let j=A.stepType,M=A.executionType;if(j==="tool"||M==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Yt=(Qt=A.id)!=null?Qt:Z.stepId)!=null?Yt:`step-${l()}`),dt=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Xe=`${Z.toolId}::${Fe}`,Qe=W.get(Xe);if(dt!==""&&Qe!==void 0&&Qe!==""&&Qe!==dt){let Pt=P.get($(Z.toolId,Fe,Qe));Pt&&Pt.streaming!==!1&&(Pt.streaming=!1,f(Pt))}dt!==""&&W.set(Xe,dt);let tt=R(Z.toolId,Fe,dt,Z.executionId),Zt=(br=(sr=(eo=(qn=A.text)!=null?qn:A.delta)!=null?eo:A.content)!=null?sr:A.chunk)!=null?br:"";Zt&&(tt.content+=String(Zt),tt.streaming=!0,f(tt)),A.isComplete&&(tt.streaming=!1,f(tt));continue}let ie=A.partId;if(ie!==void 0&&w.current!==null&&ie!==w.current){let Fe=m;Fe&&(Fe.streaming=!1,f(Fe),oe=Fe,m=null,T=!0)}ie!==void 0&&(w.current=ie);let G=ie!==void 0&&(zn=me.get(ie))!=null?zn:Ce();ie!==void 0&&(G.partId||(G.partId=ie),me.set(ie,G));let ke=(Vn=(ye=(ar=(_=A.text)!=null?_:A.delta)!=null?ar:A.content)!=null?ye:A.chunk)!=null?Vn:"";if(ke){let Fe=typeof A.seq=="number"?A.seq:void 0,dt=ie!=null?ie:G.id,Xe=Fe!==void 0?Ze(dt,Fe,String(ke)):((ir=ce.get(G.id))!=null?ir:"")+ke;G.rawContent=Xe,ne.has(G.id)||ne.set(G.id,this.createStreamParser());let Qe=ne.get(G.id),tt=Xe.trim().startsWith("{")||Xe.trim().startsWith("[");if(tt&&ce.set(G.id,Xe),Qe.__isPlainTextParser===!0){G.content=Fe!==void 0?Xe:G.content+ke,ce.delete(G.id),ne.delete(G.id),G.rawContent=void 0,f(G);continue}let Pt=Qe.processChunk(Xe);if(Pt instanceof Promise)Pt.then(Bt=>{var bn;let cn=typeof Bt=="string"?Bt:(bn=Bt==null?void 0:Bt.text)!=null?bn:null;if(cn!==null&&cn.trim()!=="")G.content=cn,f(G);else if(!tt&&!Xe.trim().startsWith("<")){let hn=m,rn=hn&&hn.id===G.id?hn:G;rn.id===G.id&&(rn.content=Fe!==void 0?Xe:rn.content+ke,ce.delete(rn.id),ne.delete(rn.id),rn.rawContent=void 0,f(rn))}}).catch(()=>{G.content=Fe!==void 0?Xe:G.content+ke,ce.delete(G.id),ne.delete(G.id),G.rawContent=void 0,f(G)});else{let Bt=typeof Pt=="string"?Pt:(yr=Pt==null?void 0:Pt.text)!=null?yr:null;Bt!==null&&Bt.trim()!==""?(G.content=Bt,f(G)):!tt&&!Xe.trim().startsWith("<")&&(G.content=Fe!==void 0?Xe:G.content+ke,ce.delete(G.id),ne.delete(G.id),G.rawContent=void 0,f(G))}}if(A.isComplete){let Fe=(xr=(Ts=A.result)==null?void 0:Ts.response)!=null?xr:G.content;if(Fe){let dt=ce.get(G.id),Xe=dt!=null?dt:Y(Fe);G.rawContent=Xe;let Qe=ne.get(G.id),tt=null,Zt=!1;if(Qe&&(tt=Qe.getExtractedText(),tt===null&&(tt=No(Xe)),tt===null)){let Pt=Qe.processChunk(Xe);Pt instanceof Promise?(Zt=!0,Pt.then(Bt=>{var bn;let cn=typeof Bt=="string"?Bt:(bn=Bt==null?void 0:Bt.text)!=null?bn:null;if(cn!==null){let hn=m;hn&&hn.id===G.id&&(hn.content=cn,hn.streaming=!1,ne.delete(hn.id),ce.delete(hn.id),f(hn))}})):tt=typeof Pt=="string"?Pt:(vr=Pt==null?void 0:Pt.text)!=null?vr:null}if(!Zt){tt!==null&&tt.trim()!==""?G.content=tt:ce.has(G.id)||(G.content=Y(Fe));let Pt=ne.get(G.id);if(Pt){let Bt=(wr=Pt.close)==null?void 0:wr.call(Pt);Bt instanceof Promise&&Bt.catch(()=>{}),ne.delete(G.id)}ce.delete(G.id),G.streaming=!1,f(G)}}}}else if(Je==="step_complete"){let j=A.stepType,M=A.executionType;if(j==="tool"||M==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Ao=(Br=A.id)!=null?Br:Z.stepId)!=null?Ao:"");if(Fe){let dt=D(Z.toolId,Fe);for(let[Xe,Qe]of P)Xe.startsWith(dt)&&Qe.streaming!==!1&&(Qe.streaming=!1,f(Qe));W.delete(`${Z.toolId}::${Fe}`)}continue}let ie=A.stopReason;if(T){if(m!==null){let Xe=m;ie&&(Xe.stopReason=ie),ne.delete(Xe.id),ce.delete(Xe.id),Xe.streaming!==!1&&(Xe.streaming=!1,f(Xe))}let Fe=(va=A.result)==null?void 0:va.response,dt=oe;dt&&(ie&&(dt.stopReason=ie),Fe!=null?We(dt,Fe):(ne.delete(dt.id),ce.delete(dt.id))),oe=null;continue}let G=(Es=A.result)==null?void 0:Es.response,ke=Ce();if(ie&&(ke.stopReason=ie),G!=null){let Fe=ne.get(ke.id),dt=!1,Xe=!1;if(Fe){let Qe=Fe.getExtractedText(),tt=ce.get(ke.id),Zt=tt!=null?tt:Y(G);if(ke.rawContent=Zt,Qe!==null&&Qe.trim()!=="")ke.content=Qe,dt=!0;else{let Pt=No(Zt);if(Pt!==null)ke.content=Pt,dt=!0;else{let Bt=Fe.processChunk(Zt);if(Bt instanceof Promise)Xe=!0,Bt.then(cn=>{var hn;let bn=typeof cn=="string"?cn:(hn=cn==null?void 0:cn.text)!=null?hn:null;if(bn!==null&&bn.trim()!==""){let rn=m;rn&&rn.id===ke.id&&(rn.content=bn,rn.streaming=!1,ne.delete(rn.id),ce.delete(rn.id),f(rn))}else{let rn=Fe.getExtractedText(),cr=m;cr&&cr.id===ke.id&&(rn!==null&&rn.trim()!==""?cr.content=rn:ce.has(cr.id)||(cr.content=Y(G)),cr.streaming=!1,ne.delete(cr.id),ce.delete(cr.id),f(cr))}});else{let cn=typeof Bt=="string"?Bt:(wa=Bt==null?void 0:Bt.text)!=null?wa:null;if(cn!==null&&cn.trim()!=="")ke.content=cn,dt=!0;else{let bn=Fe.getExtractedText();bn!==null&&bn.trim()!==""&&(ke.content=bn,dt=!0)}}}}}if(!Xe){if(!ke.rawContent){let Qe=ce.get(ke.id);ke.rawContent=Qe!=null?Qe:Y(G)}if(!dt&&!ce.has(ke.id)&&(ke.content=Y(G)),Fe){let Qe=(Xo=Fe.close)==null?void 0:Xo.call(Fe);Qe instanceof Promise&&Qe.catch(()=>{})}ne.delete(ke.id),ce.delete(ke.id),ke.streaming=!1,f(ke)}}else ne.delete(ke.id),ce.delete(ke.id),ke.streaming=!1,f(ke)}else if(Je==="flow_complete"){let j=(yt=A.result)==null?void 0:yt.response;if(T){if(m!==null){let M=m;ne.delete(M.id),ce.delete(M.id),M.streaming!==!1&&(M.streaming=!1,f(M))}}else if(j!=null){let M=Ce(),Z=ce.get(M.id),ie=Z!=null?Z:Y(j);M.rawContent=ie;let G=Y(j),ke=ne.get(M.id);if(ke){let Xe=No(ie);if(Xe!==null)G=Xe;else{let Qe=ke.processChunk(ie);Qe instanceof Promise&&Qe.then(Zt=>{var Bt;let Pt=typeof Zt=="string"?Zt:(Bt=Zt==null?void 0:Zt.text)!=null?Bt:null;Pt!==null&&(M.content=Pt,M.streaming=!1,f(M))});let tt=ke.getExtractedText();tt!==null&&(G=tt)}}ne.delete(M.id),ce.delete(M.id);let Fe=G!==M.content,dt=M.streaming!==!1;Fe&&(M.content=G),M.streaming=!1,(Fe||dt)&&f(M)}else if(m!==null){let M=m;ne.delete(M.id),ce.delete(M.id),M.streaming!==!1&&(M.streaming=!1,f(M))}n({type:"status",status:"idle"})}else if(Je==="agent_start")pe={executionId:A.executionId,agentId:(Ms=A.agentId)!=null?Ms:"virtual",agentName:(lr=A.agentName)!=null?lr:"",status:"running",currentIteration:0,maxTurns:(Wn=A.maxTurns)!=null?Wn:1,startedAt:ze(A.startedAt)};else if(Je==="agent_iteration_start"){if(pe&&(pe.currentIteration=A.iteration),Ut==="separate"&&A.iteration>1){let j=m;j&&(j.streaming=!1,f(j),Pn.set(A.iteration-1,j),m=null)}}else if(Je==="agent_turn_start")v=null;else if(Je==="agent_turn_delta"){if(A.contentType==="text"){let j=Ce();j.content+=(Ca=A.delta)!=null?Ca:"",j.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:pe==null?void 0:pe.agentName},v=j,f(j)}else if(A.contentType==="thinking"){let j=(Aa=A.turnId)!=null?Aa:`agent-think-${A.iteration}`,M=Be(j);M.reasoning=(Qo=M.reasoning)!=null?Qo:{id:j,status:"streaming",chunks:[]},M.reasoning.chunks.push((Dr=A.delta)!=null?Dr:""),M.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},f(M)}else if(A.contentType==="tool_input"){let j=(Sa=A.toolCallId)!=null?Sa:I.lastId;if(j){let M=k.get(j);M!=null&&M.toolCall&&(M.toolCall.chunks=(So=M.toolCall.chunks)!=null?So:[],M.toolCall.chunks.push((ks=A.delta)!=null?ks:""),f(M))}}}else if(Je==="agent_turn_complete"){let j=A.turnId;if(j){let ie=B.get(j);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=ze(A.completedAt);let G=(Nr=ie.reasoning.startedAt)!=null?Nr:Date.now();ie.reasoning.durationMs=Math.max(0,((Ls=ie.reasoning.completedAt)!=null?Ls:Date.now())-G),ie.streaming=!1,f(ie)}}let M=A.stopReason,Z=m!=null?m:v;if(M&&Z!==null){let ie=A.turnId;(!ie||((to=Z.agentMetadata)==null?void 0:to.turnId)===ie)&&(Z.stopReason=M,f(Z))}}else if(Je==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let j=(no=A.toolCallId)!=null?no:`agent-tool-${l()}`;Pe(se(A),j);let M=Se(j),Z=(Ta=M.toolCall)!=null?Ta:{id:j,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(Xi=(Ea=A.toolName)!=null?Ea:A.name)!=null?Xi:Z.name,Z.status="running",A.parameters!==void 0&&(Z.args=A.parameters),Z.startedAt=ze((To=A.startedAt)!=null?To:A.timestamp),M.toolCall=Z,M.streaming=!0,M.agentMetadata={executionId:A.executionId,iteration:A.iteration},f(M)}else if(Je==="agent_tool_delta"){let j=(ro=A.toolCallId)!=null?ro:I.lastId;if(j){let M=(Ma=k.get(j))!=null?Ma:Se(j);M.toolCall&&(M.toolCall.chunks=(Ps=M.toolCall.chunks)!=null?Ps:[],M.toolCall.chunks.push((oo=A.delta)!=null?oo:""),M.toolCall.status="running",M.streaming=!0,f(M))}}else if(Je==="agent_tool_complete"){let j=(ka=A.toolCallId)!=null?ka:I.lastId;if(j){let M=(Is=k.get(j))!=null?Is:Se(j);if(M.toolCall){M.toolCall.status="complete",A.result!==void 0&&(M.toolCall.result=A.result),typeof A.executionTime=="number"&&(M.toolCall.durationMs=A.executionTime),M.toolCall.completedAt=ze((so=A.completedAt)!=null?so:A.timestamp),M.streaming=!1,f(M);let Z=se(A);Z&&I.byCall.delete(Z)}}}else if(Je==="agent_media"){let j=Array.isArray(A.media)?A.media:[],M=[];for(let Z of j){if(!Z||typeof Z!="object")continue;let ie=Z,G=typeof ie.type=="string"?ie.type:void 0,ke=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",Fe=null,dt="";if(G==="media"){let Xe=typeof ie.data=="string"?ie.data:void 0;if(!Xe)continue;dt=ke.length>0?ke:"application/octet-stream",Fe=`data:${dt};base64,${Xe}`}else if(G==="image-url"){let Xe=typeof ie.url=="string"?ie.url:void 0;if(!Xe)continue;dt=ke,Fe=Xe}else if(G==="file-url"){let Xe=typeof ie.url=="string"?ie.url:void 0;if(!Xe)continue;dt=ke,Fe=Xe}else continue;if(Fe)if(G==="image-url"||dt.startsWith("image/"))M.push({type:"image",image:Fe,...dt?{mimeType:dt}:{}});else if(dt.startsWith("audio/"))M.push({type:"audio",audio:Fe,mimeType:dt});else if(dt.startsWith("video/"))M.push({type:"video",video:Fe,mimeType:dt});else{let Xe=dt||"application/octet-stream";M.push({type:"file",data:Fe,mimeType:Xe,filename:Jg(Xe)})}}if(M.length>0){let Z=l(),ie=A.toolCallId,ke={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:M,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(ke);let Fe=m;Fe&&(Fe.streaming=!1,f(Fe)),m=null,x.current=null}}else if(Je!=="agent_iteration_complete"){if(Je==="agent_reflection"||Je==="agent_reflect"){let j=`agent-reflection-${A.executionId}-${A.iteration}`,M={id:j,role:"assistant",content:(Ws=A.reflection)!=null?Ws:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(La=A.reflection)!=null?La:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(M)}else if(Je==="agent_complete"){pe&&(pe.status=A.success?"complete":"error",pe.completedAt=ze(A.completedAt),pe.stopReason=A.stopReason);let j=m;j&&(j.streaming=!1,f(j)),n({type:"status",status:"idle"})}else if(Je==="agent_error"){let j=typeof A.error=="string"?A.error:(Pa=(Or=A.error)==null?void 0:Or.message)!=null?Pa:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):n({type:"error",error:new Error(j)})}else if(Je!=="agent_ping"){if(Je==="agent_approval_start"){let j=(ao=A.approvalId)!=null?ao:`approval-${l()}`,M={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Nt=pe==null?void 0:pe.agentId)!=null?Nt:"virtual",executionId:(Zo=(Yo=A.executionId)!=null?Yo:pe==null?void 0:pe.executionId)!=null?Zo:"",toolName:(Rs=A.toolName)!=null?Rs:"",toolType:A.toolType,description:(Ia=A.description)!=null?Ia:`Execute ${(kr=A.toolName)!=null?kr:"tool"}`,parameters:A.parameters}};f(M)}else if(Je==="step_await"&&A.awaitReason==="approval_required"){let j=(Hs=A.approvalId)!=null?Hs:`approval-${l()}`,M={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Bs=pe==null?void 0:pe.agentId)!=null?Bs:"virtual",executionId:(es=(Wa=A.executionId)!=null?Wa:pe==null?void 0:pe.executionId)!=null?es:"",toolName:(ts=A.toolName)!=null?ts:"",toolType:A.toolType,description:(Ra=A.description)!=null?Ra:`Execute ${(Eo=A.toolName)!=null?Eo:"tool"}`,parameters:A.parameters}};f(M)}else if(Je==="agent_approval_complete"){let j=A.approvalId;if(j){let Z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(Ha=A.decision)!=null?Ha:"approved",agentId:(Ds=pe==null?void 0:pe.agentId)!=null?Ds:"virtual",executionId:(Os=(Ns=A.executionId)!=null?Ns:pe==null?void 0:pe.executionId)!=null?Os:"",toolName:(Fs=A.toolName)!=null?Fs:"",description:(En=A.description)!=null?En:"",resolvedAt:Date.now()}};f(Z)}}else if(Je==="artifact_start"||Je==="artifact_delta"||Je==="artifact_update"||Je==="artifact_complete"){if(Je==="artifact_start"){let j=A.artifactType,M=String(A.id),Z=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:M,artifactType:j,title:Z,component:typeof A.component=="string"?A.component:void 0}),de.set(M,{markdown:"",title:Z}),!V.has(M)){V.add(M);let ie={id:`artifact-ref-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:M,title:Z,artifactType:j,status:"streaming"}})};ue.set(M,ie),f(ie)}}else if(Je==="artifact_delta"){let j=String(A.id),M=typeof A.delta=="string"?A.delta:String((Kn=A.delta)!=null?Kn:"");n({type:"artifact_delta",id:j,artDelta:M});let Z=de.get(j);Z&&(Z.markdown+=M)}else if(Je==="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(Je==="artifact_complete"){let j=String(A.id);n({type:"artifact_complete",id:j});let M=ue.get(j);if(M){M.streaming=!1;try{let Z=JSON.parse((Fr=M.rawContent)!=null?Fr:"{}");if(Z.props){Z.props.status="complete";let ie=de.get(j);ie!=null&&ie.markdown&&(Z.props.markdown=ie.markdown)}M.rawContent=JSON.stringify(Z)}catch{}de.delete(j),f(M),ue.delete(j)}}}else if(Je==="transcript_insert"){let j=A.message;if(!j||typeof j!="object")continue;let M=String((ct=j.id)!=null?ct:`msg-${l()}`),Z=j.role,G={id:M,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(f(G),G.rawContent)try{let ke=JSON.parse(G.rawContent),Fe=($s=ke==null?void 0:ke.props)==null?void 0:$s.artifactId;typeof Fe=="string"&&V.add(Fe)}catch{}m=null,x.current=null,ne.delete(M),ce.delete(M)}else if(Je==="error"||Je==="step_error"||Je==="dispatch_error"||Je==="flow_error"){let j=null;if(A.error instanceof Error)j=A.error;else if(Je==="dispatch_error"){let M=(Mo=A.message)!=null?Mo:A.error;M!=null&&M!==""&&(j=new Error(String(M)))}else if(Je==="step_error"||Je==="flow_error"){let M=A.error;typeof M=="string"&&M!==""?j=new Error(M):M!=null&&typeof M=="object"&&"message"in M&&(j=new Error(String((Cr=M.message)!=null?Cr:M)))}else Je==="error"&&A.error!=null&&A.error!==""&&(j=new Error(String(A.error)));if(j){n({type:"error",error:j});let M=m;M&&M.streaming&&(M.streaming=!1,f(M)),n({type:"status",status:"idle"})}}}}}fe.length=0};;){let{done:F,value:Ee}=await s.read();if(F)break;a+=o.decode(Ee,{stream:!0});let De=a.split(`
|
|
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,`
|
|
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(`
|
|
10
10
|
|
|
11
|
-
`);a=(
|
|
12
|
-
`),mt="message",at="";for(let z of _e)z.startsWith("event:")?mt=z.replace("event:","").trim():z.startsWith("data:")&&(at+=z.replace("data:","").trim());if(!at)continue;let It;try{It=JSON.parse(at)}catch(z){n({type:"error",error:z instanceof Error?z:new Error("Failed to parse chat stream payload")});continue}let Kt=mt!=="message"?mt:(er=It.type)!=null?er:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,Kt,It),this.parseSSEEvent){x.current=m;let z=await this.handleCustomSSEEvent(It,n,x,f,l,w);if(x.current&&x.current!==m&&(m=x.current),z)continue}he.push(Kt,It),$e()}}he.flushPending(),$e(),he.destroy()}};function mu(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function cs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Fo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Xa="[Image]";function gu(e){return typeof e=="string"?[{type:"text",text:e}]:e}function fu(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function hu(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function bu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Js(e){return{type:"text",text:e}}function yu(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 xu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function vu(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 wu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Qg=["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"],Ur=[...wu,...Qg];function Yg(e){return wu.includes(e)||e.startsWith("image/")}function Qa(e){return Yg(e.type)}async function Cu(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Qa(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Au(e,t=Ur,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 Zg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Su(e,t){let n=Zg(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 Ya=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(n),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Za=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Gs=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 Za;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,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 B=T.code!==1006?` (code ${T.code})`:"";x("WebSocket connection failed"+B+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(t.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(t.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ya(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(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(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),s=this.getFormatFromMimeType(t.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];n(a)},s.onerror=r,s.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let l=0;l<n.length;l++)r[l]=n.charCodeAt(l);let s=t.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var $o=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function _o(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Gs(e.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ei(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return _o({type:"runtype",runtype:e.runtype});if($o.isSupported())return _o({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Xs(e){try{return ei(e),!0}catch{return!1}}function Tu(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=(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}
|
|
13
13
|
|
|
14
|
-
_Details: ${n.message}_`:r}var Qs=e=>({isError:!0,content:[{type:"text",text:e}]}),Eu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ds=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,r,s,o,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&po(p.name)&&this.enqueueWebMcpAwait(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Oo(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Xs((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,r,s;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=_o(o);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,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(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,s,o,a,i,d,l,p;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:((s=t.runtype)==null?void 0:s.clientToken)||"",host:(o=t.runtype)==null?void 0:o.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(p=t.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Oo(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,m={id:a!=null?a:n==="user"?cs():n==="assistant"?Fo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...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:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:m}=r,x={id:d!=null?d:s==="user"?cs():s==="assistant"?Fo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming: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:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,l={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,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 s=cs(),o=Fo(),a={id:s,role:"user",content:r||Xa,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let w=Tu(v,this.config.errorMessage);if(w){let T={id:o,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 s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=Fo();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=Tu(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=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,m,v;let s=`approval-${t.id}`,o={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===s),i={id:s,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:o};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(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,m,v,x,w,T,B,k,P,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 s=(u=t.agentMetadata)==null?void 0:u.executionId,o=(f=t.toolCall)==null?void 0:f.name;if(!s||!o){(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,I=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(I.length===1){let $=typeof((w=I[0])==null?void 0:w.question)=="string"?I[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=(B=t.toolCall)==null?void 0:B.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(([I,$])=>`${I}: ${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((I,$)=>{let D=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!D)return;let R=S[D],q=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${$}`,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${$}`,role:"user",content:q||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(s,{[o]:n});if(!S.ok){let I=await S.json().catch(()=>null);throw new Error((k=I==null?void 0:I.error)!=null?k:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let I=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(W=(P=this.callbacks).onError)==null||W.call(P,S instanceof Error?S:new Error(String(S)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var s,o;let n=this.messages.find(a=>a.id===t.id),r=[(s=n==null?void 0:n.toolCall)==null?void 0:s.startedAt,(o=t.toolCall)==null?void 0:o.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,s=Date.now()){this.messages.some(o=>o.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:s,duration:void 0,durationMs:Math.max(0,s-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var P,W,S,I,$,D,R;let f=(P=u.toolCall)==null?void 0:P.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),s.push(w);let T=(I=(S=u.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?I:f,B=this.client.executeWebMcpToolCall(f,($=u.toolCall)==null?void 0:$.args,w.signal),k;if(!B)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await B}catch(q){let K=q instanceof Error&&(q.name==="AbortError"||q.message.includes("aborted")||q.message.includes("abort"));return K||(R=(D=this.callbacks).onError)==null||R.call(D,q instanceof Error?q:new Error(String(q))),this.markWebMcpToolComplete(u,Qs(K?"Aborted by cancel()":Eu(q)),x),this.webMcpInflightKeys.delete(v),null}return w.signal.aborted?(this.markWebMcpToolComplete(u,Qs("Aborted by cancel()"),x),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:k,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:o.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,Qs("Aborted by cancel()"),m.startedAt)}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of s)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var m,v,x,w,T,B,k,P,W,S,I,$;let n=(m=t.agentMetadata)==null?void 0:m.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(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(!s){let D=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(D)||this.webMcpResolvedKeys.has(D))return;this.webMcpInflightKeys.add(D);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(D)}catch(R){(k=(B=this.callbacks).onError)==null||k.call(B,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(D)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(P=t.toolCall)==null?void 0:P.args,p=this.client.executeWebMcpToolCall(r,l,d),u="execute",f=a;try{let D;if(p?D=await p:D={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Qs("Aborted by cancel()"),a);return}let R=(S=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?S:r;u="resume",await this.resumeWithToolOutput(n,R,D,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,D,a,f)},signal:d})}catch(D){let R=D instanceof Error&&(D.name==="AbortError"||D.message.includes("aborted")||D.message.includes("abort"));(u==="execute"||R||d.aborted)&&this.markWebMcpToolComplete(t,Qs(R||d.aborted?"Aborted by cancel()":Eu(D)),a),R||($=(I=this.callbacks).onError)==null||$.call(I,D instanceof Error?D:new Error(String(D)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t),o=r.getVoices();if(n.voice){let a=o.find(i=>i.name===n.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=n.pickVoice?n.pickVoice(o):e.pickBestVoice(o));n.rate!==void 0&&(s.rate=n.rate),n.pitch!==void 0&&(s.pitch=n.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(t){var r;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of n){let o=t.find(a=>a.name===s);if(o)return o}return(r=t.find(s=>s.lang.startsWith("en")))!=null?r:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,u,f,m,v,x,w,T,B,k;if(o!==r)return s;let a={...s,...n};((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(u=n.toolCall)==null?void 0:u.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(m=n.toolCall)==null?void 0:m.id;if(i&&po(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let P=`${d}:${l}`,W=this.webMcpInflightKeys.has(P),S=this.webMcpResolvedKeys.has(P),I=(x=s.toolCall)==null?void 0:x.name,$=((w=s.agentMetadata)==null?void 0:w.executionId)===d&&((T=s.toolCall)==null?void 0:T.id)===l&&I!==void 0&&po(I)&&((B=s.toolCall)==null?void 0:B.status)==="complete";(W||S||$)&&(a.agentMetadata={...(k=a.agentMetadata)!=null?k:{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.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 s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Pr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var C=require("lucide"),ef={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},we=(e,t=24,n="currentColor",r=2)=>{let s=ef[e];return s?tf(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function tf(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),s.appendChild(d)}),s}var ti={allowedTypes:Ur,maxFileSize:10*1024*1024,maxFiles:4};function nf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function rf(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 jo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ti.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ti.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:ti.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:ti.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,s,o,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=Au(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,u);continue}try{let u=await Cu(l),f=Qa(l)?URL.createObjectURL(l):null,m={id:nf(),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 o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Qa(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=rf(t.file.type),d=we(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Su(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=we("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Mu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ys(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];Mu(o)&&Mu(s)?n[r]=Ys(o,s):n[r]=s}return n}var Yn="min(440px, calc(100vw - 24px))",ni="440px",$t={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:Yn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ku(e,t){if(!(!e&&!t))return e?t?Ys(e,t):e:t}function ri(e){var t,n,r,s,o,a,i,d,l,p,u,f,m,v,x,w,T,B,k,P,W;return e?{...$t,...e,theme:ku($t.theme,e.theme),darkTheme:ku($t.darkTheme,e.darkTheme),launcher:{...$t.launcher,...e.launcher,dock:{...(t=$t.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=$t.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...$t.copy,...e.copy},sendButton:{...$t.sendButton,...e.sendButton},statusIndicator:{...$t.statusIndicator,...e.statusIndicator},voiceRecognition:{...$t.voiceRecognition,...e.voiceRecognition},features:(()=>{var be,Be,Pe,J,ue,V,de,le;let S=(be=$t.features)==null?void 0:be.artifacts,I=(Be=e.features)==null?void 0:Be.artifacts,$=(Pe=$t.features)==null?void 0:Pe.scrollToBottom,D=(J=e.features)==null?void 0:J.scrollToBottom,R=(ue=$t.features)==null?void 0:ue.streamAnimation,q=(V=e.features)==null?void 0:V.streamAnimation,K=(de=$t.features)==null?void 0:de.askUserQuestion,se=(le=e.features)==null?void 0:le.askUserQuestion,Re=S===void 0&&I===void 0?void 0:{...S,...I,layout:{...S==null?void 0:S.layout,...I==null?void 0:I.layout}},Ge=$===void 0&&D===void 0?void 0:{...$,...D},Ce=R===void 0&&q===void 0?void 0:{...R,...q},He=K===void 0&&se===void 0?void 0:{...K,...se,styles:{...K==null?void 0:K.styles,...se==null?void 0:se.styles}};return{...$t.features,...e.features,...Ge!==void 0?{scrollToBottom:Ge}:{},...Re!==void 0?{artifacts:Re}:{},...Ce!==void 0?{streamAnimation:Ce}:{},...He!==void 0?{askUserQuestion:He}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:$t.suggestionChips,suggestionChipsConfig:{...$t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...$t.layout,...e.layout,header:{...(a=$t.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=$t.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=$t.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=$t.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:{...(B=$t.layout)==null?void 0:B.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...$t.markdown,...e.markdown,options:{...(P=$t.markdown)==null?void 0:P.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...$t.messageActions,...e.messageActions}}:$t}var ol={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"}},sl={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"}},al={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:Yn,maxWidth:ni,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 ps(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ps(e,r):r}function oi(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=ps(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function il(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 Lu(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=Lu(o,s):n[r]=s}return n}function of(e,t){return t?Lu(e,t):e}function us(e,t={}){var s,o,a,i,d,l,p,u,f,m,v,x,w;let n={palette:ol,semantic:sl,components:al},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(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=il(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(B=>B.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function si(e){var x,w,T,B,k,P,W,S,I,$,D,R,q,K,se,Re,Ge,Ce,He,be,Be,Pe,J,ue,V,de,le,ae,Se,ze,Y,ne,ce,xe,me,oe,Ze,We,fe,X,$e,Ht,he,pe,Pn,Ut,gn,Bn,er,Ue,F,Ee,De,Ne,_e,mt,at,It,Kt,z,qt,et,_t,re,ve,Et,Jt,nn,Cn,Wt,kt,wt,At,Gt,ot,Dn,tr,An,Nn,bt,Er,On,Co,In,Go,Gr,Wr,St,Fn,$n,Sn,Lt,nr,rr,_n,Xr,Rr,Qr,jn,Dt,Tn,or,Yr,Hr,Zr,Mr,Un,hr,xt,Qt,Yt,qn,eo,sr,br,zn,_,ar;let t=oi(e),n={};for(let[ye,Vn]of Object.entries(t)){let ir=ye.replace(/\./g,"-");n[`--persona-${ir}`]=Vn.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"]=(B=n["--persona-semantic-colors-surface"])!=null?B: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"]=(P=n["--persona-semantic-colors-container"])!=null?P: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"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=($=n["--persona-semantic-colors-border"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(D=n["--persona-semantic-colors-divider"])!=null?D:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(R=n["--persona-components-voice-recording-indicator"])!=null?R:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(q=n["--persona-components-voice-recording-background"])!=null?q:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(K=n["--persona-components-voice-processing-icon"])!=null?K:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(se=n["--persona-components-voice-speaking-icon"])!=null?se:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Re=n["--persona-components-approval-requested-background"])!=null?Re:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Ge=n["--persona-components-approval-requested-border"])!=null?Ge:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ce=n["--persona-components-approval-requested-text"])!=null?Ce:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(He=n["--persona-components-approval-requested-shadow"])!=null?He:"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"]=(Be=n["--persona-components-approval-deny-background"])!=null?Be:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Pe=n["--persona-components-attachment-image-background"])!=null?Pe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(J=n["--persona-components-attachment-image-border"])!=null?J:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ue=n["--persona-semantic-typography-fontFamily"])!=null?ue:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(V=n["--persona-semantic-typography-fontSize"])!=null?V:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(de=n["--persona-semantic-typography-fontWeight"])!=null?de:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(le=n["--persona-semantic-typography-lineHeight"])!=null?le: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"]=(ae=n["--persona-palette-radius-sm"])!=null?ae:"0.125rem",n["--persona-radius-md"]=(Se=n["--persona-palette-radius-md"])!=null?Se:"0.375rem",n["--persona-radius-lg"]=(ze=n["--persona-palette-radius-lg"])!=null?ze:"0.5rem",n["--persona-radius-xl"]=(Y=n["--persona-palette-radius-xl"])!=null?Y:"0.75rem",n["--persona-radius-full"]=(ne=n["--persona-palette-radius-full"])!=null?ne:"9999px",n["--persona-launcher-radius"]=(xe=(ce=n["--persona-components-launcher-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?xe:"9999px",n["--persona-launcher-bg"]=(me=n["--persona-components-launcher-background"])!=null?me:n["--persona-primary"],n["--persona-launcher-fg"]=(oe=n["--persona-components-launcher-foreground"])!=null?oe:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ze=n["--persona-components-launcher-border"])!=null?Ze:n["--persona-border"],n["--persona-button-primary-bg"]=(We=n["--persona-components-button-primary-background"])!=null?We:n["--persona-primary"],n["--persona-button-primary-fg"]=(fe=n["--persona-components-button-primary-foreground"])!=null?fe:n["--persona-text-inverse"],n["--persona-button-radius"]=($e=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?$e:"9999px",n["--persona-panel-radius"]=(he=(Ht=n["--persona-components-panel-borderRadius"])!=null?Ht:n["--persona-radius-xl"])!=null?he:"0.75rem",n["--persona-panel-border"]=(pe=n["--persona-components-panel-border"])!=null?pe:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ut=(Pn=n["--persona-components-panel-shadow"])!=null?Pn:n["--persona-palette-shadows-xl"])!=null?Ut:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(gn=n["--persona-components-launcher-shadow"])!=null?gn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(er=(Bn=n["--persona-components-input-borderRadius"])!=null?Bn:n["--persona-radius-lg"])!=null?er:"0.5rem",n["--persona-message-user-radius"]=(F=(Ue=n["--persona-components-message-user-borderRadius"])!=null?Ue:n["--persona-radius-lg"])!=null?F:"0.5rem",n["--persona-message-assistant-radius"]=(De=(Ee=n["--persona-components-message-assistant-borderRadius"])!=null?Ee:n["--persona-radius-lg"])!=null?De:"0.5rem",n["--persona-header-bg"]=(Ne=n["--persona-components-header-background"])!=null?Ne:n["--persona-surface"],n["--persona-header-border"]=(_e=n["--persona-components-header-border"])!=null?_e:n["--persona-divider"],n["--persona-header-icon-bg"]=(mt=n["--persona-components-header-iconBackground"])!=null?mt: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"]=(It=n["--persona-components-header-titleForeground"])!=null?It: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"]=(z=n["--persona-components-header-actionIconForeground"])!=null?z:n["--persona-muted"];let r=(qt=e.components)==null?void 0:qt.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(et=e.components)==null?void 0:et.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(re=n["--persona-components-introCard-borderRadius"])!=null?re:"1rem",n["--persona-intro-card-padding"]=(ve=n["--persona-components-introCard-padding"])!=null?ve:"1.5rem",n["--persona-intro-card-shadow"]=(Jt=(Et=s==null?void 0:s.shadow)!=null?Et:n["--persona-components-introCard-shadow"])!=null?Jt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(nn=n["--persona-components-input-background"])!=null?nn:n["--persona-surface"],n["--persona-input-placeholder"]=(Cn=n["--persona-components-input-placeholder"])!=null?Cn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Wt=n["--persona-components-message-user-background"])!=null?Wt:n["--persona-accent"],n["--persona-message-user-text"]=(kt=n["--persona-components-message-user-text"])!=null?kt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(wt=n["--persona-components-message-user-shadow"])!=null?wt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(At=n["--persona-components-message-assistant-background"])!=null?At:n["--persona-surface"],n["--persona-message-assistant-text"]=(Gt=n["--persona-components-message-assistant-text"])!=null?Gt:n["--persona-text"],n["--persona-message-assistant-border"]=(ot=n["--persona-components-message-assistant-border"])!=null?ot:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Dn=n["--persona-components-message-assistant-shadow"])!=null?Dn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(An=(tr=n["--persona-components-scrollToBottom-background"])!=null?tr:n["--persona-button-primary-bg"])!=null?An:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(bt=(Nn=n["--persona-components-scrollToBottom-foreground"])!=null?Nn:n["--persona-button-primary-fg"])!=null?bt:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Er=n["--persona-components-scrollToBottom-border"])!=null?Er:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(On=n["--persona-components-scrollToBottom-size"])!=null?On:"40px",n["--persona-scroll-to-bottom-radius"]=(Go=(In=(Co=n["--persona-components-scrollToBottom-borderRadius"])!=null?Co:n["--persona-button-radius"])!=null?In:n["--persona-radius-full"])!=null?Go:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Wr=(Gr=n["--persona-components-scrollToBottom-shadow"])!=null?Gr:n["--persona-palette-shadows-sm"])!=null?Wr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(St=n["--persona-components-scrollToBottom-padding"])!=null?St:"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"]=(Sn=($n=n["--persona-components-scrollToBottom-fontSize"])!=null?$n:n["--persona-palette-typography-fontSize-sm"])!=null?Sn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Lt=n["--persona-components-scrollToBottom-iconSize"])!=null?Lt:"14px",n["--persona-tool-bubble-shadow"]=(nr=n["--persona-components-toolBubble-shadow"])!=null?nr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(rr=n["--persona-components-reasoningBubble-shadow"])!=null?rr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(_n=n["--persona-components-composer-shadow"])!=null?_n:"none",n["--persona-md-inline-code-bg"]=(Xr=n["--persona-components-markdown-inlineCode-background"])!=null?Xr:n["--persona-container"],n["--persona-md-inline-code-color"]=(Rr=n["--persona-components-markdown-inlineCode-foreground"])!=null?Rr:n["--persona-text"],n["--persona-md-link-color"]=(jn=(Qr=n["--persona-components-markdown-link-foreground"])!=null?Qr:n["--persona-accent"])!=null?jn:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(Dt=n["--persona-components-markdown-codeBlock-background"])!=null?Dt:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Tn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Tn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(or=n["--persona-components-markdown-codeBlock-textColor"])!=null?or:"inherit",n["--persona-md-table-header-bg"]=(Yr=n["--persona-components-markdown-table-headerBackground"])!=null?Yr:n["--persona-container"],n["--persona-md-table-border-color"]=(Hr=n["--persona-components-markdown-table-borderColor"])!=null?Hr:n["--persona-border"],n["--persona-md-hr-color"]=(Zr=n["--persona-components-markdown-hr-color"])!=null?Zr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Mr=n["--persona-components-markdown-blockquote-borderColor"])!=null?Mr:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Un=n["--persona-components-markdown-blockquote-background"])!=null?Un:"transparent",n["--persona-md-blockquote-text-color"]=(hr=n["--persona-components-markdown-blockquote-textColor"])!=null?hr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(xt=n["--persona-components-collapsibleWidget-container"])!=null?xt:n["--persona-surface"],n["--cw-surface"]=(Qt=n["--persona-components-collapsibleWidget-surface"])!=null?Qt:n["--persona-surface"],n["--cw-border"]=(Yt=n["--persona-components-collapsibleWidget-border"])!=null?Yt:n["--persona-border"],n["--persona-message-border"]=(qn=n["--persona-components-message-border"])!=null?qn: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"]=(eo=n["--persona-dropdown-bg"])!=null?eo:ye.copyMenuBackground),ye.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,n["--persona-dropdown-border"]=(sr=n["--persona-dropdown-border"])!=null?sr:ye.copyMenuBorder),ye.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,n["--persona-dropdown-shadow"]=(br=n["--persona-dropdown-shadow"])!=null?br:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(zn=n["--persona-dropdown-radius"])!=null?zn:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(_=n["--persona-dropdown-item-hover-bg"])!=null?_: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 Vn=(ar=ps(e,ye.toolbarBackground))!=null?ar:ye.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Vn}}return n}var Pu={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 sf={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"}}},Iu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Zs=()=>{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"},af=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Zs()},ll=e=>af(e),lf=e=>us(e),cf=e=>{var n;let t=us(void 0,{validate:!1});return us({...e,palette:{...t.palette,colors:{...sf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ms=e=>{let t=ll(e),n=Iu(e==null?void 0:e.theme),r=Iu(e==null?void 0:e.darkTheme);return t==="dark"?cf(Ys(n!=null?n:{},r!=null?r:{})):lf(n)},df=e=>si(e),uo=(e,t)=>{let n=ms(t),r=df(n);for(let[s,o]of Object.entries(r))e.style.setProperty(s,o)},ai=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Zs())});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(Zs());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 Wu=require("idiomorph"),ii=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Wu.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var li={index:-1,draft:""};function Ru(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...li}}}function Hu(e,t){var n,r,s,o,a,i,d,l,p,u,f,m,v,x,w,T,B,k,P,W,S,I,$,D,R,q,K,se,Re,Ge,Ce,He,be,Be,Pe,J,ue,V;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(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:"",(k=(B=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:B.length)!=null?k:0,(I=(S=(W=(P=e.toolCall)==null?void 0:P.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?I:"",typeof(($=e.toolCall)==null?void 0:$.args)=="string"?e.toolCall.args.length:(D=e.toolCall)!=null&&D.args?JSON.stringify(e.toolCall.args).length:0,(K=(q=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:q.length)!=null?K:0,(Ce=(Ge=(Re=(se=e.reasoning)==null?void 0:se.chunks)==null?void 0:Re[e.reasoning.chunks.length-1])==null?void 0:Ge.length)!=null?Ce:0,(Pe=(Be=(be=(He=e.reasoning)==null?void 0:He.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Be.slice(-32))!=null?Pe:"",(ue=(J=e.contentParts)==null?void 0:J.length)!=null?ue:0,(V=e.stopReason)!=null?V:"",t].join("\0")}function Bu(){return new Map}function Du(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Nu(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Ou(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ci(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function ea(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ta(e,t){return ea(e)-e.scrollTop<=t}function di(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function pi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}var vn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,mo=wn+1;var na={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},pf=["pre","code","a","script","style"],ui=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:na.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:na.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:na.speed,duration:(s=e==null?void 0:e.duration)!=null?s:na.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:na.buffer}},$u=[{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"}],ra=new Map;for(let e of $u)ra.set(e.name,e);var _u=e=>{ra.set(e.name,e)},ju=e=>{$u.some(t=>t.name===e)||ra.delete(e)},Uu=()=>Array.from(ra.keys()),oa=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=ra.get(e))!=null?r:null},mi=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
|
|
15
|
-
`);return
|
|
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=`
|
|
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 Qs=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=o=>{var k,P,W,S,I,$,D,R,q,K,se,Re,Ge;let a=(k=o.launcher)!=null?k:{},i=ln(o),d=n.querySelector("[data-role='launcher-title']");if(d){let Ce=(P=a.title)!=null?P:"Chat Assistant";d.textContent=Ce,d.setAttribute("title",Ce)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let Ce=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=Ce,l.setAttribute("title",Ce)}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 Ce=(S=a.agentIconSize)!=null?S:"40px";if(u.style.height=Ce,u.style.width=Ce,u.innerHTML="",a.agentIconName){let He=parseFloat(Ce)||24,be=we(a.agentIconName,He*.6,"var(--persona-text-inverse, #ffffff)",2);be?(u.appendChild(be),u.style.display=""):(u.textContent=(I=a.agentIconText)!=null?I:"\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 Ce=(D=a.agentIconSize)!=null?D:"40px";f.style.height=Ce,f.style.width=Ce,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 Ce=(R=a.callToActionIconSize)!=null?R:"32px";m.style.height=Ce,m.style.width=Ce,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 He=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,He=(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(Ce)||24,Be=Math.max(be-He,8),Pe=we(a.callToActionIconName,Be,"currentColor",2);Pe?m.appendChild(Pe):m.textContent=(q=a.callToActionIconText)!=null?q:"\u2197"}else m.textContent=(K=a.callToActionIconText)!=null?K:"\u2197"}let v=a.position&&Tr[a.position]?Tr[a.position]:Tr["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((se=a.zIndex)!=null?se:wn));let T="1px solid var(--persona-border, #e5e7eb)",B="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=(Re=a.border)!=null?Re:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:B,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(Ge=a.collapsedMaxWidth)!=null?Ge:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var xf="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",hi=(e,t={})=>{var x,w,T,B,k,P;let{showClose:n=!0,wrapperClassName:r=xf,buttonSize:s,iconSize:o="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(w=s!=null?s: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=(B=a.closeButtonShowTooltip)!=null?B:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let f=(k=a.closeButtonIconName)!=null?k:"x",m=(P=a.closeButtonIconText)!=null?P:"\xD7";l.style.color=a.closeButtonColor||Ln.actionIconColor;let v=we(f,o,"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,D=$.body;if(!D)return;W=Pr($,"div","persona-clear-chat-tooltip"),W.textContent=p;let R=Pr($,"div");R.className="persona-clear-chat-tooltip-arrow",W.appendChild(R);let q=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(mo),W.style.left=`${q.left+q.width/2}px`,W.style.top=`${q.top-8}px`,W.style.transform="translate(-50%, -100%)",D.appendChild(W)},I=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",S),d.addEventListener("mouseleave",I),l.addEventListener("focus",S),l.addEventListener("blur",I),d._cleanupTooltip=()=>{I(),d.removeEventListener("mouseenter",S),d.removeEventListener("mouseleave",I),l.removeEventListener("focus",S),l.removeEventListener("blur",I)}}return{button:l,wrapper:d}},vf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",bi=(e,t={})=>{var W,S,I,$,D,R,q,K,se,Re,Ge,Ce,He;let{wrapperClassName:n=vf,buttonSize:r,iconSize:s="20px"}=t,a=(S=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?S:{},i=(I=r!=null?r:a.size)!=null?I:"32px",d=($=a.iconName)!=null?$:"refresh-cw",l=(D=a.iconColor)!=null?D:"",p=(R=a.backgroundColor)!=null?R:"",u=(q=a.borderWidth)!=null?q:"",f=(K=a.borderColor)!=null?K:"",m=(se=a.borderRadius)!=null?se:"",v=(Re=a.paddingX)!=null?Re:"",x=(Ge=a.paddingY)!=null?Ge:"",w=(Ce=a.tooltipText)!=null?Ce:"Clear chat",T=(He=a.showTooltip)!=null?He:!0,B=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||Ln.actionIconColor;let P=we(d,s,"currentColor",1);if(P&&(P.style.display="block",k.appendChild(P)),p&&(k.style.backgroundColor=p,k.classList.remove("hover:persona-bg-gray-100")),u||f){let be=u||"0px",Be=f||"transparent";k.style.border=`${be} solid ${Be}`,k.classList.remove("persona-border-none")}if(m&&(k.style.borderRadius=m,k.classList.remove("persona-rounded-full")),v&&(k.style.paddingLeft=v,k.style.paddingRight=v),x&&(k.style.paddingTop=x,k.style.paddingBottom=x),B.appendChild(k),T&&w){let be=null,Be=()=>{if(be)return;let J=k.ownerDocument,ue=J.body;if(!ue)return;be=Pr(J,"div","persona-clear-chat-tooltip"),be.textContent=w;let V=Pr(J,"div");V.className="persona-clear-chat-tooltip-arrow",be.appendChild(V);let de=k.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(mo),be.style.left=`${de.left+de.width/2}px`,be.style.top=`${de.top-8}px`,be.style.transform="translate(-50%, -100%)",ue.appendChild(be)},Pe=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};B.addEventListener("mouseenter",Be),B.addEventListener("mouseleave",Pe),k.addEventListener("focus",Be),k.addEventListener("blur",Pe),B._cleanupTooltip=()=>{Pe(),B.removeEventListener("mouseenter",Be),B.removeEventListener("mouseleave",Pe),k.removeEventListener("focus",Be),k.removeEventListener("blur",Pe)}}return{button:k,wrapper:B}};var Ln={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,I,$,D,R,q,K,se,Re,Ge,Ce,He,be,Be,Pe;let{config:t,showClose:n=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(W=t==null?void 0:t.launcher)!=null?W:{},o=(S=s.headerIconSize)!=null?S:"48px",a=(I=s.closeButtonPlacement)!=null?I:"inline",i=($=s.headerIconHidden)!=null?$:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let J=parseFloat(o)||24,ue=we(d,J*.6,"currentColor",1);ue?l.replaceChildren(ue):l.textContent=(R=(D=t==null?void 0:t.launcher)==null?void 0:D.agentIconText)!=null?R:"\u{1F4AC}"}else if((q=t==null?void 0:t.launcher)!=null&&q.iconUrl){let J=h("img");J.src=t.launcher.iconUrl,J.alt="",J.className="persona-rounded-xl persona-object-cover",J.style.height=o,J.style.width=o,l.replaceChildren(J)}else l.textContent=(se=(K=t==null?void 0:t.launcher)==null?void 0:K.agentIconText)!=null?se:"\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=Ln.titleColor,u.textContent=(Ge=(Re=t==null?void 0:t.launcher)==null?void 0:Re.title)!=null?Ge:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Ln.subtitleColor,f.textContent=(He=(Ce=t==null?void 0:t.launcher)==null?void 0:Ce.subtitle)!=null?He:"Here to help you get answers fast",p.append(u,f),i?r.append(p):r.append(l,p);let m=(be=s.clearChat)!=null?be:{},v=(Be=m.enabled)!=null?Be:!0,x=(Pe=m.placement)!=null?Pe:"inline",w=null,T=null;if(v){let ue=bi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=ue.button,T=ue.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let B=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:P}=hi(t,{showClose:n,wrapperClassName:B});return a!=="top-right"&&r.appendChild(P),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:k,closeButtonWrapper:P,clearChatButton:w,clearChatButtonWrapper:T}},Uo=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function ho(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(mo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of 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=we(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(!o)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function 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 o&&o.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:f}}function Vt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=we(t,r!=null?r:16,"currentColor",s!=null?s: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 ca(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let p=h("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let f=we(t,o!=null?o: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 da(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let 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}),o.appendChild(u)}function l(p){a=p,d()}return{element:o,setSelected:l}}function yi(e){var m,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=h("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=we(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=ho({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,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 gl=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 s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function wf(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=we(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=ho({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 fl=e=>{var B,k,P,W,S,I,$,D,R;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(B=t==null?void 0:t.launcher)!=null?B:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,p;if(d)l=yi({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Ln.titleColor,p=(P=l.querySelector(".persona-combo-btn-label"))!=null?P: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=Ln.titleColor,p.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(p),wf(l,s==null?void 0:s.trailingActions,(S=s==null?void 0:s.onAction)!=null?S:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let K=s.onTitleClick;l.addEventListener("click",se=>{se.target.closest("button")||K()}),l.addEventListener("keydown",se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),K())})}let q=s==null?void 0:s.titleRowHover;q&&(l.style.borderRadius=(I=q.borderRadius)!=null?I:"10px",l.style.padding=($=q.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 K,se;l.style.backgroundColor=(K=q.background)!=null?K:"",l.style.borderColor=(se=q.border)!=null?se:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(D=a.closeButtonSize)!=null?D:"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||Ln.actionIconColor;let v=(R=a.closeButtonIconName)!=null?R:"x",x=we(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}},xi={default:gl,minimal:fl},hl=e=>{var t;return(t=xi[e])!=null?t:xi.default},gs=(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",o=hl(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var vi=e=>{var a,i;let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:o}},wi=e=>{var W,S,I,$,D,R,q,K,se,Re,Ge,Ce;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(S=t.useIcon)!=null?S:!1,r=(I=t.iconText)!=null?I:"\u2191",s=t.iconName,o=($=t.stopIconName)!=null?$:"square",a=(D=t.tooltipText)!=null?D:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",d=(K=(q=e==null?void 0:e.copy)==null?void 0:q.sendButtonLabel)!=null?K:"Send",l=(Re=(se=e==null?void 0:e.copy)==null?void 0:se.stopButtonLabel)!=null?Re:"Stop",p=(Ge=t.showTooltip)!=null?Ge:!1,u=(Ce=t.size)!=null?Ce:"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 He=parseFloat(u)||24,be=(m==null?void 0:m.trim())||"currentColor";s?(w=we(s,He,be,2),w?x.appendChild(w):x.textContent=r):x.textContent=r,T=we(o,He,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 B=null;p&&a&&(B=h("div","persona-send-button-tooltip"),B.textContent=a,v.appendChild(B)),x.setAttribute("aria-label",a),v.appendChild(x);let k="send";return{button:x,wrapper:v,setMode:He=>{if(He===k)return;k=He;let be=He==="stop"?i:a;if(x.setAttribute("aria-label",be),B&&(B.textContent=be),n){if(w&&T){let Be=He==="stop"?T:w;x.replaceChildren(Be)}}else x.textContent=He==="stop"?l:d}}},Ci=e=>{var B,k,P,W,S,I,$,D,R,q,K,se;let t=(B=e==null?void 0:e.voiceRecognition)!=null?B:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(r||s))return null;let a=(W=(P=e==null?void 0:e.sendButton)==null?void 0:P.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=(I=t.iconSize)!=null?I:a,u=parseFloat(p)||24,f=(D=t.backgroundColor)!=null?D:($=e==null?void 0:e.sendButton)==null?void 0:$.backgroundColor,m=(q=t.iconColor)!=null?q:(R=e==null?void 0:e.sendButton)==null?void 0:R.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=we(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=(K=t.tooltipText)!=null?K:"Start voice recognition";if(((se=t.showTooltip)!=null?se:!1)&&w){let Re=h("div","persona-send-button-tooltip");Re.textContent=w,i.appendChild(Re)}return{button:d,wrapper:i}},Ai=e=>{var v,x,w,T,B,k,P,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 s=h("input");s.type="file",s.accept=((T=t.allowedTypes)!=null?T:Ur).join(","),s.multiple=((B=t.maxFiles)!=null?B:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(k=t.buttonTooltipText)!=null?k:"Attach file");let i=(P=t.buttonIconName)!=null?P:"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=we(i,p,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",S=>{S.preventDefault(),s.click()}),o.appendChild(a);let f=(W=t.buttonTooltipText)!=null?W:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,o.appendChild(m),{button:a,wrapper:o,input:s,previewsContainer:r}},Si=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=h("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},Ti=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var fs=e=>{var v,x,w,T,B,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=Ti(),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=vi(t);a();let i=wi(t),d=Ci(t),l=Ai(t),p=Si(t);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);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),s.append(u),s.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(l==null?void 0:l.button)&&P.target!==(l==null?void 0:l.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var zu=()=>{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=we("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=we("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},Vu=e=>{var v,x,w,T,B,k;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=Ti();r.style.display="none";let s=Si(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=vi(t);o.style.maxHeight="100px",a();let i=wi(t),d=Ci(t),l=Ai(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",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(l==null?void 0:l.button)&&P.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&p.append(l.input),p.append(u,o,f),l&&n.append(l.previewsContainer),n.append(p,r,s);let m=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(w=l==null?void 0:l.button)!=null?w:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(B=l==null?void 0:l.input)!=null?B:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:m,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var Ku=e=>{var p,u,f,m,v,x,w,T,B,k,P,W,S,I,$,D,R;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=ln(e);if(fo(e)){let q=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},K=h("div","persona-widget-wrapper persona-fixed persona-transition");K.setAttribute("data-persona-composer-bar",""),K.dataset.state="collapsed",K.dataset.expandedSize=(v=q.expandedSize)!=null?v:"anchored",K.style.zIndex=String((w=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?w:wn);let se=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");se.style.width="100%",K.appendChild(se);let Re=h("div","persona-widget-pill-root");return Re.setAttribute("data-persona-composer-bar",""),Re.dataset.state="collapsed",Re.dataset.expandedSize=(T=q.expandedSize)!=null?T:"anchored",Re.style.zIndex=String((k=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?k:wn),{wrapper:K,panel:se,pillRoot:Re}}if(n){let q=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),K=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return q.appendChild(K),{wrapper:q,panel:K}}if(!t){let q=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),K=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),se=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.width)!=null?W:"100%";return q.style.width=se,K.style.width="100%",q.appendChild(K),{wrapper:q,panel:K}}let s=(S=e==null?void 0:e.launcher)!=null?S:{},o=s.position&&Tr[s.position]?Tr[s.position]:Tr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String(($=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?$:wn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?R:e==null?void 0:e.launcherWidth,l=d!=null?d:Yn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Cf=(e,t)=>{var P,W,S,I,$,D,R,q,K;let n=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=hi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(S=(W=(P=e==null?void 0:e.launcher)==null?void 0:P.clearChat)==null?void 0:W.enabled)!=null?S:!0,a=null,i=null;if(o){let se=bi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=se.button,i=se.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let u=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=($=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?$:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(R=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",p.append(u,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),v=(q=e==null?void 0:e.layout)==null?void 0:q.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((K=e==null?void 0:e.copy)==null?void 0:K.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=Vu({config:e}),{root:B,textNode:k}=zu();return n.append(d,s,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:s,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:B,peekTextNode:k}},Ju=(e,t=!0)=>{var w,T,B,k,P,W,S,I,$;if(fo(e))return Cf(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,s=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,o=r?gs(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");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=ln(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=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?k:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(P=e==null?void 0:e.copy)==null?void 0:P.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",""),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let m=fs({config:e}),v=(($=e==null?void 0:e.layout)==null?void 0:$.showFooter)!==!1;s?Uo(n,o,e):(o.header.style.display="none",Uo(n,o,e)),n.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(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:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.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 Af=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}},Sf=(e,t)=>{if(!e)return null;let n=Af(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},Tf=(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},Ef=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},bl=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(":"))},yl=320,Xu=320,Mf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),kf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Lf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Pf=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),If=(e,t,n)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var 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=`${yl}px`,l.style.maxHeight=`${Xu}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,l.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{p=!0}),Ef(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},Wf=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!bl(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${yl}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Rf=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(!bl(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${yl}px`,s.style.maxHeight=`${Xu}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Hf=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(!bl(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},qo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},xl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:qo};if(t){let s=t(r);if(s!==null)return s}return qo()},Bf=(e,t)=>{let n=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Gu=(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},Df=(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},vl=(e,t,n)=>{var m,v,x,w,T,B;let r=(m=t.showCopy)!=null?m:!0,s=(v=t.showUpvote)!=null?v:!0,o=(x=t.showDownvote)!=null?x:!0;if(!r&&!s&&!o){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=(T=t.align)!=null?T:"right",d=(B=t.layout)!=null?B:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],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,P,W)=>{let S=Vt({icon:k,label:P,size:14,className:"persona-message-action-btn"});return S.setAttribute("data-action",W),S};return r&&u.appendChild(f("copy","Copy message","copy")),s&&u.appendChild(f("thumbs-up","Upvote","upvote")),o&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},hs=(e,t,n,r,s,o)=>{var J,ue,V,de,le,ae,Se,ze,Y,ne,ce,xe,me,oe,Ze,We,fe;let a=n!=null?n:{},i=(J=a.layout)!=null?J:"bubble",d=a.avatar,l=a.timestamp,p=(ue=d==null?void 0:d.show)!=null?ue:!1,u=(V=l==null?void 0:l.show)!=null?V:!1,f=(de=d==null?void 0:d.position)!=null?de:"left",m=(le=l==null?void 0:l.position)!=null?le:"below",v=Df(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=Mf(e),T=(Se=(ae=e.content)==null?void 0:ae.trim())!=null?Se:"",k=w.length>0&&T===Xa,P=ui((Y=(ze=o==null?void 0:o.widgetConfig)==null?void 0:ze.features)==null?void 0:Y.streamAnimation),W=(xe=(ce=(ne=o==null?void 0:o.widgetConfig)==null?void 0:ne.features)==null?void 0:ce.streamAnimation)==null?void 0:xe.plugins,S=e.role==="assistant"&&P.type!=="none"?oa(P.type,W):null,I=e.role==="assistant"&&((me=S==null?void 0:S.isAnimating)==null?void 0:me.call(S,e))===!0,$=e.role==="assistant"&&S!==null&&(!!e.streaming||I);$&&(S!=null&&S.bubbleClass)&&x.classList.add(S.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),$&&S&&(S.containerClass&&D.classList.add(S.containerClass),D.style.setProperty("--persona-stream-step",`${P.speed}ms`),D.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let R=$?mi((oe=e.content)!=null?oe:"",P.buffer,S,e,!!e.streaming):(Ze=e.content)!=null?Ze:"",q=t({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),K=q;$&&(S==null?void 0:S.wrap)==="char"?K=sa(q,"char",e.id,{skipTags:S.skipTags}):$&&(S==null?void 0:S.wrap)==="word"&&(K=sa(q,"word",e.id,{skipTags:S.skipTags}));let se=null;if(k?(se=document.createElement("div"),se.innerHTML=K,se.style.display="none",D.appendChild(se)):D.innerHTML=K,$&&(S!=null&&S.useCaret)&&!k&&T){let X=gi(),$e=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ht=$e[$e.length-1];if(Ht!=null&&Ht.parentNode)Ht.parentNode.insertBefore(X,Ht.nextSibling);else{let he=D.lastElementChild;he?he.appendChild(X):D.appendChild(X)}}if(u&&m==="inline"&&e.createdAt){let X=Gu(e,l);X.classList.add("persona-ml-2","persona-inline"),D.appendChild(X)}if(w.length>0){let X=If(w,!k&&!!T,()=>{k&&se&&(se.style.display="")});X?x.appendChild(X):k&&se&&(se.style.display="")}let Re=kf(e);if(Re.length>0){let X=Wf(Re);X&&x.appendChild(X)}let Ge=Lf(e);if(Ge.length>0){let X=Rf(Ge);X&&x.appendChild(X)}let Ce=Pf(e);if(Ce.length>0){let X=Hf(Ce);X&&x.appendChild(X)}if(x.appendChild(D),u&&m==="below"&&e.createdAt){let X=Gu(e,l);X.classList.add("persona-mt-1"),x.appendChild(X)}let He=e.role==="assistant"?Sf(e.stopReason,(fe=(We=o==null?void 0:o.widgetConfig)==null?void 0:We.copy)==null?void 0:fe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(R&&R.trim()),$e=P.placeholder==="skeleton",Ht=$e&&P.buffer==="line"&&X;if(X)Ht&&x.appendChild(aa());else if($e)x.appendChild(aa());else{let he=xl("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&x.appendChild(he)}}if(He&&e.stopReason&&!e.streaming&&(T||(D.style.display="none"),x.appendChild(Tf(e.stopReason,He))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=vl(e,r,s);x.appendChild(X)}if(!p||e.role==="system")return x;let Be=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Pe=Bf(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Be.append(x,Pe):Be.append(Pe,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Be},Qu=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):hs(e,t,n,r,s,o)};var bs=new Set,Nf=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Of=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
-
`):""},
|
|
25
|
-
`);let
|
|
26
|
-
`):""},_f=(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,s=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",o=$f(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?du(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return s==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=nl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=nl(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},Zu=(e,t,n)=>{var p;let r=ys.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=s.toggleTextColor||s.headerTextColor||"currentColor",f=we(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")},Cl=(e,t)=>{var K,se,Re,Ge,Ce,He,be,Be,Pe;let n=e.toolCall,r=(K=t==null?void 0:t.toolCall)!=null?K:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.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 s;let o=(Re=(se=t==null?void 0:t.features)==null?void 0:se.toolCallDisplay)!=null?Re:{},a=o.expandable!==!1,i=a&&ys.has(e.id),{summary:d,previewText:l,isActive:p}=_f(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((Ge=n.startedAt)!=null?Ge:Date.now()),x=()=>{let J=h("span","");return J.setAttribute("data-tool-elapsed",v),J.textContent=Ks(n),J},w=(He=r.renderCollapsedSummary)==null?void 0:He.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Ce=o.collapsedMode)!=null?Ce:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Ks(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=o.loadingAnimation)!=null?be:"none",B=r.activeTextTemplate,k=r.completeTextTemplate,P=p?B:k,W=w instanceof HTMLElement,S=(J,ue,V)=>{let de=V;for(let le of ue){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(de)),ae.textContent=le===" "?"\xA0":le,J.appendChild(ae),de++}return de},I=(J,ue)=>{var ae;m.textContent="";let V=((ae=n.name)==null?void 0:ae.trim())||"tool",de=Ua(J,V),le=0;for(let Se of de){let ze=Se.styles.length>0?(()=>{let Y=h("span",Se.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return m.appendChild(Y),Y})():m;if(Se.isDuration&&p)ze.appendChild(x());else{let Y=Se.isDuration?Ks(n):Se.text;ue?le=S(ze,Y,le):ze.appendChild(document.createTextNode(Y))}}};if(!W)if(p&&T!=="none"){let J=(Be=r.loadingAnimationDuration)!=null?Be:2e3;if(m.setAttribute("data-preserve-animation","true"),T==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${J}ms`),P&&I(P,!1);else if(m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${J}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)),P)I(P,!0);else{let ue=m.textContent||d;m.textContent="",S(m,ue,0)}}else P&&I(P,!1);let $=null;if(a){$=h("div","persona-flex persona-items-center");let J=r.toggleTextColor||r.headerTextColor||"currentColor",ue=we(i?"chevron-up":"chevron-down",16,J,2);ue?$.appendChild(ue):$.textContent=i?"Hide":"Show";let V=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");V.append($),u.append(f,V)}else u.append(f);let D=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&l){let J=(Pe=r.renderCollapsedPreview)==null?void 0:Pe.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Ff(D,J)||(D.textContent=l),D.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(u,D),s;let R=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.style.paddingBottom=r.contentPaddingY),n.name){let J=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?J.style.color=r.contentTextColor:r.headerTextColor&&(J.style.color=r.headerTextColor),J.textContent=n.name,R.appendChild(J)}if(n.args!==void 0){let J=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ue.style.color=r.labelTextColor),ue.textContent="Arguments";let V=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");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=ls(n.args),J.append(ue,V),R.appendChild(J)}if(n.chunks&&n.chunks.length){let J=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ue.style.color=r.labelTextColor),ue.textContent="Activity";let V=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");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=n.chunks.join(""),J.append(ue,V),R.appendChild(J)}if(n.status==="complete"&&n.result!==void 0){let J=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ue.style.color=r.labelTextColor),ue.textContent="Result";let V=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");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=ls(n.result),J.append(ue,V),R.appendChild(J)}if(n.status==="complete"&&typeof n.duration=="number"){let J=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(J.style.color=r.contentTextColor),J.textContent=`Duration: ${n.duration}ms`,R.appendChild(J)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),$){$.innerHTML="";let J=r.toggleTextColor||r.headerTextColor||"currentColor",ue=we(i?"chevron-up":"chevron-down",16,J,2);ue?$.appendChild(ue):$.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),s.append(u,D,R),s};var bo=require("partial-json");var Sl="ask_user_question",Al=8,xs="data-persona-ask-sheet-for",jf="Other",Uf="Other\u2026",tm="Type your own answer here",nm="Send",qf="Next",zf="Back",Vf="Submit all",Kf="Skip",Jf=3,Tl="data-ask-current-index",El="data-ask-question-count",rm="data-ask-answers",Ml="data-ask-grouped",om="data-ask-layout",Gf=e=>e.layout==="pills"?"pills":"rows",Xf=e=>e.getAttribute(om)==="pills"?"pills":"rows",em=!1,sm=e=>e.replace(/["\\]/g,"\\$&"),zr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Sl,Ei=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Vr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=(0,bo.parse)(s,bo.STR|bo.OBJ|bo.ARR);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},pa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Al&&!em&&(em=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Al}.`)),t.slice(0,Al)},Qf=e=>{var t;return(t=pa(e)[0])!=null?t:null},Yf=(e,t)=>{var n;return(n=pa(e)[t])!=null?n:null},am=(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))},im=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},Zf=(e,t,n,r)=>{let o=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=im(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},eh=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},th=(e,t,n,r)=>{var p,u,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<Jf;m++)o.appendChild(eh(r));return o}if(d.forEach((m,v)=>{o.appendChild(Zf(m,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?jf:Uf;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:tm,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=im(r,a,d.length);T&&v.appendChild(T),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(f=t.freeTextLabel)!=null?f:m,o.appendChild(v)}}return o},lm=(e,t)=>{var o,a;let r=h("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:tm,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:nm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},nh=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:nm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},rh=(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 s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=n.backLabel)!=null?l:zf,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:Kf,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:Vf:(f=n.nextLabel)!=null?f:qf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},zo=e=>{let t=e.getAttribute(rm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cm=(e,t)=>{e.setAttribute(rm,JSON.stringify(t))},gr=e=>{var n;let t=Number((n=e.getAttribute(Tl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},oh=(e,t)=>{e.setAttribute(Tl,String(Math.max(0,Math.floor(t))))},vs=e=>{var n;let t=Number((n=e.getAttribute(El))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yo=e=>e.getAttribute(Ml)==="true",sh=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},ah=(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)))},Mi=(e,t)=>{let{payload:n}=Vr(t),r=pa(n),s=zo(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},dm=e=>{let t=zo(e),n=gr(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},pm=e=>{if(!yo(e))return;let t=zo(e),n=gr(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},kl=(e,t,n)=>{let r=Ei(n),s=Xf(e),{payload:o,complete:a}=Vr(t),i=yo(e),d=gr(e),l=vs(e),p=i?Yf(o,d):Qf(o),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 B=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=B,v.classList.toggle("persona-ask-question-skeleton",!B&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let B=th(p,r,a,s);x.replaceWith(B)}if(s!=="rows"){let B=e.querySelector('[data-ask-free-text-row="true"]');B&&B.replaceWith(lm(r,s))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!w?e.appendChild(nh(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 B=rh(d,l,r);T?T.replaceWith(B):e.appendChild(B)}else T&&T.remove();dm(e),pm(e)},ih=(e,t,n)=>{let r=Ei(t),s=Gf(r),o=e.toolCall.id,a=pa(n),i=Math.max(1,a.length),d=i>1,l=sh(e,a),p=d?ah(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(xs,o),u.setAttribute("data-tool-call-id",o),u.setAttribute("data-message-id",e.id),u.setAttribute(El,String(i)),u.setAttribute(Tl,String(p)),u.setAttribute(Ml,d?"true":"false"),u.setAttribute(om,s),cm(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`),am(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",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),u.appendChild(w),s!=="rows"&&u.appendChild(lm(r,s)),kl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},lh=(e,t,n)=>{let{payload:r}=Vr(t),s=Math.max(1,pa(r).length);s>vs(e)&&(e.setAttribute(El,String(s)),s>1&&!yo(e)&&e.setAttribute(Ml,"true")),kl(e,t,n)},um=(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);am(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=Vr(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},ws=(e,t,n)=>{if(!n||!zr(e)||Ei(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${xs}]`).forEach(l=>{l.getAttribute(xs)!==s&&l.remove()});let a=n.querySelector(`[${xs}="${sm(s)}"]`);if(a){lh(a,e,t);return}let{payload:i}=Vr(e),d=ih(e,t,i);n.appendChild(d)},xo=(e,t)=>{if(!e)return;let n=t?`[${xs}="${sm(t)}"]`:`[${xs}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Ll=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),vo=(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,cm(e,n),dm(e),pm(e)},ki=(e,t,n,r)=>{let s=vs(e),o=Math.max(0,Math.min(s-1,r));oh(e,o),kl(e,t,n)};var Li=new Map,ch=e=>{let n=(e.startsWith(_r)?e.slice(_r.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)},mm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,gm=(e,t)=>{var r,s,o;let n=(s=(r=mm(t))==null?void 0:r.detailsDisplay)!=null?s:"collapsed";return(o=Li.get(e))!=null?o:n==="expanded"},fm=(e,t,n)=>{var a,i;let r=mm(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.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 o=e.querySelector("[data-approval-details-chevron]");if(o){o.innerHTML="";let d=we(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&o.appendChild(d)}},hm=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let o=gm(e,n);fm(r,o,n),s.style.display=o?"":"none"};var Pi=(e,t)=>{var I,$,D,R,q,K,se,Re,Ge,Ce,He,be,Be,Pe;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(I=r==null?void 0:r.backgroundColor)!=null?I:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=($=r==null?void 0:r.borderColor)!=null?$:"var(--persona-approval-border, #fef08a)",o.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 o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(D=r==null?void 0:r.titleColor)!=null?D:"currentColor",p=we(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=(R=r==null?void 0:r.title)!=null?R:"Approval Required",f.appendChild(m),!s){let J=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");J.setAttribute("data-approval-status",n.status),n.status==="approved"?(J.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",J.style.color="var(--persona-palette-colors-success-700, #15803d)",J.textContent="Approved"):n.status==="denied"?(J.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",J.style.color="var(--persona-palette-colors-error-700, #b91c1c)",J.textContent="Denied"):n.status==="timeout"&&(J.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",J.style.color="var(--persona-palette-colors-warning-700, #b45309)",J.textContent="Timeout"),f.appendChild(J)}u.appendChild(f);let x=n.toolType==="webmcp"||n.toolName.startsWith(_r)?tl(n.toolName):void 0,w=(q=r==null?void 0:r.formatDescription)==null?void 0:q.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{}}),T=!n.toolName,B=w||(T?n.description:`The assistant wants to use \u201C${x!=null?x:ch(n.toolName)}\u201D.`),k=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");k.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=B,u.appendChild(k);let P=(K=r==null?void 0:r.detailsDisplay)!=null?K:"collapsed",W=!!n.description&&!T,S=W||!!n.parameters;if(P!=="hidden"&&S){let J=gm(e.id,t),ue=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");ue.type="button",ue.setAttribute("data-expand-header","true"),ue.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ue.style.color=r.descriptionColor);let V=h("span");V.setAttribute("data-approval-details-label","true");let de=h("span","persona-inline-flex persona-items-center");de.setAttribute("data-approval-details-chevron","true"),ue.append(V,de),fm(ue,J,t),u.appendChild(ue);let le=h("div");if(le.setAttribute("data-approval-details","true"),le.style.display=J?"":"none",W){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,le.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=ls(n.parameters),le.appendChild(ae)}u.appendChild(le)}if(s){let J=h("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");let ue=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ue.type="button",ue.style.backgroundColor=(se=r==null?void 0:r.approveButtonColor)!=null?se:"var(--persona-approval-approve-bg, #22c55e)",ue.style.color=(Re=r==null?void 0:r.approveButtonTextColor)!=null?Re:"#ffffff",ue.setAttribute("data-approval-action","approve");let V=we("shield-check",14,(Ge=r==null?void 0:r.approveButtonTextColor)!=null?Ge:"#ffffff",2);V&&(V.style.marginRight="4px",ue.appendChild(V));let de=document.createTextNode((Ce=r==null?void 0:r.approveLabel)!=null?Ce:"Approve");ue.appendChild(de);let le=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");le.type="button",le.style.backgroundColor=(He=r==null?void 0:r.denyButtonColor)!=null?He:"transparent",le.style.color=(be=r==null?void 0:r.denyButtonTextColor)!=null?be:"var(--persona-feedback-error, #dc2626)",le.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,le.setAttribute("data-approval-action","deny");let ae=we("shield-x",14,(Be=r==null?void 0:r.denyButtonTextColor)!=null?Be:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",le.appendChild(ae));let Se=document.createTextNode((Pe=r==null?void 0:r.denyLabel)!=null?Pe:"Deny");le.appendChild(Se),J.append(ue,le),u.appendChild(J)}return a.append(i,u),o.appendChild(a),o};var bm=e=>{let t=[];return{buttons:t,render:(r,s,o,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let p=document.createDocumentFragment(),u=s?s.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};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",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),p.appendChild(v),t.push(v)}),e.appendChild(p)}}};var ua=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 ma=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var dh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),ph=new Set(["step_start","execution_start"]),uh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),mh=new Set(["step_complete","agent_turn_complete"]),gh=new Set(["flow_complete","agent_complete"]),ym=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),vm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Vo=(e,t)=>{let n=e[t];return vm(n)?n:void 0};function Pl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ii(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function fh(e,t){return typeof t.type=="string"?t.type:e}function hh(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 bh(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 xm(e){var r,s,o,a,i;let t=Vo(e,"result"),n=[Vo(e,"tokens"),Vo(e,"totalTokens"),t?Vo(t,"tokens"):void 0,Vo(e,"usage"),t?Vo(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(s=(r=Zn(d.output))!=null?r:Zn(d.outputTokens))!=null?s:Zn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Zn(e.outputTokens))!=null?o:Zn(e.completionTokens))!=null?i:t?(a=Zn(t.outputTokens))!=null?a:Zn(t.completionTokens):void 0}function yh(e){var n,r,s,o,a;let t=Vo(e,"result");return(a=(s=(r=(n=Zn(e.executionTime))!=null?n:Zn(e.executionTimeMs))!=null?r:Zn(e.execution_time))!=null?s:Zn(e.duration))!=null?a:t?(o=Zn(t.executionTime))!=null?o:Zn(t.executionTimeMs):void 0}function xh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ga=class{constructor(t=xh){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:Ii(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var o;if(!vm(n)){ym.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=fh(t,n),s=this.now();if(dh.has(r)){this.startRun(s);return}if(ph.has(r)){this.run||this.startRun(s);return}if(uh.has(r)){if(!bh(r,n))return;let a=hh(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Pl(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ii(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(mh.has(r)){if(!this.run)return;let a=this.run,i=xm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Pl(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:Ii(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(gh.has(r)){if(!this.run)return;let a=this.run,i=xm(n),d=i!=null?i:a.exactOutputTokens+Pl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:Ii(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(ym.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=yh(n);return o!=null?o:r-t.startedAt}};function Cs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var vh={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)"}},wh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ch=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ah=100;function Sh(e,t){let n={...vh,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return wh}function Th(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Eh(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function Mh(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function kh(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 Lh(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 Ph(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Ih(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 Wh(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Il(e,t,n,r,s,o,a,i){var f;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Cs(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:()=>o(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(u()),l;function u(){var K,se;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=we(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]"),B=(K=r.timestampFormat)!=null?K:"relative";T.textContent=B==="relative"?Th(e.timestamp,n):Eh(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 P=Sh(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=P.bg,W.style.color=P.text,W.style.borderColor=P.text+"50",W.textContent=e.type;let S=(se=r.descriptionFields)!=null?se:Ch,I=Mh(e.payload,S),$=null;I&&($=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),$.textContent=I);let D=h("div","persona-flex-1 persona-min-w-0"),R=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"),q=we("clipboard","12px","currentColor",1.5);return q&&R.appendChild(q),R.addEventListener("click",async Re=>{Re.stopPropagation(),await kh(Lh(e)),R.innerHTML="";let Ge=we("check","12px","currentColor",1.5);Ge&&R.appendChild(Ge),setTimeout(()=>{R.innerHTML="";let Ce=we("clipboard","12px","currentColor",1.5);Ce&&R.appendChild(Ce)},1500)}),v.appendChild(x),v.appendChild(T),k&&v.appendChild(k),v.appendChild(W),$&&v.appendChild($),v.appendChild(D),v.appendChild(R),m.appendChild(v),d&&m.appendChild(Wh(e,a,i)),m}}function wm(e){var v,x,w,T,B;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(v=s==null?void 0:s.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(w=i==null?void 0:i.label)!=null?w:"",u=(B=(T=s==null?void 0:s.features)==null?void 0:T.eventStream)!=null?B:{},f=o.find(k=>k.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let k=f.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return m();function m(){let k=u.classNames,P=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Cs(P,k==null?void 0:k.panel);let W=[],S="",I="",$=null,D=[],R={},q=0,K=ci(),se=0,Re=0,Ge=!1,Ce=null,He=!1,be=0,Be=new Set,Pe=new Map,J="",ue="",V=null,de,le,ae,Se,ze,Y=null,ne=null,ce=null;function xe(){let re=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ve=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");Cs(ve,k==null?void 0:k.headerBar);let Et=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Et.textContent="Events",de=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),de.textContent="0",a){ne=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let Dn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Dn.textContent="Throughput",Y=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Y.textContent="-- tok/s",ce=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"),ce.style.display="none",ce.style.pointerEvents="none";let tr=ne,An=ce,Nn=()=>{if(!An.textContent)return;let Er=tr.getBoundingClientRect(),On=re.getBoundingClientRect();An.style.left=`${Er.left-On.left}px`,An.style.top=`${Er.bottom-On.top+4}px`,An.style.display="block"},bt=()=>{An.style.display="none"};ne.addEventListener("mouseenter",Nn),ne.addEventListener("mouseleave",bt),ne.appendChild(Dn),ne.appendChild(Y)}let Jt=h("div","persona-flex-1");le=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 nn=h("option","");nn.value="",nn.textContent="All events",le.appendChild(nn),ae=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"),ae.type="button",ae.title="Copy All";let Wt=we("clipboard-copy","12px","currentColor",1.5);Wt&&ae.appendChild(Wt);let kt=h("span","persona-text-xs");kt.textContent="Copy All",ae.appendChild(kt),ve.appendChild(Et),ve.appendChild(de),ne&&ve.appendChild(ne),ve.appendChild(Jt),ve.appendChild(le),ve.appendChild(ae);let wt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Cs(wt,k==null?void 0:k.searchBar);let At=we("search","14px","var(--persona-muted, #9ca3af)",1.5),Gt=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");At&&Gt.appendChild(At),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"),Cs(Se,k==null?void 0:k.searchInput),Se.type="text",Se.placeholder="Search event payloads...",ze=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"),ze.type="button",ze.style.display="none";let ot=we("x","12px","currentColor",2);return ot&&ze.appendChild(ot),wt.appendChild(Gt),wt.appendChild(Se),wt.appendChild(ze),re.appendChild(ve),re.appendChild(wt),ce&&re.appendChild(ce),re}let me,oe=o.find(re=>re.renderEventStreamToolbar);if(oe!=null&&oe.renderEventStreamToolbar&&s){let re=oe.renderEventStreamToolbar({config:s,defaultRenderer:()=>xe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ve=>{S=ve,Bn(),F()},onSearchChange:ve=>{I=ve,Bn(),F()}});me=re!=null?re:xe()}else me=xe();let Ze=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");Ze.style.display="none";function We(){if(!a||!Y||!ne)return;let re=a();Y.textContent=Ph(re);let ve=Ih(re);ce&&(ce.textContent=ve,ve||(ce.style.display="none")),ve?ne.setAttribute("aria-label",ve):ne.removeAttribute("aria-label")}let fe=h("div","persona-flex-1 persona-min-h-0 persona-relative"),X=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let $e=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Cs($e,k==null?void 0:k.scrollIndicator),$e.style.display="none",$e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Ht=we(l,"14px","currentColor",2);Ht&&$e.appendChild(Ht);let he=h("span","");he.textContent=p,$e.appendChild(he);let pe=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");pe.style.display="none",fe.appendChild(X),fe.appendChild(pe),fe.appendChild($e),P.setAttribute("tabindex","0"),P.appendChild(me),P.appendChild(Ze),P.appendChild(fe);function Pn(){let re=t.getAll(),ve={};for(let kt of re)ve[kt.type]=(ve[kt.type]||0)+1;let Et=Object.keys(ve).sort(),Jt=Et.length!==D.length||!Et.every((kt,wt)=>kt===D[wt]),nn=!Jt&&Et.some(kt=>ve[kt]!==R[kt]),Cn=re.length!==Object.values(R).reduce((kt,wt)=>kt+wt,0);if(!Jt&&!nn&&!Cn||(D=Et,R=ve,!le))return;let Wt=le.value;if(le.options[0].textContent="All events",Jt){for(;le.options.length>1;)le.remove(1);for(let kt of Et){let wt=h("option","");wt.value=kt,wt.textContent=`${kt} (${ve[kt]||0})`,le.appendChild(wt)}Wt&&Et.includes(Wt)?le.value=Wt:Wt&&(le.value="",S="")}else for(let kt=1;kt<le.options.length;kt++){let wt=le.options[kt];wt.textContent=`${wt.value} (${ve[wt.value]||0})`}}function Ut(){let re=t.getAll();if(S&&(re=re.filter(ve=>ve.type===S)),I){let ve=I.toLowerCase();re=re.filter(Et=>Et.type.toLowerCase().includes(ve)||Et.payload.toLowerCase().includes(ve))}return re}function gn(){return S!==""||I!==""}function Bn(){q=0,se=0,K.resume(),$e.style.display="none"}function er(re){Be.has(re)?Be.delete(re):Be.add(re),V=re;let ve=X.scrollTop,Et=K.isFollowing();He=!0,K.pause(),F(),X.scrollTop=ve,Et&&K.resume(),He=!1}function Ue(){return ta(X,50)}function F(){Re=Date.now(),Ge=!1,We(),Pn();let re=t.getEvictedCount();re>0?(Ze.textContent=`${re.toLocaleString()} older events truncated`,Ze.style.display=""):Ze.style.display="none",W=Ut();let ve=W.length,Et=t.getSize()>0;de&&(de.textContent=String(t.getSize())),ve===0&&Et&&gn()?(pe.textContent=I?`No events matching '${I}'`:"No events matching filter",pe.style.display="",X.style.display="none"):(pe.style.display="none",X.style.display=""),ae&&(ae.title=gn()?`Copy Filtered (${ve})`:"Copy All"),d&&!K.isFollowing()&&ve>q&&(se+=ve-q,he.textContent=p?`${p}${se>0?` (${se})`:""}`:"",$e.style.display=""),q=ve;let Jt=t.getAll(),nn=Jt.length>0?Jt[0].timestamp:0,Cn=new Set(W.map(wt=>wt.id));for(let wt of Be)Cn.has(wt)||Be.delete(wt);let Wt=S!==J||I!==ue,kt=Pe.size===0&&W.length>0;if(Wt||kt||W.length===0){X.innerHTML="",Pe.clear();let wt=document.createDocumentFragment();for(let At=0;At<W.length;At++){let Gt=Il(W[At],At,nn,u,Be,er,o,s);Pe.set(W[At].id,Gt),wt.appendChild(Gt)}X.appendChild(wt),J=S,ue=I,V=null}else{if(V!==null){let At=Pe.get(V);if(At&&At.parentNode===X){let Gt=W.findIndex(ot=>ot.id===V);if(Gt>=0){let ot=Il(W[Gt],Gt,nn,u,Be,er,o,s);X.insertBefore(ot,At),At.remove(),Pe.set(V,ot)}}V=null}let wt=new Set(W.map(At=>At.id));for(let[At,Gt]of Pe)wt.has(At)||(Gt.remove(),Pe.delete(At));for(let At=0;At<W.length;At++){let Gt=W[At];if(!Pe.has(Gt.id)){let ot=Il(Gt,At,nn,u,Be,er,o,s);Pe.set(Gt.id,ot),X.appendChild(ot)}}}K.isFollowing()&&(X.scrollTop=X.scrollHeight)}function Ee(){if(Date.now()-Re>=Ah){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),F();return}Ge||(Ge=!0,Ce=requestAnimationFrame(()=>{Ce=null,F()}))}let De=(re,ve)=>{if(!ae)return;ae.innerHTML="";let Et=we(re,"12px","currentColor",1.5);Et&&ae.appendChild(Et);let Jt=h("span","persona-text-xs");Jt.textContent="Copy All",ae.appendChild(Jt),setTimeout(()=>{ae.innerHTML="";let nn=we("clipboard-copy","12px","currentColor",1.5);nn&&ae.appendChild(nn);let Cn=h("span","persona-text-xs");Cn.textContent="Copy All",ae.appendChild(Cn),ae.disabled=!1},ve)},Ne=async()=>{if(ae){ae.disabled=!0;try{let re;gn()?re=W:n?(re=await n(),re.length===0&&(re=t.getAll())):re=t.getAll();let ve=re.map(Et=>{try{return JSON.parse(Et.payload)}catch{return Et.payload}});await navigator.clipboard.writeText(JSON.stringify(ve,null,2)),De("check",1500)}catch{De("x",1500)}}},_e=()=>{le&&(S=le.value,Bn(),F())},mt=()=>{!Se||!ze||(ze.style.display=Se.value?"":"none",$&&clearTimeout($),$=setTimeout(()=>{I=Se.value,Bn(),F()},150))},at=()=>{!Se||!ze||(Se.value="",I="",ze.style.display="none",$&&clearTimeout($),Bn(),F())},It=()=>{if(He)return;let re=X.scrollTop,{action:ve,nextLastScrollTop:Et}=di({following:K.isFollowing(),currentScrollTop:re,lastScrollTop:be,nearBottom:Ue(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=Et,ve==="resume"?(K.resume(),se=0,$e.style.display="none"):ve==="pause"&&(K.pause(),d&&(he.textContent=p,$e.style.display=""))},Kt=re=>{let ve=pi({following:K.isFollowing(),deltaY:re.deltaY,nearBottom:Ue(),resumeWhenNearBottom:!0});ve==="pause"?(K.pause(),d&&(he.textContent=p,$e.style.display="")):ve==="resume"&&(K.resume(),se=0,$e.style.display="none")},z=()=>{d&&(X.scrollTop=X.scrollHeight,K.resume(),se=0,$e.style.display="none")},qt=re=>{let ve=re.target;if(!ve||ve.closest("button"))return;let Et=ve.closest("[data-event-id]");if(!Et)return;let Jt=Et.getAttribute("data-event-id");Jt&&er(Jt)},et=re=>{if((re.metaKey||re.ctrlKey)&&re.key==="f"){re.preventDefault(),Se==null||Se.focus(),Se==null||Se.select();return}re.key==="Escape"&&(Se&&document.activeElement===Se?(at(),Se.blur(),P.focus()):r&&r())};ae&&ae.addEventListener("click",Ne),le&&le.addEventListener("change",_e),Se&&Se.addEventListener("input",mt),ze&&ze.addEventListener("click",at),X.addEventListener("scroll",It),X.addEventListener("wheel",Kt,{passive:!0}),X.addEventListener("click",qt),$e.addEventListener("click",z),P.addEventListener("keydown",et);function _t(){$&&clearTimeout($),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ge=!1,Pe.clear(),ae&&ae.removeEventListener("click",Ne),le&&le.removeEventListener("change",_e),Se&&Se.removeEventListener("input",mt),ze&&ze.removeEventListener("click",at),X.removeEventListener("scroll",It),X.removeEventListener("wheel",Kt),X.removeEventListener("click",qt),$e.removeEventListener("click",z),P.removeEventListener("keydown",et)}return{element:P,update:Ee,destroy:_t}}}function Cm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(l.append(p,u),i.append(d,l),s==="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 Am=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Cm(e,t)});if(p)return p}return Cm(e,t)};var Wl=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)})}},Kr=new Wl;Kr.register("PersonaArtifactCard",Am);function Rh(e){var s;let t=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function Sm(e,t){var le,ae,Se,ze;let n=(ae=(le=e.features)==null?void 0:le.artifacts)==null?void 0:ae.layout,s=((Se=n==null?void 0:n.toolbarPreset)!=null?Se:"default")==="document",o=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?Bo(e.markdown):null,i=as(e.sanitize),d=Y=>{let ne=a?a(Y):Do(Y);return i?i(ne):ne},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),q==null||q.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"),s&&u.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let x="rendered",w=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=s?Vt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Vt({icon:"eye",label:"Rendered view"}),B=s?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"),P=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,S=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(W&&S&&S.length>0),$=null,D,R=null,q=null;if(s&&(P||W)&&!I){if(D=P?ca({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let Y=we("chevron-down",14,"currentColor",2);Y&&D.appendChild(Y)}}else s&&I?($=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),D=P?ca({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=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(D,R)):s?D=Vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):D=Vt({icon:"copy",label:"Copy"});let K=s?Vt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Vt({icon:"refresh-cw",label:"Refresh"}),se=s?Vt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Vt({icon:"x",label:"Close"}),Re=()=>{var me,oe,Ze;let Y=(me=Pe.find(We=>We.id===J))!=null?me:Pe[Pe.length-1],ne=(oe=Y==null?void 0:Y.id)!=null?oe:null,ce=(Y==null?void 0:Y.artifactType)==="markdown"&&(Ze=Y.markdown)!=null?Ze:"",xe=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:ce,jsonPayload:xe,id:ne}},Ge=async()=>{var me;let{markdown:Y,jsonPayload:ne}=Re(),ce=(me=Pe.find(oe=>oe.id===J))!=null?me:Pe[Pe.length-1],xe=(ce==null?void 0:ce.artifactType)==="markdown"?Y:ce?ne:"";try{await navigator.clipboard.writeText(xe)}catch{}};if(D.addEventListener("click",async()=>{let Y=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Y&&I){let{markdown:ne,jsonPayload:ce,id:xe}=Re();try{await Y({actionId:"primary",artifactId:xe,markdown:ne,jsonPayload:ce})}catch{}return}await Ge()}),R&&(S!=null&&S.length)){let Y=()=>{var ce;return(ce=u.closest("[data-persona-root]"))!=null?ce:document.body},ne=()=>{q=ho({items:S.map(ce=>({id:ce.id,label:ce.label})),onSelect:async ce=>{let{markdown:xe,jsonPayload:me,id:oe}=Re(),Ze=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ze?await Ze({actionId:ce,artifactId:oe,markdown:xe,jsonPayload:me}):ce==="markdown"||ce==="md"?await navigator.clipboard.writeText(xe):ce==="json"||ce==="source"?await navigator.clipboard.writeText(me):await navigator.clipboard.writeText(xe||me)}catch{}},anchor:$!=null?$:R,position:"bottom-right",portal:Y()})};u.isConnected?ne():requestAnimationFrame(ne),R.addEventListener("click",ce=>{ce.stopPropagation(),q==null||q.toggle()})}K.addEventListener("click",async()=>{var Y;try{await((Y=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Y.call(n))}catch{}V()}),se.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let Ce=()=>{s&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),B.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Ce(),V()}),B.addEventListener("click",()=>{x="source",Ce(),V()});let He=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),w.append(T,B),$?k.append($,K,se):k.append(D,K,se),f.append(w,He,k),Ce()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);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"),Be=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(be.style.paddingLeft=o,be.style.paddingRight=o,Be.style.padding=o),u.appendChild(f),u.appendChild(be),u.appendChild(Be);let Pe=[],J=null,ue=!1,V=()=>{var xe,me,oe,Ze;let Y=s&&Pe.length<=1;be.classList.toggle("persona-hidden",Y),be.replaceChildren();for(let We of Pe){let fe=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");fe.type="button",fe.textContent=We.title||We.id.slice(0,8),We.id===J&&fe.classList.add("persona-bg-persona-container","persona-border-persona-border"),fe.addEventListener("click",()=>t.onSelect(We.id)),be.appendChild(fe)}Be.replaceChildren();let ne=J&&Pe.find(We=>We.id===J)||Pe[Pe.length-1];if(!ne)return;if(s){let We=ne.artifactType==="markdown"?"MD":(xe=ne.component)!=null?xe:"Component",X=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";He.textContent=`${X} \xB7 ${We}`}else m.textContent="Artifacts";if(ne.artifactType==="markdown"){if(s&&x==="source"){let fe=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");fe.textContent=(me=ne.markdown)!=null?me:"",Be.appendChild(fe);return}let We=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");We.innerHTML=d((oe=ne.markdown)!=null?oe:""),Be.appendChild(We);return}let ce=ne.component?Kr.get(ne.component):void 0;if(ce){let fe={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=ce((Ze=ne.props)!=null?Ze:{},fe);if(X){Be.appendChild(X);return}}catch{}}Be.appendChild(Rh(ne))},de=()=>{var ne;let Y=Pe.length>0;if(u.classList.toggle("persona-hidden",!Y),l){let ce=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,me=((ne=ce==null?void 0:ce.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&me&&ue?(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 ne,ce,xe;Pe=Y.artifacts,J=(xe=(ce=Y.selectedId)!=null?ce:(ne=Y.artifacts[Y.artifacts.length-1])==null?void 0:ne.id)!=null?xe:null,Pe.length>0&&(ue=!0),V(),de()},setMobileOpen(Y){ue=Y,!Y&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):de()}}}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 Tm(e,t){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!fr(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Hh(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 Wi(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"),Hh(e),Tm(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 s=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(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"),Tm(e,t)}var Em=["panel","seamless"];function Ri(e,t){var i,d,l,p,u,f;for(let m of Em)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",s=Em.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(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())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Mm(e,t){var n,r,s;return!t||!fr(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Bh(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 Dh(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 Nh(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Oh(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function km(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function Lm(e,t,n,r,s,o){let a=Bh(s,200),i=Oh(t,n,r,200);i=Math.max(a,i);let d=Dh(o);return d!==null&&(i=Math.min(i,d)),Nh(e,a,i)}var Pm={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"}},Rl=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,w;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=Pm[a])!=null?x:Pm.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let 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,I;let B=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");B.htmlFor=`${t.id}-${a}-${T.name}`;let k=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,B.appendChild(k);let P=(S=T.type)!=null?S:"text",W;P==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=P),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=(I=T.placeholder)!=null?I:"",T.required&&(W.required=!0),B.appendChild(W),p.appendChild(B)});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),o.replaceChildren(d,p),p.addEventListener("submit",async T=>{var W,S;T.preventDefault();let B=(W=n.formEndpoint)!=null?W:"/form",k=new FormData(p),P={};k.forEach((I,$)=>{P[$]=I}),P.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let I=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let $=await I.json();f.textContent=(S=$.message)!=null?S:"Thanks! We'll be in touch soon.",$.success&&$.nextPrompt&&await r.sendMessage(String($.nextPrompt))}catch(I){f.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Hl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},fa=new Hl;var Im=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Fh=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},$h=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},ha=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Fh(e),n=$h(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Bl=e=>typeof e=="string"?e:e==null?"":String(e),Ko={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Bl(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=Bl(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Bl(n.text)}}},Wm=e=>Array.isArray(e)?e.map(t=>String(t)):[],ba=e=>{let t=new Set(Wm(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Wm(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var _h=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}},jh=e=>e.map(t=>({...t,streaming:!1})),Uh=e=>e.map(t=>({...t,status:"complete"})),Hi=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?_h(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?jh(n.messages):void 0,artifacts:n.artifacts?Uh(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var As=require("partial-json");function qh(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function zh(e,t){if(!qh(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 Bi(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=(0,As.parse)(n,As.STR|As.OBJ),o=zh(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Rm(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Di(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=Kr.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Hm(){let e=Bi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Bm(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 Ni(e){let t=Bm(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 Oi(e){let t=Bm(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 Vh=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fi(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Vh}=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=s,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 I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${l[S-1]}`),I.title=l[S-1],I.dataset.rating=String(S),I.innerHTML=`
|
|
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=`
|
|
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
|
-
`,I.addEventListener("click",()=>{u=S,T.forEach(($,D)=>{let R=D<S;$.classList.toggle("selected",R),$.setAttribute("aria-checked",D===S-1?"true":"false")})}),T.push(I),w.appendChild(I)}f.appendChild(w);let B=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=o,B.rows=3,B.setAttribute("aria-label","Additional comments"),S.appendChild(B),f.appendChild(S)}let k=document.createElement("div");k.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=i,P.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=(B==null?void 0:B.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)}}),k.appendChild(P),k.appendChild(W),f.appendChild(k),p.appendChild(f),p}function $i(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,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=s,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 B=document.createElement("div");B.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=p,B.appendChild(k),B.appendChild(P);let W=document.createElement("div");W.className="persona-feedback-numbers";let S=[];for(let q=0;q<=10;q++){let K=document.createElement("button");K.type="button",K.className="persona-feedback-rating-btn persona-feedback-number-btn",K.setAttribute("role","radio"),K.setAttribute("aria-checked","false"),K.setAttribute("aria-label",`Rating ${q} out of 10`),K.textContent=String(q),K.dataset.rating=String(q),q<=6?K.classList.add("persona-feedback-detractor"):q<=8?K.classList.add("persona-feedback-passive"):K.classList.add("persona-feedback-promoter"),K.addEventListener("click",()=>{f=q,S.forEach((se,Re)=>{se.classList.toggle("selected",Re===q),se.setAttribute("aria-checked",Re===q?"true":"false")})}),S.push(K),W.appendChild(K)}T.appendChild(B),T.appendChild(W),m.appendChild(T);let I=null;if(d){let q=document.createElement("div");q.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=o,I.rows=3,I.setAttribute("aria-label","Additional comments"),q.appendChild(I),m.appendChild(q)}let $=document.createElement("div");$.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),u.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(f===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let q=(I==null?void 0:I.value.trim())||void 0;await t(f,q),u.remove()}catch(q){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",q)}}),$.appendChild(D),$.appendChild(R),m.appendChild($),u.appendChild(m),u}var Ss="persona-chat-history",Kh=30*1e3,Jh={"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 Gh(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=Jh[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function _i(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 Xh(e){var t,n,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function Qh(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Dl=e=>!e||typeof e!="object"?{}:{...e},Dm=e=>e.map(t=>({...t,streaming:!1})),Nm=(e,t,n)=>{let r=e!=null&&e.markdown?Bo(e.markdown):null,s=as(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,p,u;let a=(l=o.text)!=null?l:"",i=(p=o.message.rawContent)!=null?p:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(u=i!=null?i:o.text)!=null?u:""}):r?d=r(a):d=Do(a),s?s(d):d}};function Om(e){var i,d,l,p;let t=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=we(n,r,s,o);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 ji=(e,t,n)=>{var ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,xc,vc,wc,Cc,Ac,Sc,Tc,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;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=ri(t),s=fa.getForInstance(r.plugins);r.components&&Kr.registerAll(r.components);let o=Im(),i=r.persistState===!1?null:(ic=r.storageAdapter)!=null?ic:Hi(),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=Dl(b.metadata)),(lc=b.messages)!=null&&lc.length&&(r={...r,initialMessages:b.messages}),(cc=b.artifacts)!=null&&cc.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:(dc=b.selectedArtifactId)!=null?dc: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:{},Qo()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ha],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Ko.message,Ko.messageAndClick],w=ba({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let T=(mc=(uc=r.launcher)==null?void 0:uc.enabled)!=null?mc:!0,B=(fc=(gc=r.launcher)==null?void 0:gc.autoExpand)!=null?fc:!1,k=(hc=r.autoFocusInput)!=null?hc:!1,P=B,W=T,S=(yc=(bc=r.layout)==null?void 0:bc.header)==null?void 0:yc.layout,I=!1,$=()=>fo(r),D=()=>T||$(),R=$()?!1:T?B:!0,q=!1,K=null,se=()=>{q=!0,K&&clearTimeout(K),K=setTimeout(()=>{q&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),q=!1)},1e4)},Re=Nm(r,w,se),Ge=(vc=(xc=r.features)==null?void 0:xc.showReasoning)!=null?vc:!0,Ce=(Cc=(wc=r.features)==null?void 0:wc.showToolCalls)!=null?Cc:!0,He=(Sc=(Ac=r.features)==null?void 0:Ac.showEventStreamToggle)!=null?Sc:!1,be=(Ec=(Tc=r.features)==null?void 0:Tc.scrollToBottom)!=null?Ec:{},Pe=`${(kc=typeof r.persistState=="object"?(Mc=r.persistState)==null?void 0:Mc.keyPrefix:void 0)!=null?kc:"persona-"}event-stream`,J=He?new ma(Pe):null,ue=(Ic=(Pc=(Lc=r.features)==null?void 0:Lc.eventStream)==null?void 0:Pc.maxEvents)!=null?Ic:2e3,V=He?new ua(ue,J):null,de=He?new ga:null,le=null,ae=!1,Se=null,ze=0;J==null||J.open().then(()=>V==null?void 0:V.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Y={onCopy:c=>{var g,b;o.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;o.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)}},ne=(Wc=r.statusIndicator)!=null?Wc:{},ce=c=>{var g,b,y,E;return c==="idle"?(g=ne.idleText)!=null?g:vn.idle:c==="connecting"?(b=ne.connectingText)!=null?b:vn.connecting:c==="connected"?(y=ne.connectedText)!=null?y:vn.connected:c==="error"?(E=ne.errorText)!=null?E:vn.error:vn[c]};function xe(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:me,panel:oe,pillRoot:Ze}=Ku(r),We=Ju(r,D()),{container:fe,body:X,messagesWrapper:$e,suggestions:Ht,textarea:he,sendButton:pe,sendButtonWrapper:Pn,composerForm:Ut,statusText:gn,introTitle:Bn,introSubtitle:er,closeButton:Ue,iconHolder:F,headerTitle:Ee,headerSubtitle:De,header:Ne,footer:_e,actionsRow:mt,leftActions:at,rightActions:It}=We,Kt=We.setSendButtonMode,z=We.micButton,qt=We.micButtonWrapper,et=We.attachmentButton,_t=We.attachmentButtonWrapper,re=We.attachmentInput,ve=We.attachmentPreviewsContainer;fe.classList.add("persona-relative"),X.classList.add("persona-relative");let Et=12,Jt=()=>{var c;return(c=be.label)!=null?c:""},nn=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},Cn=()=>be.enabled!==!1,Wt=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");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let kt=h("span","persona-flex persona-items-center"),wt=h("span","");Wt.append(kt,wt),fe.appendChild(Wt);let At=()=>{let g=_e.style.display==="none"?0:_e.offsetHeight;Wt.style.bottom=`${g+Et}px`};At();let Gt=()=>{let c=!!Jt();Wt.setAttribute("aria-label",Jt()||"Jump to latest"),Wt.title=Jt(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),kt.innerHTML="";let g=we(nn(),"14px","currentColor",2);g?(kt.appendChild(g),kt.style.display=""):kt.style.display="none",wt.textContent=Jt(),wt.style.display=c?"":"none"};Gt();let ot=null,Dn=null,tr=s.find(c=>c.renderHeader);if(tr!=null&&tr.renderHeader){let c=tr.renderHeader({config:r,defaultRenderer:()=>{let g=qr({config:r,showClose:D()});return Uo(fe,g,r),g.header},onClose:()=>Nt(!1,"user")});if(c){let g=fe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ne=c)}}let An=()=>{var g,b,y,E;if(!V)return;if(ae=!0,!le&&V&&(le=wm({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>Nn(),config:r,plugins:s,getThroughput:()=>{var N;return(N=de==null?void 0:de.getMetric())!=null?N:{status:"idle"}}})),le&&(X.style.display="none",(g=_e.parentNode)==null||g.insertBefore(le.element,_e),le.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${Ln.actionIconColor}`;let N=(E=(y=(b=r.features)==null?void 0:b.eventStream)==null?void 0:y.classNames)==null?void 0:E.toggleButtonActive;N&&N.split(/\s+/).forEach(O=>O&&bt.classList.add(O))}let c=()=>{if(!ae)return;let N=Date.now();N-ze>=200&&(le==null||le.update(),ze=N),Se=requestAnimationFrame(c)};ze=0,Se=requestAnimationFrame(c),Nr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,g,b;if(ae){if(ae=!1,le&&le.element.remove(),X.style.display="",bt){bt.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&&bt.classList.remove(E))}Se!==null&&(cancelAnimationFrame(Se),Se=null),Nr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(He){let c=(Hc=(Rc=r.features)==null?void 0:Rc.eventStream)==null?void 0:Hc.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:"");bt=h("button",g),bt.style.width="28px",bt.style.height="28px",bt.style.color=Ln.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let b=we("activity","18px","currentColor",1.5);b&&bt.appendChild(b);let y=We.clearChatButtonWrapper,E=We.closeButtonWrapper,N=y||E;N&&N.parentNode===Ne?Ne.insertBefore(bt,N):Ne.appendChild(bt),bt.addEventListener("click",()=>{ae?Nn():An()})}let Er=c=>{var y,E,N;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 O=c.querySelector("[data-persona-composer-form]");O!=null&&O.parentNode?O.parentNode.insertBefore(b,O):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let O=h("input");O.type="file",O.accept=((y=g.allowedTypes)!=null?y:Ur).join(","),O.multiple=((E=g.maxFiles)!=null?E:4)>1,O.style.display="none",O.setAttribute("aria-label",(N=g.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(O)}},On=s.find(c=>c.renderComposer);if(On!=null&&On.renderComposer){let c=r.composer,g=On.renderComposer({config:r,defaultRenderer:()=>fs({config:r}).footer,onSubmit:b=>{var O;if(!_||_.isStreaming())return;let y=b.trim(),E=(O=ot==null?void 0:ot.hasAttachments())!=null?O:!1;if(!y&&!E)return;Hs();let N;E&&(N=[],N.push(...ot.getContentParts()),y&&N.push(Js(y))),_.sendMessage(y,{contentParts:N}),E&&ot.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{re==null||re.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:b=>{r.composer={...r.composer,selectedModelId:b},r.agent&&(r.agent={...r.agent,model:b})},onVoiceToggle:((Bc=r.voiceRecognition)==null?void 0:Bc.enabled)===!0?()=>{Dn==null||Dn()}:void 0});g&&(_e.replaceWith(g),_e=g)}let Co=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]"),N=c.querySelector("[data-persona-composer-status]");g&&(Ut=g),b&&(he=b),y&&(pe=y),E&&(z=E,qt=E.parentElement),N&&(gn=N);let O=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Ht=O);let U=c.querySelector(".persona-attachment-button");U&&(et=U,_t=U.parentElement),re=c.querySelector('input[type="file"]'),ve=c.querySelector(".persona-attachment-previews");let H=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");H&&(mt=H)};Er(_e),Co(_e);let In=($c=(Dc=r.layout)==null?void 0:Dc.contentMaxWidth)!=null?$c:$()?(Fc=(Oc=(Nc=r.launcher)==null?void 0:Nc.composerBar)==null?void 0:Oc.contentMaxWidth)!=null?Fc:"720px":void 0;if(In&&($e.style.maxWidth=In,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%"),In&&Ut&&!$()&&(Ut.style.maxWidth=In,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),In&&Ht&&!$()&&(Ht.style.maxWidth=In,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),In&&ve&&!$()&&(ve.style.maxWidth=In,ve.style.marginLeft="auto",ve.style.marginRight="auto"),(_c=r.attachments)!=null&&_c.enabled&&re&&ve){ot=jo.fromConfig(r.attachments),ot.setPreviewsContainer(ve),re.addEventListener("change",b=>{let y=b.target;ot==null||ot.handleFileSelect(y.files),y.value=""});let c=r.attachments.dropOverlay,g=Om(c);fe.appendChild(g)}(()=>{var y,E;let c=(E=(y=r.layout)==null?void 0:y.slots)!=null?E:{},g=N=>{switch(N){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return $e;case"footer-top":return Ht;case"composer":return Ut;case"footer-bottom":return gn;default:return null}},b=(N,O)=>{var U;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")Ne.insertBefore(O,Ne.firstChild);else if(N==="header-right")Ne.appendChild(O);else{let H=Ne.querySelector(".persona-flex-col");H?(U=H.parentNode)==null||U.insertBefore(O,H.nextSibling):Ne.appendChild(O)}break;case"body-top":{let H=X.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(O):X.insertBefore(O,X.firstChild);break}case"body-bottom":X.appendChild(O);break;case"footer-top":Ht.replaceWith(O);break;case"footer-bottom":gn.replaceWith(O);break;default:break}};for(let[N,O]of Object.entries(c))if(O)try{let U=O({config:r,defaultContent:()=>g(N)});U&&b(N,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,U)}})();let Gr=c=>{var O,U;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 N=b.getAttribute("data-bubble-type");if(N==="reasoning")bs.has(E)?bs.delete(E):bs.add(E),Yu(E,y);else if(N==="tool")ys.has(E)?ys.delete(E):ys.add(E),Zu(E,y,r);else if(N==="approval"){let H=r.approval!==!1?r.approval:void 0,Te=((O=H==null?void 0:H.detailsDisplay)!=null?O:"collapsed")==="expanded",ge=(U=Li.get(E))!=null?U:Te;Li.set(E,!ge),hm(E,y,r)}ye.delete(E)};$e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Gr(c))}),$e.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Gr(c))});let Wr=new Map;$e.addEventListener("click",c=>{var O;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 N=b.getAttribute("data-action");if(N==="copy"){let H=_.getMessages().find(Te=>Te.id===E);if(H&&Y.onCopy){let Te=H.content||"";navigator.clipboard.writeText(Te).then(()=>{b.classList.add("persona-message-action-success");let ge=we("check",14,"currentColor",2);ge&&(b.innerHTML="",b.appendChild(ge)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let ee=we("copy",14,"currentColor",2);ee&&(b.innerHTML="",b.appendChild(ee))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),Y.onCopy(H)}}else if(N==="upvote"||N==="downvote"){let H=((O=Wr.get(E))!=null?O:null)===N,Te=N==="upvote"?"thumbs-up":"thumbs-down";if(H){Wr.delete(E),b.classList.remove("persona-message-action-active");let ge=we(Te,14,"currentColor",2);ge&&(b.innerHTML="",b.appendChild(ge))}else{let ge=N==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${ge}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Ve=we(ge==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ve&&(ee.innerHTML="",ee.appendChild(Ve))}Wr.set(E,N),b.classList.add("persona-message-action-active");let Ae=we(Te,14,"currentColor",2);Ae&&(Ae.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(Ae)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let je=_.getMessages().find(st=>st.id===E);je&&Y.onFeedback&&Y.onFeedback({type:N,messageId:je.id,message:je})}}}),$e.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 N=b.getAttribute("data-approval-action");if(!N)return;let O=N==="approve"?"approved":"denied",H=_.getMessages().find(ge=>ge.id===E);if(!(H!=null&&H.approval))return;let Te=y.querySelector("[data-approval-buttons]");Te&&Te.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?_.resolveWebMcpApproval(E,O):_.resolveApproval(H.approval,O)});let St=null,Fn=null,$n={artifacts:[],selectedId:null},Sn=!1,Lt={current:null};$e.addEventListener("click",c=>{var ee,Ae,Me,je,st;let b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.getAttribute("data-download-artifact");if(!y||((Me=(Ae=(ee=r.features)==null?void 0:ee.artifacts)==null?void 0:Ae.onArtifactAction)==null?void 0:Me.call(Ae,{type:"download",artifactId:y}))===!0)return;let N=_.getArtifactById(y),O=N==null?void 0:N.markdown,U=(N==null?void 0:N.title)||"artifact";if(!O){let Ve=b.closest("[data-open-artifact]"),gt=Ve==null?void 0:Ve.closest("[data-message-id]"),pt=gt==null?void 0:gt.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);O=(je=qe==null?void 0:qe.props)==null?void 0:je.markdown,U=((st=qe==null?void 0:qe.props)==null?void 0:st.title)||U}catch{}}}if(!O)return;let H=new Blob([O],{type:"text/markdown"}),Te=URL.createObjectURL(H),ge=document.createElement("a");ge.href=Te,ge.download=`${U}.md`,ge.click(),URL.revokeObjectURL(Te)}),$e.addEventListener("click",c=>{var N,O,U;let b=c.target.closest("[data-open-artifact]");if(!b)return;let y=b.getAttribute("data-open-artifact");!y||((U=(O=(N=r.features)==null?void 0:N.artifacts)==null?void 0:O.onArtifactAction)==null?void 0:U.call(O,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Sn=!1,_.selectArtifact(y),Un())}),$e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let nr=We.composerOverlay,rr=(c,g,b)=>{var U,H,Te,ge;let y=g.trim();if(!y||!Lt.current)return;let E=(U=c.getAttribute("data-tool-call-id"))!=null?U:"",N=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:E,answer:y,answers:b.structured,values:(H=b.values)!=null?H:b.source==="multi"?y.split(", "):[y],isFreeText:N,source:b.source},bubbles:!0,composed:!0})),xo(nr,E);let O=Lt.current.getMessages().find(ee=>{var Ae;return((Ae=ee.toolCall)==null?void 0:Ae.id)===E});(Te=O==null?void 0:O.agentMetadata)!=null&&Te.awaitingLocalTool?Lt.current.resolveAskUserQuestion(O,(ge=b.structured)!=null?ge:y):Lt.current.sendMessage(y)},_n=c=>{var E;let g=Lt.current;if(!g)return;let b=(E=c.getAttribute("data-tool-call-id"))!=null?E:"",y=g.getMessages().find(N=>{var O;return((O=N.toolCall)==null?void 0:O.id)===b});y&&g.persistAskUserQuestionProgress(y,{answers:Mi(c,y),currentIndex:gr(c)})},Xr=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Rr=c=>{var E,N,O;if(((N=(E=r.features)==null?void 0:E.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let g=gr(c),b=vs(c);if(g>=b-1)return;let y=(O=Lt.current)==null?void 0:O.getMessages().find(U=>{var H;return((H=U.toolCall)==null?void 0:H.id)===c.getAttribute("data-tool-call-id")});y&&(ki(c,y,r,g+1),_n(c))};nr.addEventListener("click",c=>{var N,O,U,H,Te,ge,ee,Ae,Me,je,st,Ve,gt,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=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),xo(nr,Ie);let Le=(O=Lt.current)==null?void 0:O.getMessages().find(qe=>{var Ye;return((Ye=qe.toolCall)==null?void 0:Ye.id)===Ie});(U=Le==null?void 0:Le.agentMetadata)!=null&&U.awaitingLocalTool&&((H=Lt.current)==null||H.markAskUserQuestionResolved(Le),(Te=Lt.current)==null||Te.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=yo(y);if(qe&&Le){let Ye=zo(y)[gr(y)],vt=new Set(Array.isArray(Ye)?Ye:[]);vt.has(Ie)?vt.delete(Ie):vt.add(Ie),vo(y,Array.from(vt)),_n(y);return}if(qe){vo(y,Ie),_n(y),Rr(y);return}if(Le){let Ye=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",Ye?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!Ye);let vt=y.querySelector('[data-ask-user-action="submit-multi"]');vt&&(vt.disabled=Ll(y).length===0);return}rr(y,Ie,{source:"pick",values:[Ie]});return}if(E==="submit-multi"){let Ie=Ll(y);if(Ie.length===0)return;rr(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=(ge=Ie==null?void 0:Ie.value)!=null?ge:"";if(!Le.trim())return;if(yo(y)){vo(y,Le.trim()),_n(y),Rr(y);return}rr(y,Le,{source:"free-text"});return}if(E==="next"||E==="back"){if(!Lt.current)return;let Ie=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Le=Lt.current.getMessages().find(Oe=>{var te;return((te=Oe.toolCall)==null?void 0:te.id)===Ie});if(!Le)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Ye=(Me=(Ae=qe==null?void 0:qe.value)==null?void 0:Ae.trim())!=null?Me:"";if(Ye){let Oe=zo(y)[gr(y)];(typeof Oe!="string"||Oe!==Ye)&&vo(y,Ye)}let vt=E==="next"?1:-1,L=gr(y)+vt;ki(y,Le,r,L),_n(y);return}if(E==="submit-all"){if(!Lt.current)return;let Ie=(je=y.getAttribute("data-tool-call-id"))!=null?je:"",Le=Lt.current.getMessages().find(Oe=>{var te;return((te=Oe.toolCall)==null?void 0:te.id)===Ie});if(!Le)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Ye=(Ve=(st=qe==null?void 0:qe.value)==null?void 0:st.trim())!=null?Ve:"";Ye&&vo(y,Ye);let vt=Mi(y,Le);Lt.current.persistAskUserQuestionProgress(Le,{answers:vt,currentIndex:gr(y)});let L=Xr(vt);rr(y,L||"(submitted)",{source:"submit-all",structured:vt});return}if(E==="skip"){if(!Lt.current)return;let Ie=(gt=y.getAttribute("data-tool-call-id"))!=null?gt:"",Le=Lt.current.getMessages().find(te=>{var nt;return((nt=te.toolCall)==null?void 0:nt.id)===Ie});if(!Le)return;let qe=yo(y),Ye=gr(y),vt=vs(y),L=Ye>=vt-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),xo(nr,Ie),(pt=Le.agentMetadata)!=null&&pt.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Le),Lt.current.resolveAskUserQuestion(Le,"(dismissed)"));return}vo(y,"");let Oe=y.querySelector('[data-ask-free-text-input="true"]');if(Oe&&(Oe.value=""),L){let te=Mi(y,Le),nt=Xr(te);rr(y,nt||"(skipped)",{source:"submit-all",structured:te});return}ki(y,Le,r,Ye+1),_n(y);return}}),nr.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let b=c.target;if(!((N=b.matches)!=null&&N.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(yo(y)){vo(y,E.trim()),_n(y),Rr(y);return}rr(y,E,{source:"free-text"})}});let Qr=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=nr.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),N=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];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",Qr);let jn=null,Dt=null,Tn=null,or=null,Yr=()=>{};function Hr(){or==null||or(),or=null}let Zr=()=>{var O;if(!jn||!Dt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),b=((O=e.ownerDocument.defaultView)!=null?O: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=jn.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 N=y.offsetWidth-E/2;Dt.style.left=`${Math.max(0,N)}px`},Mr=()=>{},Un=()=>{var b,y,E,N,O;if(!St||!fr(r))return;Wi(e,r),Ri(e,r),Mr();let c=(N=(E=(y=(b=r.features)==null?void 0:b.artifacts)==null?void 0:y.layout)==null?void 0:E.narrowHostMaxWidth)!=null?N:520,g=oe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),St.update($n),Sn?(St.setMobileOpen(!1),St.element.classList.add("persona-hidden"),(O=St.backdrop)==null||O.classList.add("persona-hidden")):$n.artifacts.length>0&&(St.element.classList.remove("persona-hidden"),St.setMobileOpen(!0)),Yr()};if(fr(r)){oe.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(fe),St=Sm(r,{onSelect:b=>{var y;return(y=Lt.current)==null?void 0:y.selectArtifact(b)},onDismiss:()=>{Sn=!0,Un()}}),St.element.classList.add("persona-hidden"),jn=g,g.appendChild(c),g.appendChild(St.element),St.backdrop&&oe.appendChild(St.backdrop),oe.appendChild(g),Yr=()=>{var y,E,N,O;if(!jn||!St)return;if(!(((N=(E=(y=r.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:N.resizable)===!0)){Tn==null||Tn(),Tn=null,Hr(),Dt&&(Dt.remove(),Dt=null),St.element.style.removeProperty("width"),St.element.style.removeProperty("maxWidth");return}if(!Dt){let U=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let H=e.ownerDocument,Te=(O=H.defaultView)!=null?O:window,ge=ee=>{var gt,pt;if(!St||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||Te.innerWidth<=640)return;ee.preventDefault(),Hr();let Ae=ee.clientX,Me=St.element.getBoundingClientRect().width,je=(pt=(gt=r.features)==null?void 0:gt.artifacts)==null?void 0:pt.layout,st=Ie=>{let Le=jn.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Ye=qe?0:km(jn,Te),vt=qe?0:U.getBoundingClientRect().width||6,L=Me-(Ie.clientX-Ae),Oe=Lm(L,Le,Ye,vt,je==null?void 0:je.resizableMinWidth,je==null?void 0:je.resizableMaxWidth);St.element.style.width=`${Oe}px`,St.element.style.maxWidth="none",Zr()},Ve=()=>{H.removeEventListener("pointermove",st),H.removeEventListener("pointerup",Ve),H.removeEventListener("pointercancel",Ve),or=null;try{U.releasePointerCapture(ee.pointerId)}catch{}};or=Ve,H.addEventListener("pointermove",st),H.addEventListener("pointerup",Ve),H.addEventListener("pointercancel",Ve);try{U.setPointerCapture(ee.pointerId)}catch{}};U.addEventListener("pointerdown",ge),Dt=U,jn.insertBefore(U,St.element),Tn=()=>{U.removeEventListener("pointerdown",ge)}}if(Dt){let U=$n.artifacts.length>0&&!Sn;Dt.classList.toggle("persona-hidden",!U),Zr()}},Mr=()=>{var Te,ge,ee,Ae,Me,je,st,Ve,gt,pt,Ie,Le,qe,Ye;if(!T||!St||((ge=(Te=r.launcher)==null?void 0:Te.sidebarMode)!=null?ge:!1)||ln(r)&&mr(r).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,E=(Me=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Me:!0,N=(st=(je=r.launcher)==null?void 0:je.mobileBreakpoint)!=null?st:640;if(E&&y.innerWidth<=N||!Mm(r,T))return;let O=(pt=(gt=(Ve=r.launcher)==null?void 0:Ve.width)!=null?gt:r.launcherWidth)!=null?pt:Yn,U=(Ye=(qe=(Le=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:Le.layout)==null?void 0:qe.expandedPanelWidth)!=null?Ye:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!Sn?(oe.style.width=U,oe.style.maxWidth=U):(oe.style.width=O,oe.style.maxWidth=O)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{Un()}),Fn.observe(oe))}else oe.appendChild(fe),$()&&Ze&&(We.peekBanner&&Ze.appendChild(We.peekBanner),Ze.appendChild(_e));e.appendChild(me),Ze&&e.appendChild(Ze);let hr=()=>{var Oe,te,nt,Ft,Ot,zt,it,dn,Jn,Ke,Ct,Gn,sn,pr,Xn,ko,os,ss,Xt,Lo,lo,co,$r,Po,rt,yn,fn,pn;if($()){oe.style.width="100%",oe.style.maxWidth="100%";let ft=(te=(Oe=r.launcher)==null?void 0:Oe.composerBar)!=null?te:{},lt=me.dataset.state==="expanded",Mt=(nt=ft.expandedSize)!=null?nt:"anchored";if(!(lt&&Mt!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let tn=(Ot=(Ft=r.theme)==null?void 0:Ft.components)==null?void 0:Ot.panel,Lr=ms(r),an=(Wo,Da)=>{var js;return Wo==null||Wo===""?Da:(js=ps(Lr,Wo))!=null?js:Wo},Mn="1px solid var(--persona-border)",ur="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=an(tn==null?void 0:tn.border,Mn),fe.style.borderRadius=an(tn==null?void 0:tn.borderRadius,Io),fe.style.boxShadow=an(tn==null?void 0:tn.shadow,ur),fe.style.overflow="hidden";return}let c=ln(r),g=(it=(zt=r.launcher)==null?void 0:zt.sidebarMode)!=null?it:!1,b=c||g||((Jn=(dn=r.launcher)==null?void 0:dn.fullHeight)!=null?Jn:!1),y=((Ke=r.launcher)==null?void 0:Ke.enabled)===!1,E=(Gn=(Ct=r.theme)==null?void 0:Ct.components)==null?void 0:Gn.panel,N=ms(r),O=(ft,lt)=>{var Mt;return ft==null||ft===""?lt:(Mt=ps(N,ft))!=null?Mt:ft},U=(sn=e.ownerDocument.defaultView)!=null?sn:window,H=(Xn=(pr=r.launcher)==null?void 0:pr.mobileFullscreen)!=null?Xn:!0,Te=(os=(ko=r.launcher)==null?void 0:ko.mobileBreakpoint)!=null?os:640,ge=U.innerWidth<=Te,ee=H&&ge&&T,Ae=(Xt=(ss=r.launcher)==null?void 0:ss.position)!=null?Xt:"bottom-left",Me=Ae==="bottom-left"||Ae==="top-left",je=(lo=(Lo=r.launcher)==null?void 0:Lo.zIndex)!=null?lo:wn,st=g||ee?"none":"1px solid var(--persona-border)",Ve=ee?"none":g?Me?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Ve="none",st="none");let gt=g||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",pt=O(E==null?void 0:E.border,st),Ie=O(E==null?void 0:E.shadow,Ve),Le=O(E==null?void 0:E.borderRadius,gt),qe=X.scrollTop;e.style.cssText="",me.style.cssText="",oe.style.cssText="",fe.style.cssText="",X.style.cssText="",_e.style.cssText="";let Ye=()=>{var lt;if(qe<=0)return;((lt=X.ownerDocument.defaultView)!=null?lt:window).requestAnimationFrame(()=>{if(X.scrollTop===qe)return;let Mt=X.scrollHeight-X.clientHeight;Mt<=0||(X.scrollTop=Math.min(qe,Mt))})};if(ee){me.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),me.style.cssText=`
|
|
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=`
|
|
31
31
|
position: fixed !important;
|
|
32
32
|
inset: 0 !important;
|
|
33
33
|
width: 100% !important;
|
|
@@ -37,9 +37,9 @@ _Details: ${n.message}_`:r}var Qs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
37
37
|
padding: 0 !important;
|
|
38
38
|
display: flex !important;
|
|
39
39
|
flex-direction: column !important;
|
|
40
|
-
z-index: ${
|
|
40
|
+
z-index: ${Te} !important;
|
|
41
41
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
42
|
-
`,
|
|
42
|
+
`,fe.style.cssText=`
|
|
43
43
|
position: relative !important;
|
|
44
44
|
display: flex !important;
|
|
45
45
|
flex-direction: column !important;
|
|
@@ -52,7 +52,7 @@ _Details: ${n.message}_`:r}var Qs=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
|
-
`,
|
|
55
|
+
`,z.style.cssText=`
|
|
56
56
|
display: flex !important;
|
|
57
57
|
flex-direction: column !important;
|
|
58
58
|
flex: 1 1 0% !important;
|
|
@@ -63,20 +63,20 @@ _Details: ${n.message}_`:r}var Qs=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
|
-
`,
|
|
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=`
|
|
67
67
|
position: fixed !important;
|
|
68
68
|
top: 0 !important;
|
|
69
69
|
bottom: 0 !important;
|
|
70
|
-
width: ${
|
|
70
|
+
width: ${ut} !important;
|
|
71
71
|
height: 100vh !important;
|
|
72
72
|
max-height: 100vh !important;
|
|
73
73
|
margin: 0 !important;
|
|
74
74
|
padding: 0 !important;
|
|
75
75
|
display: flex !important;
|
|
76
76
|
flex-direction: column !important;
|
|
77
|
-
z-index: ${
|
|
78
|
-
${
|
|
79
|
-
`,
|
|
77
|
+
z-index: ${Te} !important;
|
|
78
|
+
${_e?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
79
|
+
`,fe.style.cssText=`
|
|
80
80
|
position: relative !important;
|
|
81
81
|
display: flex !important;
|
|
82
82
|
flex-direction: column !important;
|
|
@@ -89,7 +89,7 @@ _Details: ${n.message}_`:r}var Qs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
89
89
|
padding: 0 !important;
|
|
90
90
|
box-shadow: ${Ie} !important;
|
|
91
91
|
border-radius: ${Le} !important;
|
|
92
|
-
`,
|
|
92
|
+
`,fe.style.setProperty("width","100%","important"),fe.style.setProperty("max-width","100%","important"),z.style.cssText=`
|
|
93
93
|
display: flex !important;
|
|
94
94
|
flex-direction: column !important;
|
|
95
95
|
flex: 1 1 0% !important;
|
|
@@ -100,27 +100,27 @@ _Details: ${n.message}_`:r}var Qs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
100
100
|
overflow: hidden !important;
|
|
101
101
|
border-radius: ${Le} !important;
|
|
102
102
|
border: ${pt} !important;
|
|
103
|
-
`,
|
|
103
|
+
`,je.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 ft="max-height: -moz-available !important; max-height: stretch !important;",lt=g?"":"padding-top: 1.25em !important;",Mt=g?"":`z-index: ${(pn=(fn=r.launcher)==null?void 0:fn.zIndex)!=null?pn:wn} !important;`;me.style.cssText+=ft+lt+Mt}Ye()};hr(),uo(e,r),Wi(e,r),Ri(e,r);let xt=[];xt.push(()=>{document.removeEventListener("keydown",Qr)});let Qt=null,Yt=null;xt.push(()=>{Qt==null||Qt(),Qt=null,Yt==null||Yt(),Yt=null}),Fn&&xt.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),xt.push(()=>{Tn==null||Tn(),Tn=null,Hr(),Dt&&(Dt.remove(),Dt=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),He&&xt.push(()=>{Se!==null&&(cancelAnimationFrame(Se),Se=null),le==null||le.destroy(),le=null,V==null||V.destroy(),V=null,J=null});let qn=null,eo=()=>{qn&&(qn(),qn=null),r.colorScheme==="auto"&&(qn=ai(()=>{uo(e,r)}))};eo(),xt.push(()=>{qn&&(qn(),qn=null)});let sr=(jc=r.features)==null?void 0:jc.streamAnimation;if(sr!=null&&sr.type&&sr.type!=="none"){let c=oa(sr.type,sr.plugins);c&&(pl(c,e),xt.push(()=>qu(e)))}let br=bm(Ht),zn=null,_,ar=!1,ye=Bu(),Vn=new Map,ir=new Map,yr=new Map,Ts=0,xr=ci(),vr=0,wr=null,Br=!1,Ao=!1,va=4,Es=24,wa=80,Xo=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ms=(qc=(Uc=r.voiceRecognition)==null?void 0:Uc.autoResume)!=null?qc:!1,lr=c=>{o.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},Wn=()=>{m(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Ca=()=>{var y,E;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Dl(d.voiceState),g=!!c.active,b=Number((E=c.timestamp)!=null?E:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<Kh&&setTimeout(()=>{var N,O;yt.active||(yt.manuallyDeactivated=!1,((O=(N=r.voiceRecognition)==null?void 0:N.provider)==null?void 0:O.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("restore"),_.isVoiceActive()&&M()}):Mo("restore"))},1e3)},Aa=()=>_?Dm(_.getMessages()).filter(c=>!c.__skipPersist):[];function Qo(c){if(!(i!=null&&i.save))return;let b={messages:c?Dm(c):_?Aa():[],metadata:d,artifacts:$n.artifacts,selectedArtifactId:$n.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 Dr=null,Sa=()=>me.querySelector("#persona-scroll-container")||X,So=()=>{Dr!==null&&(cancelAnimationFrame(Dr),Dr=null),Br=!1},ks=()=>{wr!==null&&(cancelAnimationFrame(wr),wr=null),Ao=!1,So()},Nr=()=>{if(!Cn()||ae){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==fe&&fe.appendChild(Wt),At();let c=ea(X)>0;Wt.style.display=xr.isFollowing()||!c?"none":""},Ls=()=>{xr.pause()&&(ks(),Nr())},to=()=>{xr.resume(),Nr()},no=(c=!1)=>{xr.isFollowing()&&(!c&&!ar||(wr!==null&&(cancelAnimationFrame(wr),wr=null),Ao=!0,wr=requestAnimationFrame(()=>{wr=null,Ao=!1,xr.isFollowing()&&Ta(Sa(),c?220:140)})))},Ta=(c,g=500)=>{let b=c.scrollTop,y=ea(c),E=y-b;if(Math.abs(E)<1){vr=c.scrollTop;return}if(Math.abs(E)>=wa){So(),Br=!0,c.scrollTop=y,vr=c.scrollTop,Br=!1;return}So();let N=performance.now();Br=!0;let O=H=>1-Math.pow(1-H,3),U=H=>{if(!xr.isFollowing()){So();return}let Te=ea(c);Te!==y&&(y=Te,E=y-b);let ge=H-N,ee=Math.min(ge/g,1),Ae=O(ee),Me=b+E*Ae;c.scrollTop=Me,vr=c.scrollTop,ee<1?Dr=requestAnimationFrame(U):(c.scrollTop=y,vr=c.scrollTop,Dr=null,Br=!1)};Dr=requestAnimationFrame(U)},Ea=c=>{let g=new Map;c.forEach(b=>{let y=Xo.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!y&&b.role==="assistant"&&o.emit("assistant:message",b),b.role==="assistant"&&(y!=null&&y.streaming)&&b.streaming===!1&&o.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(y?b.approval.status!=="pending"&&o.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):o.emit("approval:requested",{approval:b.approval,message:b}))}),Xo.clear(),g.forEach((b,y)=>{Xo.set(y,b)})},To=(c,g,b)=>{var pt,Ie,Le,qe,Ye,vt;let y=document.createElement("div"),N=(()=>{var Oe;let L=s.find(te=>te.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((Oe=r.loadingIndicator)!=null&&Oe.render)return r.loadingIndicator.render})(),O=(L,Oe)=>Oe==null?!1:typeof Oe=="string"?(L.textContent=Oe,!0):(L.appendChild(Oe),!0),U=new Set,H=new Set,Te=s.some(L=>L.renderAskUserQuestion),ge=[],ee=[],Ae=r.enableComponentStreaming!==!1,Me=s.some(L=>L.renderApproval)&&r.approval!==!1,je=[];if(g.forEach(L=>{var Ct,Gn,sn,pr,Xn,ko,os,ss,Xt,Lo,lo,co,$r,Po;U.add(L.id);let Oe=Te&&zr(L),te=Me&&L.variant==="approval"&&!!L.approval,nt=!Oe&&L.role==="assistant"&&!L.variant&&Ae&&Ni(L);if(!te&&yr.has(L.id)){let rt=c.querySelector(`#wrapper-${L.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),yr.delete(L.id)}if(!nt&&ir.has(L.id)){let rt=c.querySelector(`#wrapper-${L.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),ir.delete(L.id)}let Ft=zr(L)?`:${(Ct=L.agentMetadata)!=null&&Ct.askUserQuestionAnswered?"a":"u"}:${(Gn=L.agentMetadata)!=null&&Gn.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=Hu(L,Ts)+Ft,zt=Oe||te||nt?null:Du(ye,L.id,Ot);if(zt){y.appendChild(zt.cloneNode(!0)),zr(L)&&((sn=L.toolCall)!=null&&sn.id)&&((pr=L.agentMetadata)==null?void 0:pr.awaitingLocalTool)===!0&&!((Xn=L.agentMetadata)!=null&&Xn.askUserQuestionAnswered)&&(H.add(L.toolCall.id),ws(L,r,We.composerOverlay));return}let it=null,dn=s.find(rt=>!!(L.variant==="reasoning"&&rt.renderReasoning||L.variant==="tool"&&rt.renderToolCall||!L.variant&&rt.renderMessage)),Jn=(ko=r.layout)==null?void 0:ko.messages;if(zr(L)&&((os=L.agentMetadata)==null?void 0:os.askUserQuestionAnswered)===!0){Vn.delete(L.id);let rt=c.querySelector(`#wrapper-${L.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(zr(L)&&((Xt=(ss=r.features)==null?void 0:ss.askUserQuestion)==null?void 0:Xt.enabled)!==!1){let rt=s.find(yn=>typeof yn.renderAskUserQuestion=="function");if(rt&&Lt.current){let yn=Vn.get(L.id),fn=yn!==Ot,pn=null;if(fn){let{payload:Mt,complete:Rn}=Vr(L),tn=L.id,Lr=()=>{var an;return(an=Lt.current)==null?void 0:an.getMessages().find(Mn=>Mn.id===tn)};pn=rt.renderAskUserQuestion({message:L,payload:Mt,complete:Rn,resolve:an=>{var ur;let Mn=Lr();Mn&&((ur=Lt.current)==null||ur.resolveAskUserQuestion(Mn,an))},dismiss:()=>{var Mn,ur,Io;let an=Lr();(Mn=an==null?void 0:an.agentMetadata)!=null&&Mn.awaitingLocalTool&&((ur=Lt.current)==null||ur.markAskUserQuestionResolved(an),(Io=Lt.current)==null||Io.resolveAskUserQuestion(an,"(dismissed)"))},config:r})}let ft=yn!=null;if(fn&&pn===null&&!ft){((Lo=L.agentMetadata)==null?void 0:Lo.awaitingLocalTool)===!0&&!((lo=L.agentMetadata)!=null&&lo.askUserQuestionAnswered)&&(H.add(L.toolCall.id),ws(L,r,We.composerOverlay));return}let lt=document.createElement("div");lt.className="persona-flex",lt.id=`wrapper-${L.id}`,lt.setAttribute("data-wrapper-id",L.id),lt.setAttribute("data-ask-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),y.appendChild(lt),ge.push({messageId:L.id,fingerprint:Ot,bubble:pn});return}else{((co=L.agentMetadata)==null?void 0:co.awaitingLocalTool)===!0&&!(($r=L.agentMetadata)!=null&&$r.askUserQuestionAnswered)&&(H.add(L.toolCall.id),ws(L,r,We.composerOverlay));return}}else if(te){let rt=s.find(ft=>typeof ft.renderApproval=="function"),fn=yr.get(L.id)!==Ot,pn=null;if(fn&&(rt!=null&&rt.renderApproval)){let ft=L.id,lt=(Mt,Rn)=>{var Lr,an,Mn;let tn=(Lr=Lt.current)==null?void 0:Lr.getMessages().find(ur=>ur.id===ft);tn!=null&&tn.approval&&(tn.approval.toolType==="webmcp"?(an=Lt.current)==null||an.resolveWebMcpApproval(tn.id,Mt):(Mn=Lt.current)==null||Mn.resolveApproval(tn.approval,Mt,Rn))};pn=rt.renderApproval({message:L,defaultRenderer:()=>Pi(L,r),config:r,approve:Mt=>lt("approved",Mt),deny:Mt=>lt("denied",Mt)})}if(fn&&pn===null){let ft=c.querySelector(`#wrapper-${L.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),yr.delete(L.id),it=Pi(L,r)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${L.id}`,ft.setAttribute("data-wrapper-id",L.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),y.appendChild(ft),je.push({messageId:L.id,fingerprint:Ot,bubble:pn});return}}else if(dn)if(L.variant==="reasoning"&&L.reasoning&&dn.renderReasoning){if(!Ge)return;it=dn.renderReasoning({message:L,defaultRenderer:()=>wl(L,r),config:r})}else if(L.variant==="tool"&&L.toolCall&&dn.renderToolCall){if(!Ce)return;it=dn.renderToolCall({message:L,defaultRenderer:()=>Cl(L,r),config:r})}else dn.renderMessage&&(it=dn.renderMessage({message:L,defaultRenderer:()=>{let rt=hs(L,b,Jn,r.messageActions,Y,{loadingIndicatorRenderer:N,widgetConfig:r});return L.role!=="user"&&Rl(rt,L,r,_),rt},config:r}));if(!it&&nt){let rt=Oi(L);if(rt){let yn=ir.get(L.id),fn=yn!==Ot,pn=r.wrapComponentDirectiveInBubble!==!1,ft=null;if(fn){let lt=Di(rt,{config:r,message:L,transform:b});if(lt)if(pn){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-${L.id}`,Mt.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let Rn=document.createElement("div");Rn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Rn.innerHTML=b({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Mt.appendChild(Rn)}Mt.appendChild(lt),ft=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-${L.id}`,Mt.setAttribute("data-message-id",L.id),Mt.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let Rn=document.createElement("div");Rn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Rn.innerHTML=b({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Mt.appendChild(Rn)}Mt.appendChild(lt),ft=Mt}}if(ft||yn!=null){let lt=document.createElement("div");lt.className="persona-flex",lt.id=`wrapper-${L.id}`,lt.setAttribute("data-wrapper-id",L.id),lt.setAttribute("data-component-directive-stub","true"),lt.setAttribute("data-preserve-runtime","true"),pn||lt.classList.add("persona-w-full"),y.appendChild(lt),ee.push({messageId:L.id,fingerprint:Ot,bubble:ft});return}}}if(!it)if(L.variant==="reasoning"&&L.reasoning){if(!Ge)return;it=wl(L,r)}else if(L.variant==="tool"&&L.toolCall){if(!Ce)return;it=Cl(L,r)}else if(L.variant==="approval"&&L.approval){if(r.approval===!1)return;it=Pi(L,r)}else{let rt=(Po=r.layout)==null?void 0:Po.messages;rt!=null&&rt.renderUserMessage&&L.role==="user"?it=rt.renderUserMessage({message:L,config:r,streaming:!!L.streaming}):rt!=null&&rt.renderAssistantMessage&&L.role==="assistant"?it=rt.renderAssistantMessage({message:L,config:r,streaming:!!L.streaming}):it=hs(L,b,rt,r.messageActions,Y,{loadingIndicatorRenderer:N,widgetConfig:r}),L.role!=="user"&&it&&Rl(it,L,r,_)}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${L.id}`,Ke.setAttribute("data-wrapper-id",L.id),L.role==="user"&&Ke.classList.add("persona-justify-end"),(it==null?void 0:it.getAttribute("data-persona-component-directive"))==="true"&&Ke.classList.add("persona-w-full"),Ke.appendChild(it),Nu(ye,L.id,Ot,Ke),y.appendChild(Ke)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Oe=>{let te=Oe.getAttribute("data-persona-ask-sheet-for");te&&!H.has(te)&&xo(We.composerOverlay,te)}),(Ie=(pt=r.features)==null?void 0:pt.toolCallDisplay)!=null&&Ie.grouped){let L=[],Oe=[];g.forEach(te=>{if(te.variant==="tool"&&te.toolCall&&Ce){Oe.push(te);return}Oe.length>1&&L.push(Oe),Oe=[]}),Oe.length>1&&L.push(Oe),L.forEach((te,nt)=>{var Ct,Gn;let Ft=te.map(sn=>Array.from(y.children).find(pr=>pr instanceof HTMLElement&&pr.getAttribute("data-wrapper-id")===sn.id)).filter(sn=>!!sn);if(Ft.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${nt}-${te[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${nt}-${te[0].id}`);let zt=document.createElement("div");zt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",zt.setAttribute("data-persona-tool-group","true");let it=document.createElement("div");it.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${te.length} tools`,Jn=(Gn=(Ct=r.toolCall)==null?void 0:Ct.renderGroupedSummary)==null?void 0:Gn.call(Ct,{messages:te,toolCalls:te.map(sn=>sn.toolCall).filter(sn=>!!sn),defaultSummary:dn,config:r});O(it,Jn)||(it.textContent=dn);let Ke=document.createElement("div");Ke.className="persona-tool-group-stack persona-flex persona-flex-col",zt.append(it,Ke),Ot.appendChild(zt),Ft[0].before(Ot),Ft.forEach((sn,pr)=>{let Xn=document.createElement("div");Xn.className="persona-tool-group-item persona-relative",Xn.setAttribute("data-persona-tool-group-item","true"),pr<Ft.length-1&&Xn.setAttribute("data-persona-tool-group-connector","true"),Xn.appendChild(sn),Ke.appendChild(Xn)})})}Ou(ye,U);let st=g.some(L=>L.role==="assistant"&&L.streaming),Ve=g[g.length-1],gt=(Ve==null?void 0:Ve.role)==="assistant"&&!Ve.streaming&&Ve.variant!=="approval";if(ar&&g.some(L=>L.role==="user")&&!st&&!gt){let L={config:r,streaming:!0,location:"standalone",defaultRenderer:qo},Oe=s.find(nt=>nt.renderLoadingIndicator),te=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(te=Oe.renderLoadingIndicator(L)),te===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(te=r.loadingIndicator.render(L)),te===null&&(te=qo()),te){let nt=document.createElement("div"),Ft=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;nt.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(" "),nt.setAttribute("data-typing-indicator","true"),nt.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",nt.appendChild(te);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(nt),y.appendChild(Ot)}}if(!ar&&g.length>0){let L=g[g.length-1],Oe={config:r,lastMessage:L,messageCount:g.length},te=s.find(Ft=>Ft.renderIdleIndicator),nt=null;if(te!=null&&te.renderIdleIndicator&&(nt=te.renderIdleIndicator(Oe)),nt===null&&((Ye=r.loadingIndicator)!=null&&Ye.renderIdle)&&(nt=r.loadingIndicator.renderIdle(Oe)),nt){let Ft=document.createElement("div"),Ot=((vt=r.loadingIndicator)==null?void 0:vt.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(nt);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-idle-indicator",zt.setAttribute("data-wrapper-id","idle-indicator"),zt.appendChild(Ft),y.appendChild(zt)}}if(ii(c,y),ge.length>0)for(let{messageId:L,fingerprint:Oe,bubble:te}of ge){let nt=c.querySelector(`#wrapper-${L}`);nt&&te!==null&&(nt.replaceChildren(te),nt.setAttribute("data-bubble-fp",Oe),Vn.set(L,Oe))}if(Vn.size>0)for(let L of Vn.keys())U.has(L)||Vn.delete(L);if(ee.length>0)for(let{messageId:L,fingerprint:Oe,bubble:te}of ee){let nt=c.querySelector(`#wrapper-${L}`);nt&&te!==null&&(nt.replaceChildren(te),nt.setAttribute("data-bubble-fp",Oe),ir.set(L,Oe))}if(ir.size>0)for(let L of ir.keys())U.has(L)||ir.delete(L);if(je.length>0)for(let{messageId:L,fingerprint:Oe,bubble:te}of je){let nt=c.querySelector(`#wrapper-${L}`);nt&&te!==null&&(nt.replaceChildren(te),nt.setAttribute("data-bubble-fp",Oe),yr.set(L,Oe))}if(yr.size>0)for(let L of yr.keys())U.has(L)||yr.delete(L)},ro=null,Ma=()=>{var b;if(ro)return;let c=y=>{let E=y.composedPath();E.includes(me)||Ze&&E.includes(Ze)||Nt(!1,"user")};ro=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},Ps=()=>{var g;if(!ro)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",ro,!0),ro=null};xt.push(()=>Ps());let oo=null,ka=()=>{var b;if(oo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Nt(!1,"user"))};oo=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Is=()=>{var g;if(!oo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",oo,!0),oo=null};xt.push(()=>Is());let so=!1,Ws=new Set,La=()=>{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)},Or=()=>{var gt,pt,Ie,Le;if(!$())return;let c=We.peekBanner,g=We.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let b=(gt=_==null?void 0:_.getMessages())!=null?gt:[],y;for(let qe=b.length-1;qe>=0;qe--){let Ye=b[qe];if(Ye.role==="assistant"&&Ye.content){y=Ye;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let E=y.content,N=!!y.streaming,O=La(),U=ui(O),H=U.type!=="none"?oa(U.type,O==null?void 0:O.plugins):null,Te=((pt=H==null?void 0:H.isAnimating)==null?void 0:pt.call(H,y))===!0,ge=H!==null&&(N||Te);ge&&H&&!Ws.has(H.name)&&(pl(H,e),Ws.add(H.name));let ee=ge&&(H!=null&&H.containerClass)?H.containerClass:null,Ae=(Ie=g.dataset.personaPeekStreamClass)!=null?Ie:null;Ae&&Ae!==ee&&(g.classList.remove(Ae),delete g.dataset.personaPeekStreamClass),ee&&Ae!==ee&&(g.classList.add(ee),g.dataset.personaPeekStreamClass=ee),ge?(g.style.setProperty("--persona-stream-step",`${U.speed}ms`),g.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Me=ge?mi(E,U.buffer,H,y,N):E;if(ge&&U.placeholder==="skeleton"&&N&&(!Me||!Me.trim())){let qe=document.createElement("div"),Ye=aa();Ye.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Ye),ii(g,qe)}else{let qe=Math.max(0,Me.length-100),Ye=Me.length>100?Me.slice(-100):Me,vt=Do(Ye);if(!ge||!H){let L=Me.length>100?`\u2026${Ye}`:Ye;g.textContent!==L&&(g.textContent=L)}else{let L=vt;(H.wrap==="char"||H.wrap==="word")&&(L=sa(vt,H.wrap,`peek-${y.id}`,{skipTags:H.skipTags,startIndex:qe}));let Oe=document.createElement("div");if(Oe.innerHTML=L,H.useCaret&&Ye.length>0){let te=gi(),nt=Oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=nt[nt.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(te,Ft.nextSibling):Oe.appendChild(te)}ii(g,Oe),(Le=H.onAfterRender)==null||Le.call(H,{container:g,bubble:c,messageId:y.id,message:y,speed:U.speed,duration:U.duration})}}let Ve=ar||so;c.classList.toggle("persona-pill-peek--visible",Ve)};if($()){let c=We.peekBanner;if(c){let y=E=>{E.preventDefault(),E.stopPropagation(),Nt(!0,"user")};c.addEventListener("pointerdown",y),xt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{so||(so=!0,Or())},b=()=>{so&&(so=!1,Or())};oe.addEventListener("pointerenter",g),oe.addEventListener("pointerleave",b),xt.push(()=>{oe.removeEventListener("pointerenter",g),oe.removeEventListener("pointerleave",b)}),Ze&&(Ze.addEventListener("pointerenter",g),Ze.addEventListener("pointerleave",b),xt.push(()=>{Ze.removeEventListener("pointerenter",g),Ze.removeEventListener("pointerleave",b)}))}let Pa=c=>{var Ae,Me,je,st,Ve,gt,pt,Ie;let g=(Me=(Ae=r.launcher)==null?void 0:Ae.composerBar)!=null?Me:{},b=(je=g.expandedSize)!=null?je:"anchored",y=(st=g.bottomOffset)!=null?st:"16px",E=g.collapsedMaxWidth,N=(Ve=g.expandedMaxWidth)!=null?Ve:"880px",O=(gt=g.expandedTopOffset)!=null?gt:"5vh",U=(pt=g.modalMaxWidth)!=null?pt:"880px",H=(Ie=g.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",Te="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",ee=me.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Ze){let Le=Ze.style;Le.bottom=y,Le.width=E!=null?E:""}if(c&&b!=="fullscreen"){if(b==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=U,ee.maxWidth=Te,ee.maxHeight=H,ee.height=H;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${ge})`,ee.top=O,ee.width=N,ee.maxWidth=Te}},ao=()=>{var H,Te,ge,ee,Ae,Me,je,st;if(!D())return;if($()){let gt=(ge=((Te=(H=r.launcher)==null?void 0:H.composerBar)!=null?Te:{}).expandedSize)!=null?ge:"anchored",pt=R?"expanded":"collapsed";me.dataset.state=pt,me.dataset.expandedSize=gt,Ze&&(Ze.dataset.state=pt,Ze.dataset.expandedSize=gt),me.style.removeProperty("display"),me.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Pa(R),fe.style.display=R?"flex":"none",hr(),R?(Ma(),ka()):(Ps(),Is()),Or();return}let c=ln(r),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,b=(Me=(Ae=r.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?Me:640,y=(st=(je=r.launcher)==null?void 0:je.mobileFullscreen)!=null?st:!0,E=g.innerWidth<=b,N=y&&E&&T,O=mr(r).reveal;R?(me.style.removeProperty("display"),me.style.display=c?"flex":"",me.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-95","persona-opacity-0"),oe.classList.add("persona-scale-100","persona-opacity-100"),Qe?Qe.element.style.display="none":tt&&(tt.style.display="none")):(c?c&&(O==="overlay"||O==="push")&&!N?(me.style.removeProperty("display"),me.style.display="flex",me.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(me.style.setProperty("display","none","important"),me.classList.remove("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(me.style.display="",me.classList.add("persona-pointer-events-none","persona-opacity-0"),oe.classList.remove("persona-scale-100","persona-opacity-100"),oe.classList.add("persona-scale-95","persona-opacity-0")),Qe?Qe.element.style.display=c?"none":"":tt&&(tt.style.display=c?"none":""))},Nt=(c,g="user")=>{var N,O;if(!D()||R===c)return;let b=R;R=c,ao();let y=(()=>{var je,st,Ve,gt,pt,Ie,Le,qe,Ye,vt;let U=(st=(je=r.launcher)==null?void 0:je.sidebarMode)!=null?st:!1,H=(Ve=e.ownerDocument.defaultView)!=null?Ve:window,Te=(pt=(gt=r.launcher)==null?void 0:gt.mobileFullscreen)!=null?pt:!0,ge=(Le=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Le:640,ee=H.innerWidth<=ge,Ae=ln(r)&&Te&&ee,Me=$()&&((vt=(Ye=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Ye.expandedSize)!=null?vt:"fullscreen")==="fullscreen";return U||Te&&ee&&T||Ae||Me})();if(R&&y){if(!Qt){let U=e.getRootNode(),H=U instanceof ShadowRoot?U.host:e.closest(".persona-host");H&&(Qt=ul(H,(O=(N=r.launcher)==null?void 0:N.zIndex)!=null?O:wn))}Yt||(Yt=ml(e.ownerDocument))}else R||(Qt==null||Qt(),Qt=null,Yt==null||Yt(),Yt=null);R&&(Zt(),no(!0));let E={open:R,source:g,timestamp:Date.now()};R&&!b?o.emit("widget:opened",E):!R&&b&&o.emit("widget:closed",E),o.emit("widget:state",{open:R,launcherEnabled:T,voiceActive:yt.active,streaming:_.isStreaming()})},Yo=c=>{Kt(c?"stop":"send"),z&&(z.disabled=c),br.buttons.forEach(g=>{g.disabled=c}),_e.dataset.personaComposerStreaming=c?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Zo=()=>{yt.active||he&&he.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Zo(),200)});let Rs=()=>{var b,y,E,N,O,U,H,Te,ge,ee,Ae;Bn.textContent=(y=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?y:"Hello \u{1F44B}",er.textContent=(N=(E=r.copy)==null?void 0:E.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",he.placeholder=(U=(O=r.copy)==null?void 0:O.inputPlaceholder)!=null?U:"How can I help...";let c=X.querySelector("[data-persona-intro-card]");if(c){let Me=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;c.style.display=Me?"":"none",Me?(X.classList.remove("persona-gap-3"),X.classList.add("persona-gap-6")):(X.classList.remove("persona-gap-6"),X.classList.add("persona-gap-3"))}!((ge=(Te=r.sendButton)==null?void 0:Te.useIcon)!=null&&ge)&&!(_!=null&&_.isStreaming())&&(pe.textContent=(Ae=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?Ae:"Send"),he.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',he.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 kr=null,Ia=()=>{kr==null&&(kr=setInterval(()=>{let c=$e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(kr),kr=null;return}let g=Date.now();c.forEach(b=>{let y=Number(b.getAttribute("data-tool-elapsed"));y&&(b.textContent=_a(g-y))})},100))};if(_=new ds(r,{onMessagesChanged(c){To($e,c,Re),Ia(),_&&(c.some(E=>E.role==="user")?br.render([],_,he,c):br.render(r.suggestionChips,_,he,c,r.suggestionChipsConfig)),no(!ar),Ea(c);let g=[...c].reverse().find(y=>y.role==="user"),b=yt.lastUserMessageId;g&&g.id!==b&&(yt.lastUserMessageId=g.id,o.emit("user:message",g)),yt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Qo(c),Or()},onStatusChanged(c){var y;let g=(y=r.statusIndicator)!=null?y:{};xe(gn,(E=>{var N,O,U,H;return E==="idle"?(N=g.idleText)!=null?N:vn.idle:E==="connecting"?(O=g.connectingText)!=null?O:vn.connecting:E==="connected"?(U=g.connectedText)!=null?U:vn.connected:E==="error"?(H=g.errorText)!=null?H:vn.error:vn[E]})(c),g,c)},onStreamingChanged(c){ar=c,Yo(c),_&&To($e,_.getMessages(),Re),c||no(!0),Or()},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":G(),Z();break;case"speaking":G(),ie();break;default:c==="idle"&&_.isBargeInActive()?(G(),M(),z==null||z.setAttribute("aria-label","End voice session")):(yt.active=!1,G(),lr("system"),Wn());break}},onArtifactsState(c){$n=c,Un(),Qo()}}),Lt.current=_,((Vc=(zc=r.voiceRecognition)==null?void 0:zc.provider)==null?void 0:Vc.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)}),(V||r.onSSEEvent)&&_.setSSEEventCallback((c,g)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,g),de==null||de.processEvent(c,g),V==null||V.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;c&&(c.metadata&&(d=Dl(c.metadata),w.syncFromMetadata()),(g=c.messages)!=null&&g.length&&_.hydrateMessages(c.messages),(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 Hs=()=>{var g,b,y;!$()||R||!((y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||y)||Nt(!0,"auto")},Bs=c=>{var E;if(c.preventDefault(),_.isStreaming()){_.cancel(),de==null||de.reset(),le==null||le.update();return}let g=he.value.trim(),b=(E=ot==null?void 0:ot.hasAttachments())!=null?E:!1;if(!g&&!b)return;Hs();let y;b&&(y=[],y.push(...ot.getContentParts()),g&&y.push(Js(g))),he.value="",he.style.height="auto",Eo(),_.sendMessage(g,{contentParts:y}),b&&ot.clearAttachments()},Wa=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},es={...li},ts=!1,Eo=()=>{es={...li}},Ra=()=>_.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),Ha=c=>{if(!he)return;ts=!0,he.value=c,he.dispatchEvent(new Event("input",{bubbles:!0})),ts=!1;let g=he.value.length;he.setSelectionRange(g,g)},Ds=()=>{ts||Eo()},Ns=c=>{if(he){if(Wa()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=he.selectionStart===0&&he.selectionEnd===0,b=Ru({direction:c.key==="ArrowUp"?"up":"down",history:Ra(),currentValue:he.value,atStart:g,state:es});if(es=b.state,b.handled){c.preventDefault(),b.value!==void 0&&Ha(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(_.isStreaming()){c.preventDefault();return}Eo(),c.preventDefault(),pe.click()}}},Os=c=>{c.key!=="Escape"||c.isComposing||_.isStreaming()&&c.composedPath().includes(fe)&&(_.cancel(),de==null||de.reset(),le==null||le.update(),Eo(),c.preventDefault(),c.stopImmediatePropagation())},Fs=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!ot)return;let g=Gh(c.clipboardData);g.length!==0&&(c.preventDefault(),await ot.handleFiles(g))},En=null,Kn=!1,Fr=null,ct=null,$s=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Mo=(c="user")=>{var N,O,U,H,Te,ge,ee;if(Kn||_.isStreaming())return;let g=$s();if(!g)return;En=new g;let y=(O=((N=r.voiceRecognition)!=null?N:{}).pauseDuration)!=null?O:2e3;En.continuous=!0,En.interimResults=!0,En.lang="en-US";let E=he.value;En.onresult=Ae=>{let Me="",je="";for(let Ve=0;Ve<Ae.results.length;Ve++){let gt=Ae.results[Ve],pt=gt[0].transcript;gt.isFinal?Me+=pt+" ":je=pt}let st=E+Me+je;he.value=st,Fr&&clearTimeout(Fr),(Me||je)&&(Fr=window.setTimeout(()=>{let Ve=he.value.trim();Ve&&En&&Kn&&(Cr(),he.value="",he.style.height="auto",_.sendMessage(Ve,{viaVoice:!0}))},y))},En.onerror=Ae=>{Ae.error!=="no-speech"&&Cr()},En.onend=()=>{if(Kn){let Ae=he.value.trim();Ae&&Ae!==E.trim()&&(he.value="",he.style.height="auto",_.sendMessage(Ae,{viaVoice:!0})),Cr()}};try{if(En.start(),Kn=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),lr(c),Wn(),z){let Ae=(U=r.voiceRecognition)!=null?U:{};ct={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(H=Ae.iconName)!=null?H:"mic",iconSize:parseFloat((ee=(ge=Ae.iconSize)!=null?ge:(Te=r.sendButton)==null?void 0:Te.size)!=null?ee:"40")||24};let Me=Ae.recordingBackgroundColor,je=Ae.recordingIconColor,st=Ae.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=Me!=null?Me:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=je!=null?je:"var(--persona-voice-recording-indicator, #ffffff)",je){let Ve=z.querySelector("svg");Ve&&Ve.setAttribute("stroke",je)}st&&(z.style.borderColor=st),z.setAttribute("aria-label","Stop voice recognition")}}catch{Cr("system")}},Cr=(c="user")=>{if(Kn){if(Kn=!1,Fr&&(clearTimeout(Fr),Fr=null),En){try{En.stop()}catch{}En=null}if(yt.active=!1,lr(c),Wn(),z){if(z.classList.remove("persona-voice-recording"),ct){z.style.backgroundColor=ct.backgroundColor,z.style.color=ct.color,z.style.borderColor=ct.borderColor;let g=z.querySelector("svg");g&&g.setAttribute("stroke",ct.color||"currentColor"),ct=null}z.setAttribute("aria-label","Start voice recognition")}}},ns=(c,g)=>{var gt,pt,Ie,Le,qe,Ye,vt,L;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((gt=c==null?void 0:c.provider)==null?void 0:gt.type)==="runtype";if(!(b||y))return null;let N=h("div","persona-send-button-wrapper"),O=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let U=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",H=(Ie=g==null?void 0:g.size)!=null?Ie:"40px",Te=(Le=c==null?void 0:c.iconSize)!=null?Le:H,ge=parseFloat(Te)||24,ee=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,Ae=(Ye=c==null?void 0:c.iconColor)!=null?Ye:g==null?void 0:g.textColor;O.style.width=Te,O.style.height=Te,O.style.minWidth=Te,O.style.minHeight=Te,O.style.fontSize="18px",O.style.lineHeight="1",Ae?O.style.color=Ae:O.style.color="var(--persona-text, #111827)";let je=we(U,ge,Ae||"currentColor",1.5);je?O.appendChild(je):O.textContent="\u{1F3A4}",ee?O.style.backgroundColor=ee:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),N.appendChild(O);let st=(vt=c==null?void 0:c.tooltipText)!=null?vt:"Start voice recognition";if(((L=c==null?void 0:c.showTooltip)!=null?L:!1)&&st){let Oe=h("div","persona-send-button-tooltip");Oe.textContent=st,N.appendChild(Oe)}return{micButton:O,micButtonWrapper:N}},Je=()=>{var g,b,y,E,N;if(!z||ct)return;let c=(g=r.voiceRecognition)!=null?g:{};ct={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((N=(E=c.iconSize)!=null?E:(y=r.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},A=(c,g)=>{var N,O,U,H,Te;if(!z)return;let b=z.querySelector("svg");b&&b.remove();let y=(Te=ct==null?void 0:ct.iconSize)!=null?Te:parseFloat((H=(U=(N=r.voiceRecognition)==null?void 0:N.iconSize)!=null?U:(O=r.sendButton)==null?void 0:O.size)!=null?H:"40")||24,E=we(c,y,g,1.5);E&&z.appendChild(E)},j=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},M=()=>{var E;if(!z)return;Je();let c=(E=r.voiceRecognition)!=null?E:{},g=c.recordingBackgroundColor,b=c.recordingIconColor,y=c.recordingBorderColor;if(j(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let N=z.querySelector("svg");N&&N.setAttribute("stroke",b)}y&&(z.style.borderColor=y),z.setAttribute("aria-label","Stop voice recognition")},Z=()=>{var U,H,Te,ge,ee,Ae,Me,je;if(!z)return;Je();let c=(U=r.voiceRecognition)!=null?U:{},g=_.getVoiceInterruptionMode(),b=(H=c.processingIconName)!=null?H:"loader",y=(ge=(Te=c.processingIconColor)!=null?Te:ct==null?void 0:ct.color)!=null?ge:"",E=(Ae=(ee=c.processingBackgroundColor)!=null?ee:ct==null?void 0:ct.backgroundColor)!=null?Ae:"",N=(je=(Me=c.processingBorderColor)!=null?Me:ct==null?void 0:ct.borderColor)!=null?je:"";j(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=E,z.style.borderColor=N;let O=y||"currentColor";z.style.color=O,A(b,O),z.setAttribute("aria-label","Processing voice input"),g==="none"&&(z.style.cursor="default")},ie=()=>{var Te,ge,ee,Ae,Me,je,st,Ve,gt,pt,Ie,Le;if(!z)return;Je();let c=(Te=r.voiceRecognition)!=null?Te:{},g=_.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(ge=c.speakingIconName)!=null?ge:b,E=(je=c.speakingIconColor)!=null?je:g==="barge-in"?(Ae=(ee=c.recordingIconColor)!=null?ee:ct==null?void 0:ct.color)!=null?Ae:"":(Me=ct==null?void 0:ct.color)!=null?Me:"",N=(gt=c.speakingBackgroundColor)!=null?gt:g==="barge-in"?(st=c.recordingBackgroundColor)!=null?st:"var(--persona-voice-recording-bg, #ef4444)":(Ve=ct==null?void 0:ct.backgroundColor)!=null?Ve:"",O=(Le=c.speakingBorderColor)!=null?Le:g==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(Ie=ct==null?void 0:ct.borderColor)!=null?Ie:"";j(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=N,z.style.borderColor=O;let U=E||"currentColor";z.style.color=U,A(y,U);let H=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",H),g==="none"&&(z.style.cursor="default"),g==="barge-in"&&z.classList.add("persona-voice-recording")},G=()=>{var c,g,b;z&&(j(),ct&&(z.style.backgroundColor=(c=ct.backgroundColor)!=null?c:"",z.style.color=(g=ct.color)!=null?g:"",z.style.borderColor=(b=ct.borderColor)!=null?b:"",A(ct.iconName,ct.color||"currentColor"),ct=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},ke=()=>{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(()=>{yt.active=!1,yt.manuallyDeactivated=!0,Wn(),lr("user"),G()});return}_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),yt.manuallyDeactivated=!_.isVoiceActive(),Wn(),lr("user"),_.isVoiceActive()?M():G()});return}if(Kn){let b=he.value.trim();yt.manuallyDeactivated=!0,Wn(),Cr("user"),b&&(he.value="",he.style.height="auto",_.sendMessage(b))}else yt.manuallyDeactivated=!1,Wn(),Mo("user")};Dn=ke,z&&(z.addEventListener("click",ke),xt.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),G()):Cr("system"),z&&z.removeEventListener("click",ke)}));let Fe=o.on("assistant:complete",()=>{Ms&&(yt.active||yt.manuallyDeactivated||Ms==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!yt.active&&!yt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("auto"),_.isVoiceActive()&&M()}):Mo("auto"))},600))});xt.push(Fe);let dt=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});xt.push(dt);let Xe=()=>{Nt(!R,"user")},Qe=null,tt=null;if(T&&!$()){let c=s.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>la(r,Xe).element,onToggle:Xe});g&&(tt=g)}tt||(Qe=la(r,Xe))}Qe?e.appendChild(Qe.element):tt&&e.appendChild(tt),ao(),br.render(r.suggestionChips,_,he,void 0,r.suggestionChipsConfig),Rs(),Yo(_.isStreaming()),no(!0),Ca(),k&&(!T||$()?setTimeout(()=>Zo(),0):R&&setTimeout(()=>Zo(),200));let Zt=()=>{var H,Te,ge,ee,Ae,Me,je,st,Ve,gt,pt,Ie,Le,qe,Ye,vt,L,Oe,te,nt,Ft,Ot;if($()){At(),ao();return}let c=ln(r),g=(Te=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?Te:!1,b=c||g||((ee=(ge=r.launcher)==null?void 0:ge.fullHeight)!=null?ee:!1),y=(Ae=e.ownerDocument.defaultView)!=null?Ae:window,E=(je=(Me=r.launcher)==null?void 0:Me.mobileFullscreen)!=null?je:!0,N=(Ve=(st=r.launcher)==null?void 0:st.mobileBreakpoint)!=null?Ve:640,O=y.innerWidth<=N,U=E&&O&&T;try{if(U){hr(),uo(e,r);return}if(I&&(I=!1,hr(),uo(e,r)),!T&&!c){oe.style.height="",oe.style.width="";return}if(!g&&!c){let zt=(pt=(gt=r==null?void 0:r.launcher)==null?void 0:gt.width)!=null?pt:r==null?void 0:r.launcherWidth,it=zt!=null?zt:Yn;oe.style.width=it,oe.style.maxWidth=it}if(Mr(),!b){let zt=y.innerHeight,it=64,dn=(Le=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Le:0,Jn=Math.max(200,zt-it),Ke=Math.min(640,Jn),Ct=Math.max(200,Ke-dn);oe.style.height=`${Ct}px`}}finally{if(At(),ao(),R&&T){let it=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((vt=(Ye=r.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?vt:640),dn=(Oe=(L=r.launcher)==null?void 0:L.sidebarMode)!=null?Oe:!1,Jn=(nt=(te=r.launcher)==null?void 0:te.mobileFullscreen)!=null?nt:!0,Ke=ln(r)&&Jn&&it,Ct=dn||Jn&&it&&T||Ke;if(Ct&&!Yt){let Gn=e.getRootNode(),sn=Gn instanceof ShadowRoot?Gn.host:e.closest(".persona-host");sn&&!Qt&&(Qt=ul(sn,(Ot=(Ft=r.launcher)==null?void 0:Ft.zIndex)!=null?Ot:wn)),Yt=ml(e.ownerDocument)}else Ct||(Qt==null||Qt(),Qt=null,Yt==null||Yt(),Yt=null)}}};Zt();let Pt=(Kc=e.ownerDocument.defaultView)!=null?Kc:window;if(Pt.addEventListener("resize",Zt),xt.push(()=>Pt.removeEventListener("resize",Zt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{At()});c.observe(_e),xt.push(()=>c.disconnect())}vr=X.scrollTop;let Bt=X.scrollHeight,cn=()=>{let c=X.scrollTop,g=X.scrollHeight,b=g<Bt;Bt=g;let{action:y,nextLastScrollTop:E}=di({following:xr.isFollowing(),currentScrollTop:c,lastScrollTop:vr,nearBottom:ta(X,Es),userScrollThreshold:va,isAutoScrolling:Br||Ao||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(vr=E,y==="resume"){to();return}y==="pause"&&Ls()};X.addEventListener("scroll",cn,{passive:!0}),xt.push(()=>X.removeEventListener("scroll",cn));let bn=c=>{let g=pi({following:xr.isFollowing(),deltaY:c.deltaY,nearBottom:ta(X,Es),resumeWhenNearBottom:!0});g==="pause"?Ls():g==="resume"&&to()};X.addEventListener("wheel",bn,{passive:!0}),xt.push(()=>X.removeEventListener("wheel",bn)),Wt.addEventListener("click",()=>{X.scrollTop=X.scrollHeight,vr=X.scrollTop,to(),no(!0)}),xt.push(()=>Wt.remove()),xt.push(()=>{ks()});let hn=()=>{Ue&&(zn&&(Ue.removeEventListener("click",zn),zn=null),D()?(Ue.style.display="",zn=()=>{Nt(!1,"user")},Ue.addEventListener("click",zn)):Ue.style.display="none")};hn(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{_.clearMessages(),ye.clear(),to(),xo(We.composerOverlay);try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)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(),V==null||V.clear(),de==null||de.reset(),le==null||le.update()})})(),Ut&&Ut.addEventListener("submit",Bs),he==null||he.addEventListener("keydown",Ns),he==null||he.addEventListener("input",Ds),he==null||he.addEventListener("paste",Fs);let cr=(Jc=e.ownerDocument)!=null?Jc:document;cr.addEventListener("keydown",Os,!0);let ec="persona-attachment-drop-active",_s=0,Qi=()=>{_s=0,fe.classList.remove(ec)},rs=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&ot!==null},tc=c=>{!_i(c.dataTransfer)||!rs()||(_s++,_s===1&&fe.classList.add(ec))},nc=c=>{!_i(c.dataTransfer)||!rs()||(_s--,_s<=0&&Qi())},rc=c=>{!_i(c.dataTransfer)||!rs()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},oc=c=>{var b;if(!_i(c.dataTransfer)||!rs())return;c.preventDefault(),c.stopPropagation(),Qi();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&ot.handleFiles(g)},io=!0;fe.addEventListener("dragenter",tc,io),fe.addEventListener("dragleave",nc,io),e.addEventListener("dragover",rc,io),e.addEventListener("drop",oc,io);let Ba=e.ownerDocument,sc=c=>{rs()&&c.preventDefault()},ac=c=>{rs()&&c.preventDefault()};Ba.addEventListener("dragover",sc),Ba.addEventListener("drop",ac),xt.push(()=>{Ut&&Ut.removeEventListener("submit",Bs),he==null||he.removeEventListener("keydown",Ns),he==null||he.removeEventListener("input",Ds),he==null||he.removeEventListener("paste",Fs),cr.removeEventListener("keydown",Os,!0)}),xt.push(()=>{fe.removeEventListener("dragenter",tc,io),fe.removeEventListener("dragleave",nc,io),e.removeEventListener("dragover",rc,io),e.removeEventListener("drop",oc,io),Ba.removeEventListener("dragover",sc),Ba.removeEventListener("drop",ac),Qi()}),xt.push(()=>{_.cancel()}),Qe?xt.push(()=>{Qe==null||Qe.destroy()}):tt&&xt.push(()=>{tt==null||tt.remove()});let on={update(c){var tn,Lr,an,Mn,ur,Io,Wo,Da,js,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,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;let g=r.toolCall,b=r.messageActions,y=(tn=r.layout)==null?void 0:tn.messages,E=r.colorScheme,N=r.loadingIndicator,O=r.iterationDisplay,U=(Lr=r.features)==null?void 0:Lr.showReasoning,H=(an=r.features)==null?void 0:an.showToolCalls,Te=(Mn=r.features)==null?void 0:Mn.toolCallDisplay,ge=(ur=r.features)==null?void 0:ur.reasoningDisplay;r={...r,...c},hr(),uo(e,r),Wi(e,r),Ri(e,r),Un(),r.colorScheme!==E&&eo();let ee=fa.getForInstance(r.plugins);s.length=0,s.push(...ee),T=(Wo=(Io=r.launcher)==null?void 0:Io.enabled)!=null?Wo:!0,B=(js=(Da=r.launcher)==null?void 0:Da.autoExpand)!=null?js:!1,Ge=(nd=(td=r.features)==null?void 0:td.showReasoning)!=null?nd:!0,Ce=(od=(rd=r.features)==null?void 0:rd.showToolCalls)!=null?od:!0,be=(ad=(sd=r.features)==null?void 0:sd.scrollToBottom)!=null?ad:{},Gt(),Nr();let Ae=He;if(He=(ld=(id=r.features)==null?void 0:id.showEventStreamToggle)!=null?ld:!1,He&&!Ae){if(V||(J=new ma(Pe),V=new ua(ue,J),de=de!=null?de:new ga,J.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),_.setSSEEventCallback((Q,Tt)=>{var jt;(jt=r.onSSEEvent)==null||jt.call(r,Q,Tt),de==null||de.processEvent(Q,Tt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!bt&&Ne){let Q=(dd=(cd=r.features)==null?void 0:cd.eventStream)==null?void 0:dd.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:"");bt=h("button",Tt),bt.style.width="28px",bt.style.height="28px",bt.style.color=Ln.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let jt=we("activity","18px","currentColor",1.5);jt&&bt.appendChild(jt);let ut=We.clearChatButtonWrapper,Rt=We.closeButtonWrapper,un=ut||Rt;un&&un.parentNode===Ne?Ne.insertBefore(bt,un):Ne.appendChild(bt),bt.addEventListener("click",()=>{ae?Nn():An()})}}else!He&&Ae&&(Nn(),bt&&(bt.remove(),bt=null),V==null||V.clear(),J==null||J.destroy(),V=null,J=null,de==null||de.reset(),de=null);if(((pd=r.launcher)==null?void 0:pd.enabled)===!1&&Qe&&(Qe.destroy(),Qe=null),((ud=r.launcher)==null?void 0:ud.enabled)===!1&&tt&&(tt.remove(),tt=null),((md=r.launcher)==null?void 0:md.enabled)!==!1&&!Qe&&!tt){let Q=s.find(Tt=>Tt.renderLauncher);if(Q!=null&&Q.renderLauncher){let Tt=Q.renderLauncher({config:r,defaultRenderer:()=>la(r,Xe).element,onToggle:Xe});Tt&&(tt=Tt,e.appendChild(tt))}tt||(Qe=la(r,Xe),e.appendChild(Qe.element))}Qe&&Qe.update(r),Ee&&((gd=r.launcher)==null?void 0:gd.title)!==void 0&&(Ee.textContent=r.launcher.title),De&&((fd=r.launcher)==null?void 0:fd.subtitle)!==void 0&&(De.textContent=r.launcher.subtitle);let Me=(hd=r.layout)==null?void 0:hd.header;if((Me==null?void 0:Me.layout)!==S&&Ne){let Q=Me?gs(r,Me,{showClose:D(),onClose:()=>Nt(!1,"user")}):qr({config:r,showClose:D(),onClose:()=>Nt(!1,"user")});Ne.replaceWith(Q.header),Ne=Q.header,F=Q.iconHolder,Ee=Q.headerTitle,De=Q.headerSubtitle,Ue=Q.closeButton,S=Me==null?void 0:Me.layout}else if(Me&&(F&&(F.style.display=Me.showIcon===!1?"none":""),Ee&&(Ee.style.display=Me.showTitle===!1?"none":""),De&&(De.style.display=Me.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=Me.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let Q=Me.showClearChat;if(Q!==void 0){We.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:Tt}=We;Tt&&!Tt.classList.contains("persona-absolute")&&(Q?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let st=((bd=r.layout)==null?void 0:bd.showHeader)!==!1;Ne&&(Ne.style.display=st?"":"none");let Ve=((yd=r.layout)==null?void 0:yd.showFooter)!==!1;_e&&(_e.style.display=Ve?"":"none"),At(),Nr(),T!==W?T?Nt(B,"auto"):(R=!0,ao()):B!==P&&Nt(B,"auto"),P=B,W=T,Zt(),hn();let Ie=JSON.stringify(c.toolCall)!==JSON.stringify(g),Le=JSON.stringify(r.messageActions)!==JSON.stringify(b),qe=JSON.stringify((xd=r.layout)==null?void 0:xd.messages)!==JSON.stringify(y),Ye=((vd=r.loadingIndicator)==null?void 0:vd.render)!==(N==null?void 0:N.render)||((wd=r.loadingIndicator)==null?void 0:wd.renderIdle)!==(N==null?void 0:N.renderIdle)||((Cd=r.loadingIndicator)==null?void 0:Cd.showBubble)!==(N==null?void 0:N.showBubble),vt=r.iterationDisplay!==O,L=((Sd=(Ad=r.features)==null?void 0:Ad.showReasoning)!=null?Sd:!0)!==(U!=null?U:!0)||((Ed=(Td=r.features)==null?void 0:Td.showToolCalls)!=null?Ed:!0)!==(H!=null?H:!0)||JSON.stringify((Md=r.features)==null?void 0:Md.toolCallDisplay)!==JSON.stringify(Te)||JSON.stringify((kd=r.features)==null?void 0:kd.reasoningDisplay)!==JSON.stringify(ge);(Ie||Le||qe||Ye||vt||L)&&_&&(Ts++,To($e,_.getMessages(),Re));let te=(Ld=r.launcher)!=null?Ld:{},nt=(Pd=te.headerIconHidden)!=null?Pd:!1,Ft=(Wd=(Id=r.layout)==null?void 0:Id.header)==null?void 0:Wd.showIcon,Ot=nt||Ft===!1,zt=te.headerIconName,it=(Rd=te.headerIconSize)!=null?Rd:"48px";if(F){let Q=fe.querySelector(".persona-border-b-persona-divider"),Tt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Ot)F.style.display="none",Q&&Tt&&!Q.contains(Tt)&&Q.insertBefore(Tt,Q.firstChild);else{if(F.style.display="",F.style.height=it,F.style.width=it,Q&&Tt&&(Q.contains(F)?F.nextSibling!==Tt&&(F.remove(),Q.insertBefore(F,Tt)):Q.insertBefore(F,Tt)),zt){let ut=parseFloat(it)||24,Rt=we(zt,ut*.6,"#ffffff",2);Rt?F.replaceChildren(Rt):F.textContent=(Hd=te.agentIconText)!=null?Hd:"\u{1F4AC}"}else if(te.iconUrl){let ut=F.querySelector("img");if(ut)ut.src=te.iconUrl,ut.style.height=it,ut.style.width=it;else{let Rt=document.createElement("img");Rt.src=te.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=it,Rt.style.width=it,F.replaceChildren(Rt)}}else{let ut=F.querySelector("svg"),Rt=F.querySelector("img");(ut||Rt)&&F.replaceChildren(),F.textContent=(Bd=te.agentIconText)!=null?Bd:"\u{1F4AC}"}let jt=F.querySelector("img");jt&&(jt.style.height=it,jt.style.width=it)}}let dn=(Nd=(Dd=r.layout)==null?void 0:Dd.header)==null?void 0:Nd.showTitle,Jn=(Fd=(Od=r.layout)==null?void 0:Od.header)==null?void 0:Fd.showSubtitle;if(Ee&&(Ee.style.display=dn===!1?"none":""),De&&(De.style.display=Jn===!1?"none":""),Ue){((_d=($d=r.layout)==null?void 0:$d.header)==null?void 0:_d.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let Tt=(jd=te.closeButtonSize)!=null?jd:"32px",jt=(Ud=te.closeButtonPlacement)!=null?Ud:"inline";Ue.style.height=Tt,Ue.style.width=Tt;let{closeButtonWrapper:ut}=We,Rt=jt==="top-right",un=ut==null?void 0:ut.classList.contains("persona-absolute");if(ut&&Rt!==un)if(ut.remove(),Rt)ut.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(ut);else{let ht=(zd=(qd=te.clearChat)==null?void 0:qd.placement)!=null?zd:"inline",mn=(Kd=(Vd=te.clearChat)==null?void 0:Vd.enabled)!=null?Kd:!0;ut.className=mn&&ht==="inline"?"":"persona-ml-auto";let Hn=fe.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(ut)}if(Ue.style.color=te.closeButtonColor||Ln.actionIconColor,te.closeButtonBackgroundColor?(Ue.style.backgroundColor=te.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),te.closeButtonBorderWidth||te.closeButtonBorderColor){let ht=te.closeButtonBorderWidth||"0px",mn=te.closeButtonBorderColor||"transparent";Ue.style.border=`${ht} solid ${mn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");te.closeButtonBorderRadius?(Ue.style.borderRadius=te.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),te.closeButtonPaddingX?(Ue.style.paddingLeft=te.closeButtonPaddingX,Ue.style.paddingRight=te.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),te.closeButtonPaddingY?(Ue.style.paddingTop=te.closeButtonPaddingY,Ue.style.paddingBottom=te.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let xn=(Jd=te.closeButtonIconName)!=null?Jd:"x",Ar=(Gd=te.closeButtonIconText)!=null?Gd:"\xD7";Ue.innerHTML="";let kn=we(xn,"28px","currentColor",1);kn?Ue.appendChild(kn):Ue.textContent=Ar;let en=(Xd=te.closeButtonTooltipText)!=null?Xd:"Close chat",Qn=(Qd=te.closeButtonShowTooltip)!=null?Qd:!0;if(Ue.setAttribute("aria-label",en),ut&&(ut._cleanupTooltip&&(ut._cleanupTooltip(),delete ut._cleanupTooltip),Qn&&en)){let ht=null,mn=()=>{if(ht||!Ue)return;let Ro=Ue.ownerDocument,Us=Ro.body;if(!Us)return;ht=Pr(Ro,"div","persona-clear-chat-tooltip"),ht.textContent=en;let qs=Pr(Ro,"div");qs.className="persona-clear-chat-tooltip-arrow",ht.appendChild(qs);let Ho=Ue.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(mo),ht.style.left=`${Ho.left+Ho.width/2}px`,ht.style.top=`${Ho.top-8}px`,ht.style.transform="translate(-50%, -100%)",Us.appendChild(ht)},Hn=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};ut.addEventListener("mouseenter",mn),ut.addEventListener("mouseleave",Hn),Ue.addEventListener("focus",mn),Ue.addEventListener("blur",Hn),ut._cleanupTooltip=()=>{Hn(),ut&&(ut.removeEventListener("mouseenter",mn),ut.removeEventListener("mouseleave",Hn)),Ue&&(Ue.removeEventListener("focus",mn),Ue.removeEventListener("blur",Hn))}}}let{clearChatButton:Ke,clearChatButtonWrapper:Ct}=We;if(Ke){let Q=(Yd=te.clearChat)!=null?Yd:{},Tt=(Zd=Q.enabled)!=null?Zd:!0,jt=(tp=(ep=r.layout)==null?void 0:ep.header)==null?void 0:tp.showClearChat,ut=jt!==void 0?jt:Tt,Rt=(np=Q.placement)!=null?np:"inline";if(Ct){Ct.style.display=ut?"":"none";let{closeButtonWrapper:un}=We;!$()&&un&&!un.classList.contains("persona-absolute")&&(ut?un.classList.remove("persona-ml-auto"):un.classList.add("persona-ml-auto"));let xn=Rt==="top-right",Ar=Ct.classList.contains("persona-absolute");if(!$()&&xn!==Ar&&ut){if(Ct.remove(),xn)Ct.className="persona-absolute persona-top-4 persona-z-50",Ct.style.right="48px",fe.style.position="relative",fe.appendChild(Ct);else{Ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ct.style.right="";let en=fe.querySelector(".persona-border-b-persona-divider"),Qn=We.closeButtonWrapper;en&&Qn&&Qn.parentElement===en?en.insertBefore(Ct,Qn):en&&en.appendChild(Ct)}let kn=We.closeButtonWrapper;kn&&!kn.classList.contains("persona-absolute")&&(xn?kn.classList.add("persona-ml-auto"):kn.classList.remove("persona-ml-auto"))}}if(ut){if(!$()){let ht=(rp=Q.size)!=null?rp:"32px";Ke.style.height=ht,Ke.style.width=ht}let un=(op=Q.iconName)!=null?op:"refresh-cw",xn=(sp=Q.iconColor)!=null?sp:"";Ke.style.color=xn||Ln.actionIconColor,Ke.innerHTML="";let Ar=$()?"14px":"20px",kn=we(un,Ar,"currentColor",2);if(kn&&Ke.appendChild(kn),Q.backgroundColor?(Ke.style.backgroundColor=Q.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let ht=Q.borderWidth||"0px",mn=Q.borderColor||"transparent";Ke.style.border=`${ht} solid ${mn}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");Q.borderRadius?(Ke.style.borderRadius=Q.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),Q.paddingX?(Ke.style.paddingLeft=Q.paddingX,Ke.style.paddingRight=Q.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),Q.paddingY?(Ke.style.paddingTop=Q.paddingY,Ke.style.paddingBottom=Q.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let en=(ap=Q.tooltipText)!=null?ap:"Clear chat",Qn=(ip=Q.showTooltip)!=null?ip:!0;if(Ke.setAttribute("aria-label",en),Ct&&(Ct._cleanupTooltip&&(Ct._cleanupTooltip(),delete Ct._cleanupTooltip),Qn&&en)){let ht=null,mn=()=>{if(ht||!Ke)return;let Ro=Ke.ownerDocument,Us=Ro.body;if(!Us)return;ht=Pr(Ro,"div","persona-clear-chat-tooltip"),ht.textContent=en;let qs=Pr(Ro,"div");qs.className="persona-clear-chat-tooltip-arrow",ht.appendChild(qs);let Ho=Ke.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(mo),ht.style.left=`${Ho.left+Ho.width/2}px`,ht.style.top=`${Ho.top-8}px`,ht.style.transform="translate(-50%, -100%)",Us.appendChild(ht)},Hn=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};Ct.addEventListener("mouseenter",mn),Ct.addEventListener("mouseleave",Hn),Ke.addEventListener("focus",mn),Ke.addEventListener("blur",Hn),Ct._cleanupTooltip=()=>{Hn(),Ct&&(Ct.removeEventListener("mouseenter",mn),Ct.removeEventListener("mouseleave",Hn)),Ke&&(Ke.removeEventListener("focus",mn),Ke.removeEventListener("blur",Hn))}}}}let Gn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ha],sn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Ko.message,Ko.messageAndClick];w=ba({parsers:Gn,handlers:sn,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Re=Nm(r,w,se),_.updateConfig(r),To($e,_.getMessages(),Re),br.render(r.suggestionChips,_,he,void 0,r.suggestionChipsConfig),Rs(),Yo(_.isStreaming());let pr=((lp=r.voiceRecognition)==null?void 0:lp.enabled)===!0,Xn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ko=((dp=(cp=r.voiceRecognition)==null?void 0:cp.provider)==null?void 0:dp.type)==="runtype";if(pr&&(Xn||ko))if(!z||!qt){let Q=ns(r.voiceRecognition,r.sendButton);Q&&(z=Q.micButton,qt=Q.micButtonWrapper,It.insertBefore(qt,Pn),z.addEventListener("click",ke),z.disabled=_.isStreaming())}else{let Q=(pp=r.voiceRecognition)!=null?pp:{},Tt=(up=r.sendButton)!=null?up:{},jt=(mp=Q.iconName)!=null?mp:"mic",ut=(gp=Tt.size)!=null?gp:"40px",Rt=(fp=Q.iconSize)!=null?fp:ut,un=parseFloat(Rt)||24;z.style.width=Rt,z.style.height=Rt,z.style.minWidth=Rt,z.style.minHeight=Rt;let xn=(bp=(hp=Q.iconColor)!=null?hp:Tt.textColor)!=null?bp:"currentColor";z.innerHTML="";let Ar=we(jt,un,xn,2);Ar?z.appendChild(Ar):z.textContent="\u{1F3A4}";let kn=(yp=Q.backgroundColor)!=null?yp:Tt.backgroundColor;kn?z.style.backgroundColor=kn:z.style.backgroundColor="",xn?z.style.color=xn:z.style.color="var(--persona-text, #111827)",Q.borderWidth?(z.style.borderWidth=Q.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),Q.borderColor?z.style.borderColor=Q.borderColor:z.style.borderColor="",Q.paddingX?(z.style.paddingLeft=Q.paddingX,z.style.paddingRight=Q.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),Q.paddingY?(z.style.paddingTop=Q.paddingY,z.style.paddingBottom=Q.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let en=qt==null?void 0:qt.querySelector(".persona-send-button-tooltip"),Qn=(xp=Q.tooltipText)!=null?xp:"Start voice recognition";if(((vp=Q.showTooltip)!=null?vp:!1)&&Qn)if(en)en.textContent=Qn,en.style.display="";else{let mn=document.createElement("div");mn.className="persona-send-button-tooltip",mn.textContent=Qn,qt==null||qt.insertBefore(mn,z)}else en&&(en.style.display="none");qt.style.display="",z.disabled=_.isStreaming()}else z&&qt&&(qt.style.display="none",((Cp=(wp=r.voiceRecognition)==null?void 0:wp.provider)==null?void 0:Cp.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Kn&&Cr());if(((Ap=r.attachments)==null?void 0:Ap.enabled)===!0)if(!_t||!et){let Q=(Sp=r.attachments)!=null?Sp:{},jt=(Ep=((Tp=r.sendButton)!=null?Tp:{}).size)!=null?Ep:"40px";ve||(ve=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ve.style.display="none",Ut.insertBefore(ve,he)),re||(re=document.createElement("input"),re.type="file",re.accept=((Mp=Q.allowedTypes)!=null?Mp:Ur).join(","),re.multiple=((kp=Q.maxFiles)!=null?kp:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),Ut.insertBefore(re,he)),_t=h("div","persona-send-button-wrapper"),et=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),et.type="button",et.setAttribute("aria-label",(Lp=Q.buttonTooltipText)!=null?Lp:"Attach file");let ut=(Pp=Q.buttonIconName)!=null?Pp:"paperclip",Rt=jt,un=parseFloat(Rt)||40,xn=Math.round(un*.6);et.style.width=Rt,et.style.height=Rt,et.style.minWidth=Rt,et.style.minHeight=Rt,et.style.fontSize="18px",et.style.lineHeight="1",et.style.backgroundColor="transparent",et.style.color="var(--persona-primary, #111827)",et.style.border="none",et.style.borderRadius="6px",et.style.transition="background-color 0.15s ease",et.addEventListener("mouseenter",()=>{et.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),et.addEventListener("mouseleave",()=>{et.style.backgroundColor="transparent"});let Ar=we(ut,xn,"currentColor",1.5);Ar?et.appendChild(Ar):et.textContent="\u{1F4CE}",et.addEventListener("click",Qn=>{Qn.preventDefault(),re==null||re.click()}),_t.appendChild(et);let kn=(Ip=Q.buttonTooltipText)!=null?Ip:"Attach file",en=h("div","persona-send-button-tooltip");en.textContent=kn,_t.appendChild(en),at.append(_t),!ot&&re&&ve&&(ot=jo.fromConfig(Q),ot.setPreviewsContainer(ve),re.addEventListener("change",async()=>{ot&&(re!=null&&re.files)&&(await ot.handleFileSelect(re.files),re.value="")})),fe.querySelector(".persona-attachment-drop-overlay")||fe.appendChild(Om(Q.dropOverlay))}else{_t.style.display="";let Q=(Wp=r.attachments)!=null?Wp:{};re&&(re.accept=((Rp=Q.allowedTypes)!=null?Rp:Ur).join(","),re.multiple=((Hp=Q.maxFiles)!=null?Hp:4)>1),ot&&ot.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else _t&&(_t.style.display="none"),ot&&ot.clearAttachments(),(Bp=fe.querySelector(".persona-attachment-drop-overlay"))==null||Bp.remove();let Xt=(Dp=r.sendButton)!=null?Dp:{},Lo=(Np=Xt.useIcon)!=null?Np:!1,lo=(Op=Xt.iconText)!=null?Op:"\u2191",co=Xt.iconName,$r=(Fp=Xt.tooltipText)!=null?Fp:"Send message",Po=($p=Xt.showTooltip)!=null?$p:!1,rt=(_p=Xt.size)!=null?_p:"40px",yn=Xt.backgroundColor,fn=Xt.textColor;if(Lo){if(pe.style.width=rt,pe.style.height=rt,pe.style.minWidth=rt,pe.style.minHeight=rt,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.innerHTML="",fn?pe.style.color=fn:pe.style.color="var(--persona-button-primary-fg, #ffffff)",co){let Q=parseFloat(rt)||24,Tt=(fn==null?void 0:fn.trim())||"currentColor",jt=we(co,Q,Tt,2);jt?pe.appendChild(jt):pe.textContent=lo}else pe.textContent=lo;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",yn?(pe.style.backgroundColor=yn,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=(Up=(jp=r.copy)==null?void 0:jp.sendButtonLabel)!=null?Up:"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.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",yn?(pe.style.backgroundColor=yn,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),fn?pe.style.color=fn:pe.classList.add("persona-text-white");Xt.borderWidth?(pe.style.borderWidth=Xt.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Xt.borderColor?pe.style.borderColor=Xt.borderColor:pe.style.borderColor="",Xt.paddingX?(pe.style.paddingLeft=Xt.paddingX,pe.style.paddingRight=Xt.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Xt.paddingY?(pe.style.paddingTop=Xt.paddingY,pe.style.paddingBottom=Xt.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let pn=Pn==null?void 0:Pn.querySelector(".persona-send-button-tooltip");if(Po&&$r)if(pn)pn.textContent=$r,pn.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=$r,Pn==null||Pn.insertBefore(Q,pe)}else pn&&(pn.style.display="none");let ft=(Jp=(qp=r.layout)==null?void 0:qp.contentMaxWidth)!=null?Jp:$()?(Kp=(Vp=(zp=r.launcher)==null?void 0:zp.composerBar)==null?void 0:Vp.contentMaxWidth)!=null?Kp:"720px":void 0;ft?($e.style.maxWidth=ft,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Ut&&(Ut.style.maxWidth=ft,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),Ht&&(Ht.style.maxWidth=ft,Ht.style.marginLeft="auto",Ht.style.marginRight="auto")):($e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",Ut&&(Ut.style.maxWidth="",Ut.style.marginLeft="",Ut.style.marginRight=""),Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""));let lt=(Gp=r.statusIndicator)!=null?Gp:{},Mt=(Xp=lt.visible)!=null?Xp:!0;if(gn.style.display=Mt?"":"none",_){let Q=_.getStatus();xe(gn,(jt=>{var ut,Rt,un,xn;return jt==="idle"?(ut=lt.idleText)!=null?ut:vn.idle:jt==="connecting"?(Rt=lt.connectingText)!=null?Rt:vn.connecting:jt==="connected"?(un=lt.connectedText)!=null?un:vn.connected:jt==="error"?(xn=lt.errorText)!=null?xn:vn.error:vn[jt]})(Q),lt,Q)}gn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Rn=lt.align==="left"?"persona-text-left":lt.align==="center"?"persona-text-center":"persona-text-right";gn.classList.add(Rn)},open(){D()&&Nt(!0,"api")},close(){D()&&Nt(!1,"api")},toggle(){D()&&Nt(!R,"api")},clearChat(){Sn=!1,_.clearMessages(),ye.clear(),to();try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)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(),V==null||V.clear(),de==null||de.reset(),le==null||le.update()},setMessage(c){return!he||_.isStreaming()?!1:(!R&&D()&&Nt(!0,"system"),he.value=c,he.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let g=(c==null?void 0:c.trim())||he.value.trim();return g?(!R&&D()&&Nt(!0,"system"),he.value="",he.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()||(!R&&D()&&Nt(!0,"system"),yt.manuallyDeactivated=!1,Wn(),_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("user"),_.isVoiceActive()&&M()})),!0):Kn?!0:$s()?(!R&&D()&&Nt(!0,"system"),yt.manuallyDeactivated=!1,Wn(),Mo("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(()=>{yt.active=!1,yt.manuallyDeactivated=!0,Wn(),lr("user"),G()}),!0):!1:Kn?(yt.manuallyDeactivated=!0,Wn(),Cr("user"),!0):!1},injectMessage(c){return!R&&D()&&Nt(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!R&&D()&&Nt(!0,"system");let g=_.injectAssistantMessage(c);return q&&(q=!1,K&&(clearTimeout(K),K=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(c){return!R&&D()&&Nt(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!R&&D()&&Nt(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!R&&D()&&Nt(!0,"system"),_.injectMessageBatch(c)},injectComponentDirective(c){return!R&&D()&&Nt(!0,"system"),_.injectComponentDirective(c)},injectTestMessage(c){!R&&D()&&Nt(!0,"system"),_.injectTestEvent(c)},async connectStream(c,g){return _.connectStream(c,g)},__pushEventStreamEvent(c){V&&(de==null||de.processEvent(c.type,c.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!He||!V||An()},hideEventStream(){ae&&Nn()},isEventStreamVisible(){return ae},showArtifacts(){fr(r)&&(Sn=!1,Un(),St==null||St.setMobileOpen(!0))},hideArtifacts(){fr(r)&&(Sn=!0,Un())},upsertArtifact(c){return fr(r)?(Sn=!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&&!R&&!$()||!he?!1:(he.focus(),!0)},async resolveApproval(c,g,b){let E=_.getMessages().find(N=>{var O;return N.variant==="approval"&&((O=N.approval)==null?void 0:O.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 o.on(c,g)},off(c,g){o.off(c,g)},isOpen(){return D()&&R},isVoiceActive(){return yt.active},getState(){return{open:D()&&R,launcherEnabled:T,voiceActive:yt.active,streaming:_.isStreaming()}},showCSATFeedback(c){!R&&D()&&Nt(!0,"system");let g=$e.querySelector(".persona-feedback-container");g&&g.remove();let b=Fi({onSubmit:async(y,E)=>{var N;_.isClientTokenMode()&&await _.submitCSATFeedback(y,E),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,E)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&D()&&Nt(!0,"system");let g=$e.querySelector(".persona-feedback-container");g&&g.remove();let b=$i({onSubmit:async(y,E)=>{var N;_.isClientTokenMode()&&await _.submitNPSFeedback(y,E),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,E)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.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(){kr!=null&&(clearInterval(kr),kr=null),xt.forEach(c=>c()),me.remove(),Ze==null||Ze.remove(),Qe==null||Qe.destroy(),tt==null||tt.remove(),zn&&Ue.removeEventListener("click",zn)}};if((((Gc=n==null?void 0:n.debugTools)!=null?Gc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:on,getMessages:on.getMessages,getStatus:on.getStatus,getMetadata:on.getPersistentMetadata,updateMetadata:on.updatePersistentMetadata,clearHistory:()=>on.clearChat(),setVoiceActive:b=>b?on.startVoiceRecognition():on.stopVoiceRecognition()};window.AgentWidgetBrowser=g,xt.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=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&on.focusInput()};if(window.addEventListener("persona:focusInput",g),xt.push(()=>{window.removeEventListener("persona:focusInput",g)}),He){let U=Te=>{let ge=Te.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&on.showEventStream()},H=Te=>{let ge=Te.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&on.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",H),xt.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",H)})}let b=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&on.showArtifacts()},y=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&on.hideArtifacts()},E=U=>{let H=U.detail;H!=null&&H.instanceId&&H.instanceId!==c||H!=null&&H.artifact&&on.upsertArtifact(H.artifact)},N=U=>{let H=U.detail;H!=null&&H.instanceId&&H.instanceId!==c||typeof(H==null?void 0:H.id)=="string"&&on.selectArtifact(H.id)},O=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&on.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",E),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",O),xt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",E),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",O)})}let dr=Xh(r.persistState);if(dr&&D()){let c=Qh(dr.storage),g=`${dr.keyPrefix}widget-open`,b=`${dr.keyPrefix}widget-voice`,y=`${dr.keyPrefix}widget-voice-mode`;if(c){let E=((Xc=dr.persist)==null?void 0:Xc.openState)&&c.getItem(g)==="true",N=((Qc=dr.persist)==null?void 0:Qc.voiceState)&&c.getItem(b)==="true",O=((Yc=dr.persist)==null?void 0:Yc.voiceState)&&c.getItem(y)==="true";if(E&&setTimeout(()=>{on.open(),setTimeout(()=>{var U;if(N||O)on.startVoiceRecognition();else if((U=dr.persist)!=null&&U.focusInput){let H=e.querySelector("textarea");H&&H.focus()}},100)},0),(Zc=dr.persist)!=null&&Zc.openState&&(o.on("widget:opened",()=>{c.setItem(g,"true")}),o.on("widget:closed",()=>{c.setItem(g,"false")})),(ed=dr.persist)!=null&&ed.voiceState&&(o.on("voice:state",U=>{c.setItem(b,U.active?"true":"false")}),o.on("user:message",U=>{c.setItem(y,U.viaVoice?"true":"false")})),dr.clearOnChatClear){let U=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(y)},H=()=>U();window.addEventListener("persona:clear-chat",H),xt.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return p&&D()&&setTimeout(()=>{on.open()},0),Or(),on};var Yh=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Fm=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},$l=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=""},$m=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",$l(e)},Nl=e=>{e.style.transition=""},Ol=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=""},Fl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ui=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Zh=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},eb=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},_m=(e,t,n,r,s,o,a)=>{var v,x,w,T,B,k;let i=mr(o),d=i.reveal==="push";Zh(e,t,n,r,d),eb(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,u=(T=(w=o==null?void 0:o.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"),Ol(t),Nl(r),$m(r),Fl(n),Ui(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((k=(B=o==null?void 0:o.launcher)==null?void 0:B.zIndex)!=null?k:wn),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"),$m(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ol(t),Nl(r),Fl(n),Ui(s,r);let P=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=P,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",Nl(r),$l(r),Ui(s,r);let P=Yh(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),S=i.animate?"transform 180ms ease":"none",I=i.side==="right"?a?`translateX(-${P}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${P}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+P}px`,t.style.transition=S,t.style.transform=I,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="",Ol(t),$l(r),Fl(n),Ui(s,r);let P=i.reveal==="emerge";P?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",I=!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=P||I?"hidden":"visible",r.style.transition=S,P&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},tb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Fm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Fm(n,r)},destroy(){n.remove()}}},nb=(e,t)=>{var B,k,P,W;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(k=(B=t==null?void 0:t.launcher)==null?void 0:B.enabled)==null||k?(W=(P=t==null?void 0:t.launcher)==null?void 0:P.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(()=>{_m(a,i,d,l,p,t,u)}),f.observe(a))},x=()=>{_m(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 I=S.launcherEnabled?S.open:!0;u!==I&&(u=I,x())},updateConfig(S){var I,$;t=S,(($=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)!=null?$:!0)===!1&&(u=!0),x()},destroy(){w==null||w.removeEventListener("resize",T),m(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},ya=(e,t)=>ln(t)?nb(e,t):tb(e,t);var _l={},jm=!1,rb=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},ob=()=>{try{if(typeof _l!="undefined"&&_l.url)return new URL("../widget.css",_l.url).href}catch{}return null},Um=(e,t)=>{let n=ob(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},jl=e=>{let t=rb(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=ya(t,s),a,i=[],d=(w,T)=>{var W,S;let k=!((S=(W=T==null?void 0:T.launcher)==null?void 0:W.enabled)!=null?S:!0)||ln(T),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),k&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let I=w.attachShadow({mode:"open"});I.appendChild(P),Um(I,r)}else w.appendChild(P),Um(w,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let w=d(o.host,s);a=ji(w,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(jm||(jm=!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(),o.destroy(),o=ya(t,w),s=w,u()},v={update(w){var S,I,$,D,R,q;let T={...s,...w,launcher:{...(S=s==null?void 0:s.launcher)!=null?S:{},...(I=w==null?void 0:w.launcher)!=null?I:{},dock:{...(D=($=s==null?void 0:s.launcher)==null?void 0:$.dock)!=null?D:{},...(q=(R=w==null?void 0:w.launcher)==null?void 0:R.dock)!=null?q:{}}}},B=ln(s),k=ln(T),P=fo(s),W=fo(T);if(B!==k||P!==W){m(T);return}s=T,o.updateConfig(s),a.update(w),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(w,T,B){if(T==="host")return o.host;if(T in w)return Reflect.get(w,T,B);let k=a[T];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Jm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),sb=new Set(["button","a","input","select","textarea","details","summary"]),ab=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ul=/\b(product|card|item|listing|result)\b/i,zl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,ib=3e3,lb=100;function Gm(e){let t=typeof e.className=="string"?e.className:"";if(Ul.test(t)||e.id&&Ul.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Ul.test(r.value))return!0}return!1}function Xm(e){var t;return zl.test(((t=e.textContent)!=null?t:"").trim())}function Qm(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function cb(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function qm(e){let t=e.match(zl);return t?t[0]:null}function zm(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function db(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var pb="commerce-card",ub="result-card";function Vm(e){return!Gm(e)||!Xm(e)||!Qm(e)&&!cb(e)?0:5200}function Km(e){var r;return!Gm(e)||Xm(e)||!Qm(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 Vl=[{id:pb,scoreElement(e){return Vm(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||zl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(Vm(e)===0)return null;let{title:n,href:r}=zm(e),s=(p=(l=qm(((d=e.textContent)!=null?d:"").trim()))!=null?l:qm(t.text))!=null?p:"",o=db(e);return[r&&n?`[${n}](${r})${s?` \u2014 ${s}`:""}`:n?`${n}${s?` \u2014 ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
108
|
-
`)}},{id:
|
|
109
|
-
`)}}];function
|
|
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&>){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:
|
|
110
110
|
${a.map(i=>`- ${i.split(`
|
|
111
111
|
`).join(`
|
|
112
112
|
`)}`).join(`
|
|
113
|
-
`)}`)}let
|
|
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:
|
|
114
114
|
${a.join(`
|
|
115
|
-
`)}`)}if(
|
|
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:
|
|
116
116
|
${a.join(`
|
|
117
|
-
`)}`)}if(
|
|
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:
|
|
118
118
|
${a.join(`
|
|
119
|
-
`)}`)}if(
|
|
119
|
+
`)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Yi)}"`);r.push(`Content:
|
|
120
120
|
${a.join(`
|
|
121
121
|
`)}`)}return r.join(`
|
|
122
122
|
|
|
123
|
-
`)}var
|
|
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) => {
|
|
124
124
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
125
125
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
126
126
|
let cleanJson = jsonSource
|
|
@@ -133,7 +133,7 @@ ${a.join(`
|
|
|
133
133
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
134
134
|
} catch (e) { return null; }
|
|
135
135
|
return null;
|
|
136
|
-
}`,
|
|
136
|
+
}`,_g=`function(ctx) {
|
|
137
137
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
138
138
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
139
139
|
var cleanJson = jsonSource
|
|
@@ -146,7 +146,7 @@ ${a.join(`
|
|
|
146
146
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
147
147
|
} catch (e) { return null; }
|
|
148
148
|
return null;
|
|
149
|
-
}`,
|
|
149
|
+
}`,jg=`(action: any, context: any) => {
|
|
150
150
|
if (action.type !== 'nav_then_click') return;
|
|
151
151
|
const payload = action.payload || action.raw || {};
|
|
152
152
|
const url = payload?.page;
|
|
@@ -163,7 +163,7 @@ ${a.join(`
|
|
|
163
163
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
164
164
|
window.location.href = targetUrl;
|
|
165
165
|
return { handled: true, displayText: text };
|
|
166
|
-
}`,
|
|
166
|
+
}`,Ug=`function(action, context) {
|
|
167
167
|
if (action.type !== 'nav_then_click') return;
|
|
168
168
|
var payload = action.payload || action.raw || {};
|
|
169
169
|
var url = payload.page;
|
|
@@ -180,26 +180,26 @@ ${a.join(`
|
|
|
180
180
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
181
181
|
window.location.href = targetUrl;
|
|
182
182
|
return { handled: true, displayText: text };
|
|
183
|
-
}`,
|
|
183
|
+
}`,sy=`(parsed: any) => {
|
|
184
184
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
185
185
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
186
186
|
if (parsed.action === 'message') return parsed.text || '';
|
|
187
187
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
188
188
|
return parsed.text || null;
|
|
189
|
-
}`,
|
|
189
|
+
}`,ay=`function(parsed) {
|
|
190
190
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
191
191
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
192
192
|
if (parsed.action === 'message') return parsed.text || '';
|
|
193
193
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
194
194
|
return parsed.text || null;
|
|
195
|
-
}`;function
|
|
196
|
-
`)}function
|
|
197
|
-
`)}function Ib(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: '${xa(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&&wo(r,"theme",e.theme," "),e.launcher&&wo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Vi(e," ")),r.push(...Ki(e," ",n)),r.push(...Ji(e," ")),r.push(...Gi(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(${Eb}),`)),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(` ${ug}`),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(` ${ug}`),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(` ${gg}`),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(` ${gg}`),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
|
|
199
|
-
`)}function
|
|
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,"'");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(`
|
|
200
200
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
201
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${
|
|
202
|
-
`)}var
|
|
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=`
|
|
203
203
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
204
204
|
.persona-dc-root {
|
|
205
205
|
display: flex;
|
|
@@ -350,7 +350,7 @@ ${a.join(`
|
|
|
350
350
|
.persona-dc-stage {
|
|
351
351
|
height: 550px;
|
|
352
352
|
min-height: 400px;
|
|
353
|
-
padding: ${
|
|
353
|
+
padding: ${dc}px;
|
|
354
354
|
overflow: auto;
|
|
355
355
|
background: #f0f1f3;
|
|
356
356
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -440,5 +440,5 @@ ${a.join(`
|
|
|
440
440
|
min-height: 300px;
|
|
441
441
|
}
|
|
442
442
|
}
|
|
443
|
-
`;function
|
|
443
|
+
`;function 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});
|
|
444
444
|
//# sourceMappingURL=index.cjs.map
|