@runtypelabs/persona 4.0.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,23 @@
1
- "use strict";var AgentWidget=(()=>{var Xx=Object.create;var qs=Object.defineProperty;var Jx=Object.getOwnPropertyDescriptor;var Qx=Object.getOwnPropertyNames;var Yx=Object.getPrototypeOf,Zx=Object.prototype.hasOwnProperty;var yl=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,r)=>(typeof require!="undefined"?require:t)[r]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Ym=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ey=(e,t)=>{for(var r in t)qs(e,r,{get:t[r],enumerable:!0})},Zm=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Qx(t))!Zx.call(e,n)&&n!==r&&qs(e,n,{get:()=>t[n],enumerable:!(o=Jx(t,n))||o.enumerable});return e};var ya=(e,t,r)=>(r=e!=null?Xx(Yx(e)):{},Zm(t||!e||!e.__esModule?qs(r,"default",{value:e,enumerable:!0}):r,e)),ty=e=>Zm(qs({},"__esModule",{value:!0}),e);var Ml=Ym(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.Allow=Ne.ALL=Ne.COLLECTION=Ne.ATOM=Ne.SPECIAL=Ne.INF=Ne._INFINITY=Ne.INFINITY=Ne.NAN=Ne.BOOL=Ne.NULL=Ne.OBJ=Ne.ARR=Ne.NUM=Ne.STR=void 0;Ne.STR=1;Ne.NUM=2;Ne.ARR=4;Ne.OBJ=8;Ne.NULL=16;Ne.BOOL=32;Ne.NAN=64;Ne.INFINITY=128;Ne._INFINITY=256;Ne.INF=Ne.INFINITY|Ne._INFINITY;Ne.SPECIAL=Ne.NULL|Ne.BOOL|Ne.INF|Ne.NAN;Ne.ATOM=Ne.STR|Ne.NUM|Ne.SPECIAL;Ne.COLLECTION=Ne.ARR|Ne.OBJ;Ne.ALL=Ne.ATOM|Ne.COLLECTION;Ne.Allow={STR:Ne.STR,NUM:Ne.NUM,ARR:Ne.ARR,OBJ:Ne.OBJ,NULL:Ne.NULL,BOOL:Ne.BOOL,NAN:Ne.NAN,INFINITY:Ne.INFINITY,_INFINITY:Ne._INFINITY,INF:Ne.INF,SPECIAL:Ne.SPECIAL,ATOM:Ne.ATOM,COLLECTION:Ne.COLLECTION,ALL:Ne.ALL};Ne.default=Ne.Allow});var Ks=Ym(hr=>{"use strict";var my=hr&&hr.__createBinding||(Object.create?(function(e,t,r,o){o===void 0&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}):(function(e,t,r,o){o===void 0&&(o=r),e[o]=t[r]})),gy=hr&&hr.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&my(t,e,r)};Object.defineProperty(hr,"__esModule",{value:!0});hr.Allow=hr.MalformedJSON=hr.PartialJSON=hr.parseJSON=hr.parse=void 0;var Rr=Ml();Object.defineProperty(hr,"Allow",{enumerable:!0,get:function(){return Rr.Allow}});gy(Ml(),hr);var js=class extends Error{};hr.PartialJSON=js;var Gs=class extends Error{};hr.MalformedJSON=Gs;function pg(e,t=Rr.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return hy(e.trim(),t)}hr.parseJSON=pg;var hy=(e,t)=>{let r=e.length,o=0,n=c=>{throw new js(`${c} at position ${o}`)},a=c=>{throw new Gs(`${c} at position ${o}`)},s=()=>(g(),o>=r&&n("Unexpected end of input"),e[o]==='"'?i():e[o]==="{"?p():e[o]==="["?d():e.substring(o,o+4)==="null"||Rr.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Rr.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Rr.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Rr.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Rr.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Rr.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):u()),i=()=>{let c=o,m=!1;for(o++;o<r&&(e[o]!=='"'||m&&e[o-1]==="\\");)m=e[o]==="\\"?!m:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(c,++o-Number(m)))}catch(x){a(String(x))}else if(Rr.Allow.STR&t)try{return JSON.parse(e.substring(c,o-Number(m))+'"')}catch{return JSON.parse(e.substring(c,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},p=()=>{o++,g();let c={};try{for(;e[o]!=="}";){if(g(),o>=r&&Rr.Allow.OBJ&t)return c;let m=i();g(),o++;try{let x=s();c[m]=x}catch(x){if(Rr.Allow.OBJ&t)return c;throw x}g(),e[o]===","&&o++}}catch{if(Rr.Allow.OBJ&t)return c;n("Expected '}' at end of object")}return o++,c},d=()=>{o++;let c=[];try{for(;e[o]!=="]";)c.push(s()),g(),e[o]===","&&o++}catch{if(Rr.Allow.ARR&t)return c;n("Expected ']' at end of array")}return o++,c},u=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Rr.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let c=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==r&&!(Rr.Allow.NUM&t)&&n("Unterminated number literal");try{return JSON.parse(e.substring(c,o))}catch{e.substring(c,o)==="-"&&n("Not sure what '-' is");try{return JSON.parse(e.substring(c,e.lastIndexOf("e")))}catch(x){a(String(x))}}},g=()=>{for(;o<r&&`
2
- \r `.includes(e[o]);)o++};return s()},xy=pg;hr.parse=xy});var E0={};ey(E0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Bl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Hl,ASK_USER_QUESTION_TOOL_NAME:()=>os,AgentWidgetClient:()=>Kn,AgentWidgetSession:()=>ka,AttachmentManager:()=>Yn,BrowserSpeechEngine:()=>Sn,DEFAULT_COMPONENTS:()=>Np,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ai,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Yr,DEFAULT_PALETTE:()=>Dp,DEFAULT_SEMANTIC:()=>Fp,DEFAULT_WIDGET_CONFIG:()=>Ft,PRESETS:()=>Tc,PRESET_FULLSCREEN:()=>Mc,PRESET_MINIMAL:()=>Ac,PRESET_SHOP:()=>Sc,ReadAloudController:()=>Qn,SUGGEST_REPLIES_CLIENT_TOOL:()=>Ys,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Rl,SUGGEST_REPLIES_TOOL_NAME:()=>bo,THEME_ZONES:()=>Qg,VERSION:()=>Gn,WEBMCP_TOOL_PREFIX:()=>Ko,WebMcpBridge:()=>Ca,accessibilityPlugin:()=>fx,animationsPlugin:()=>mx,applyThemeVariables:()=>An,attachHeaderToContainer:()=>ta,brandPlugin:()=>gx,buildComposer:()=>Wa,buildDefaultHeader:()=>Kp,buildHeader:()=>en,buildHeaderWithLayout:()=>Ia,buildMinimalHeader:()=>Xp,builtInClientToolsForDispatch:()=>ss,collectEnrichedPageContext:()=>cx,componentRegistry:()=>tn,createActionManager:()=>Ls,createAgentExperience:()=>sl,createAskUserQuestionBubble:()=>Sg,createBestAvailableVoiceProvider:()=>ui,createBubbleWithLayout:()=>Ch,createCSATFeedback:()=>ol,createComboButton:()=>Oi,createComponentMiddleware:()=>$h,createComponentStreamParser:()=>Zi,createDefaultSanitizer:()=>Cl,createDirectivePostprocessor:()=>ng,createDropdownMenu:()=>kn,createFlexibleJsonStreamParser:()=>Eg,createIconButton:()=>cr,createImagePart:()=>Bg,createJsonStreamParser:()=>si,createLabelButton:()=>Ss,createLocalStorageAdapter:()=>Yi,createMarkdownProcessor:()=>es,createMarkdownProcessorFromConfig:()=>$n,createMessageActions:()=>rc,createNPSFeedback:()=>nl,createPlainTextParser:()=>ni,createPlugin:()=>yx,createRegexJsonParser:()=>ai,createStandardBubble:()=>Ha,createTextPart:()=>ps,createTheme:()=>Pa,createThemeObserver:()=>ki,createToggleGroup:()=>fh,createTypingIndicator:()=>ra,createVoiceProvider:()=>wn,createWidgetHostLayout:()=>Ps,createXmlParser:()=>ii,defaultActionHandlers:()=>na,defaultJsonActionParser:()=>ks,defaultParseRules:()=>Cc,detectColorScheme:()=>gs,directivePostprocessor:()=>ag,ensureAskUserQuestionSheet:()=>Aa,escapeHtml:()=>Ho,extractComponentDirectiveFromMessage:()=>rl,fileToImagePart:()=>Dg,formatEnrichedContext:()=>ux,generateAssistantMessageId:()=>Xn,generateMessageId:()=>Pg,generateStableSelector:()=>wc,generateUserMessageId:()=>Ta,getActiveTheme:()=>Ra,getColorScheme:()=>_p,getDisplayText:()=>Ig,getHeaderLayout:()=>Jp,getImageParts:()=>Hg,getPreset:()=>vx,hasComponentDirective:()=>tl,hasImages:()=>Wg,headerLayouts:()=>_i,highContrastPlugin:()=>xx,initAgentWidget:()=>ex,isAskUserQuestionMessage:()=>Xo,isComponentDirectiveType:()=>zh,isDockedMountMode:()=>nr,isSuggestRepliesMessage:()=>as,isVoiceSupported:()=>us,isWebMcpToolName:()=>xn,latestAgentSuggestions:()=>Zs,listRegisteredStreamAnimations:()=>zp,markdownPostprocessor:()=>vl,mergeWithDefaults:()=>Mi,normalizeContent:()=>Rg,parseAskUserQuestionPayload:()=>Jo,parseSuggestRepliesPayload:()=>Wl,pickBestVoice:()=>Ea,pluginRegistry:()=>Es,reducedMotionPlugin:()=>hx,registerStreamAnimationPlugin:()=>ea,removeAskUserQuestionSheet:()=>vn,renderComponentDirective:()=>el,renderLoadingIndicatorWithFallback:()=>tc,renderLucideIcon:()=>be,resolveDockConfig:()=>Zr,resolveSanitizer:()=>va,resolveTokens:()=>Ti,stripWebMcpPrefix:()=>$s,themeToCssVariables:()=>Ei,unregisterStreamAnimationPlugin:()=>Vp,validateImageFile:()=>Fg,validateTheme:()=>Op});var bl=null,Za=null,ba=null,eg=e=>{bl=e};var Vs=()=>Za?Promise.resolve(Za):ba||(bl?(ba=bl().then(e=>(Za=e,e)),ba):(ba=import("./markdown-parsers-entry").then(e=>(Za=e,e)),ba)),zn=()=>Za;var ry=e=>{if(e)return e},es=e=>{let t=null;return r=>{var n,a;let o=zn();if(!o)return Ho(r);if(!t){let{Marked:s}=o,i=e==null?void 0:e.markedOptions;t=new s({gfm:(n=i==null?void 0:i.gfm)!=null?n:!0,breaks:(a=i==null?void 0:i.breaks)!=null?a:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let p=ry(e==null?void 0:e.renderer);p&&t.use({renderer:p})}return t.parse(r)}},$n=e=>e?es({markedOptions:e.options,renderer:e.renderer}):es(),oy=es(),vl=e=>oy(e),Ho=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),rg=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),tg=e=>`%%FORM_PLACEHOLDER_${e}%%`,og=(e,t)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,n)=>{try{let a=JSON.parse(n.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=tg(t.length);return t.push({token:s,type:String(a.type)}),s}}catch{return o}return o}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,n)=>{let a=tg(t.length);return t.push({token:a,type:n}),a}),r},ng=e=>{let t=$n(e);return r=>{let o=[],n=og(r,o),a=t(n);return o.forEach(({token:s,type:i})=>{let p=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${rg(i)}"></div>`;a=a.replace(p,u)}),a}},ag=e=>{let t=[],r=og(e,t),o=vl(r);return t.forEach(({token:n,type:a})=>{let s=new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${rg(a)}"></div>`;o=o.replace(s,p)}),o};var ny={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"]},ay=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Cl=()=>{let e=null;return t=>{let r=zn();if(!r)return Ho(t);if(!e){let{DOMPurify:o}=r;e=o(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(n,a)=>{if(a.attrName==="src"||a.attrName==="href"){let s=a.attrValue;s.toLowerCase().startsWith("data:")&&!ay.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,ny)}},va=e=>e===!1?null:typeof e=="function"?e:Cl();var Ko="webmcp:",wl=new Map,sg=e=>{var t;wl.clear();for(let r of e){let o=(t=r.title)==null?void 0:t.trim();o&&wl.set(r.name,o)}},Al=e=>wl.get($s(e)),zs={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Sl=null,lg=e=>{Sl=e};function dg(e){if(e.length===0)return"0:empty";let t=e.map(r=>{var o,n;return[r.name,(o=r.description)!=null?o:"",r.parametersSchema?JSON.stringify(r.parametersSchema):"",(n=r.origin)!=null?n:"",r.annotations?JSON.stringify(r.annotations):""].join("")}).sort();return`${e.length}:${sy(t.join(""))}`}function ig(e,t){let r=3735928559^t,o=1103547991^t;for(let n=0;n<e.length;n++){let a=e.charCodeAt(n);r=Math.imul(r^a,2654435761),o=Math.imul(o^a,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&o)+(r>>>0)}function sy(e){let t=ig(e,0).toString(36),r=ig(e,2654435761).toString(36);return`${t}.${r}`}var Ca=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var r;this.confirmHandler=(r=t.onConfirm)!=null?r: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 r;try{r=await t.getTools()}catch(n){return zs.warn("getTools() threw: shipping an empty WebMCP snapshot.",n),[]}sg(r);let o=typeof location!="undefined"?location.origin:"";return r.filter(n=>this.passesClientAllowlist(n.name)).map(n=>{let a={name:n.name,description:n.description,origin:"webmcp",...o?{pageOrigin:o}:{}},s=ly(n.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,r,o){if(await this.ensureReady(),this.config.enabled!==!0)return yo("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let x=typeof document!="undefined"&&!!document.modelContext;return yo(x?"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 a=$s(t),s;try{s=await n.getTools()}catch(x){let C=x instanceof Error?x.message:String(x);return yo(`Failed to read WebMCP registry: ${C}`)}sg(s);let i=s.find(x=>x.name===a);if(!i)return yo(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return yo(`WebMCP tool not allowed by client allowlist: ${a}`);if(o!=null&&o.aborted)return yo("Aborted by cancel()");let p=Al(a),d={toolName:a,args:r,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return yo("User declined the tool call.");if(o!=null&&o.aborted)return yo("Aborted by cancel()");let u=new AbortController,g=!1,c=setTimeout(()=>{g=!0,u.abort()},this.timeoutMs),m=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",m,{once:!0}));try{let x=await n.executeTool(i,uy(r),{signal:u.signal});return dy(x)}catch(x){if(g)return yo(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return yo("Aborted by cancel()");let C=x instanceof Error?x.message:String(x);return yo(C)}finally{clearTimeout(c),o&&o.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}(Sl?await Sl():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){zs.warn("Failed to load @mcp-b/webmcp-polyfill: 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 r=t;return typeof r.getTools!="function"||typeof r.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,zs.warn("document.modelContext is present but does not expose getTools()/executeTool(): 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 o;let r=(o=this.confirmHandler)!=null?o:py;try{return await r(t)}catch(n){return zs.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,n),!1}}passesClientAllowlist(t){let r=this.config.allowlist;return!r||r.length===0?!0:r.some(o=>iy(t,o))}},$s=e=>e.startsWith(Ko)?e.slice(Ko.length):e,xn=e=>e.startsWith(Ko),iy=(e,t)=>{if(t==="*")return!0;let r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)},ly=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},dy=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:fy(t)}]}},yo=e=>({isError:!0,content:[{type:"text",text:e}]}),py=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=cy(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var AgentWidget=(()=>{var ly=Object.create;var $s=Object.defineProperty;var dy=Object.getOwnPropertyDescriptor;var cy=Object.getOwnPropertyNames;var py=Object.getPrototypeOf,uy=Object.prototype.hasOwnProperty;var Cl=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,r)=>(typeof require!="undefined"?require:t)[r]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var tg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),fy=(e,t)=>{for(var r in t)$s(e,r,{get:t[r],enumerable:!0})},rg=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of cy(t))!uy.call(e,n)&&n!==r&&$s(e,n,{get:()=>t[n],enumerable:!(o=dy(t,n))||o.enumerable});return e};var Aa=(e,t,r)=>(r=e!=null?ly(py(e)):{},rg(t||!e||!e.__esModule?$s(r,"default",{value:e,enumerable:!0}):r,e)),my=e=>rg($s({},"__esModule",{value:!0}),e);var El=tg(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.Allow=Fe.ALL=Fe.COLLECTION=Fe.ATOM=Fe.SPECIAL=Fe.INF=Fe._INFINITY=Fe.INFINITY=Fe.NAN=Fe.BOOL=Fe.NULL=Fe.OBJ=Fe.ARR=Fe.NUM=Fe.STR=void 0;Fe.STR=1;Fe.NUM=2;Fe.ARR=4;Fe.OBJ=8;Fe.NULL=16;Fe.BOOL=32;Fe.NAN=64;Fe.INFINITY=128;Fe._INFINITY=256;Fe.INF=Fe.INFINITY|Fe._INFINITY;Fe.SPECIAL=Fe.NULL|Fe.BOOL|Fe.INF|Fe.NAN;Fe.ATOM=Fe.STR|Fe.NUM|Fe.SPECIAL;Fe.COLLECTION=Fe.ARR|Fe.OBJ;Fe.ALL=Fe.ATOM|Fe.COLLECTION;Fe.Allow={STR:Fe.STR,NUM:Fe.NUM,ARR:Fe.ARR,OBJ:Fe.OBJ,NULL:Fe.NULL,BOOL:Fe.BOOL,NAN:Fe.NAN,INFINITY:Fe.INFINITY,_INFINITY:Fe._INFINITY,INF:Fe.INF,SPECIAL:Fe.SPECIAL,ATOM:Fe.ATOM,COLLECTION:Fe.COLLECTION,ALL:Fe.ALL};Fe.default=Fe.Allow});var Qs=tg(vr=>{"use strict";var Py=vr&&vr.__createBinding||(Object.create?(function(e,t,r,o){o===void 0&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}):(function(e,t,r,o){o===void 0&&(o=r),e[o]=t[r]})),Ry=vr&&vr.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Py(t,e,r)};Object.defineProperty(vr,"__esModule",{value:!0});vr.Allow=vr.MalformedJSON=vr.PartialJSON=vr.parseJSON=vr.parse=void 0;var Br=El();Object.defineProperty(vr,"Allow",{enumerable:!0,get:function(){return Br.Allow}});Ry(El(),vr);var Xs=class extends Error{};vr.PartialJSON=Xs;var Js=class extends Error{};vr.MalformedJSON=Js;function xg(e,t=Br.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return Iy(e.trim(),t)}vr.parseJSON=xg;var Iy=(e,t)=>{let r=e.length,o=0,n=u=>{throw new Xs(`${u} at position ${o}`)},a=u=>{throw new Js(`${u} at position ${o}`)},s=()=>(f(),o>=r&&n("Unexpected end of input"),e[o]==='"'?i():e[o]==="{"?c():e[o]==="["?l():e.substring(o,o+4)==="null"||Br.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Br.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Br.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Br.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Br.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Br.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):p()),i=()=>{let u=o,m=!1;for(o++;o<r&&(e[o]!=='"'||m&&e[o-1]==="\\");)m=e[o]==="\\"?!m:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(u,++o-Number(m)))}catch(x){a(String(x))}else if(Br.Allow.STR&t)try{return JSON.parse(e.substring(u,o-Number(m))+'"')}catch{return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{o++,f();let u={};try{for(;e[o]!=="}";){if(f(),o>=r&&Br.Allow.OBJ&t)return u;let m=i();f(),o++;try{let x=s();u[m]=x}catch(x){if(Br.Allow.OBJ&t)return u;throw x}f(),e[o]===","&&o++}}catch{if(Br.Allow.OBJ&t)return u;n("Expected '}' at end of object")}return o++,u},l=()=>{o++;let u=[];try{for(;e[o]!=="]";)u.push(s()),f(),e[o]===","&&o++}catch{if(Br.Allow.ARR&t)return u;n("Expected ']' at end of array")}return o++,u},p=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Br.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let u=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==r&&!(Br.Allow.NUM&t)&&n("Unterminated number literal");try{return JSON.parse(e.substring(u,o))}catch{e.substring(u,o)==="-"&&n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(x){a(String(x))}}},f=()=>{for(;o<r&&`
2
+ \r `.includes(e[o]);)o++};return s()},Hy=xg;vr.parse=Hy});var X0={};fy(X0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Fl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Dl,ASK_USER_QUESTION_TOOL_NAME:()=>ls,AgentWidgetClient:()=>Qn,AgentWidgetSession:()=>Ha,AttachmentManager:()=>ta,BrowserSpeechEngine:()=>En,DEFAULT_COMPONENTS:()=>_c,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ei,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Zr,DEFAULT_PALETTE:()=>Nc,DEFAULT_SEMANTIC:()=>Oc,DEFAULT_WIDGET_CONFIG:()=>Bt,PRESETS:()=>Lp,PRESET_FULLSCREEN:()=>kp,PRESET_MINIMAL:()=>Ep,PRESET_SHOP:()=>Tp,ReadAloudController:()=>ea,SUGGEST_REPLIES_CLIENT_TOOL:()=>ti,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Hl,SUGGEST_REPLIES_TOOL_NAME:()=>wo,THEME_ZONES:()=>nh,VERSION:()=>Jn,WEBMCP_TOOL_PREFIX:()=>Co,WebMcpBridge:()=>Ea,accessibilityPlugin:()=>Ax,animationsPlugin:()=>Mx,applyThemeVariables:()=>kn,attachHeaderToContainer:()=>na,brandPlugin:()=>Tx,buildComposer:()=>Na,buildDefaultHeader:()=>Jc,buildHeader:()=>rn,buildHeaderWithLayout:()=>Fa,buildMinimalHeader:()=>Qc,builtInClientToolsForDispatch:()=>ps,collectEnrichedPageContext:()=>wx,componentRegistry:()=>on,createActionManager:()=>Ws,createAgentExperience:()=>dl,createAskUserQuestionBubble:()=>Pg,createBestAvailableVoiceProvider:()=>gi,createBubbleWithLayout:()=>kh,createCSATFeedback:()=>sl,createComboButton:()=>qi,createComponentMiddleware:()=>rx,createComponentStreamParser:()=>rl,createDefaultSanitizer:()=>Al,createDirectivePostprocessor:()=>ig,createDropdownMenu:()=>In,createFlexibleJsonStreamParser:()=>Wg,createIconButton:()=>ur,createImagePart:()=>qg,createJsonStreamParser:()=>di,createLabelButton:()=>ks,createLocalStorageAdapter:()=>tl,createMarkdownProcessor:()=>ns,createMarkdownProcessorFromConfig:()=>Kn,createMessageActions:()=>np,createNPSFeedback:()=>il,createPlainTextParser:()=>ii,createPlugin:()=>Lx,createRegexJsonParser:()=>li,createStandardBubble:()=>Oa,createTextPart:()=>gs,createTheme:()=>Ba,createThemeObserver:()=>Ri,createToggleGroup:()=>vh,createTypingIndicator:()=>aa,createVoiceProvider:()=>Tn,createWidgetHostLayout:()=>Bs,createXmlParser:()=>ci,defaultActionHandlers:()=>da,defaultJsonActionParser:()=>Hs,defaultParseRules:()=>Ap,detectColorScheme:()=>vs,directivePostprocessor:()=>lg,ensureAskUserQuestionSheet:()=>Pa,escapeHtml:()=>No,extractComponentDirectiveFromMessage:()=>al,fileToImagePart:()=>Vg,formatEnrichedContext:()=>Sx,generateAssistantMessageId:()=>Yn,generateMessageId:()=>Fg,generateStableSelector:()=>Mp,generateUserMessageId:()=>Ra,getActiveTheme:()=>Da,getColorScheme:()=>qc,getDisplayText:()=>Og,getHeaderLayout:()=>Yc,getImageParts:()=>Ug,getPreset:()=>Rx,hasComponentDirective:()=>nl,hasImages:()=>_g,headerLayouts:()=>Vi,highContrastPlugin:()=>kx,initAgentWidget:()=>px,isAskUserQuestionMessage:()=>Qo,isComponentDirectiveType:()=>tx,isDockedMountMode:()=>sr,isSuggestRepliesMessage:()=>cs,isVoiceSupported:()=>xs,isWebMcpToolName:()=>vn,latestAgentSuggestions:()=>ri,listRegisteredStreamAnimations:()=>jc,markdownPostprocessor:()=>Sl,mergeWithDefaults:()=>ki,normalizeContent:()=>Ng,parseAskUserQuestionPayload:()=>Yo,parseSuggestRepliesPayload:()=>Bl,pickBestVoice:()=>Ia,pluginRegistry:()=>Is,reducedMotionPlugin:()=>Ex,registerStreamAnimationPlugin:()=>oa,removeAskUserQuestionSheet:()=>Sn,renderComponentDirective:()=>ol,renderLoadingIndicatorWithFallback:()=>op,renderLucideIcon:()=>fe,resolveDockConfig:()=>eo,resolveSanitizer:()=>Ta,resolveTokens:()=>Li,stripWebMcpPrefix:()=>Ks,themeToCssVariables:()=>Pi,unregisterStreamAnimationPlugin:()=>$c,validateImageFile:()=>zg,validateTheme:()=>Uc});var wl=null,os=null,Ma=null,og=e=>{wl=e};var js=()=>os?Promise.resolve(os):Ma||(wl?(Ma=wl().then(e=>(os=e,e)),Ma):(Ma=import("./markdown-parsers-entry").then(e=>(os=e,e)),Ma)),Gn=()=>os;var gy=e=>{if(e)return e},ns=e=>{let t=null;return r=>{var n,a;let o=Gn();if(!o)return No(r);if(!t){let{Marked:s}=o,i=e==null?void 0:e.markedOptions;t=new s({gfm:(n=i==null?void 0:i.gfm)!=null?n:!0,breaks:(a=i==null?void 0:i.breaks)!=null?a:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let c=gy(e==null?void 0:e.renderer);c&&t.use({renderer:c})}return t.parse(r)}},Kn=e=>e?ns({markedOptions:e.options,renderer:e.renderer}):ns(),hy=ns(),Sl=e=>hy(e),No=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),ag=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),ng=e=>`%%FORM_PLACEHOLDER_${e}%%`,sg=(e,t)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,n)=>{try{let a=JSON.parse(n.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=ng(t.length);return t.push({token:s,type:String(a.type)}),s}}catch{return o}return o}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,n)=>{let a=ng(t.length);return t.push({token:a,type:n}),a}),r},ig=e=>{let t=Kn(e);return r=>{let o=[],n=sg(r,o),a=t(n);return o.forEach(({token:s,type:i})=>{let c=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${ag(i)}"></div>`;a=a.replace(c,p)}),a}},lg=e=>{let t=[],r=sg(e,t),o=Sl(r);return t.forEach(({token:n,type:a})=>{let s=new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${ag(a)}"></div>`;o=o.replace(s,c)}),o};var xy={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"]},yy=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Al=()=>{let e=null;return t=>{let r=Gn();if(!r)return No(t);if(!e){let{DOMPurify:o}=r;e=o(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(n,a)=>{if(a.attrName==="src"||a.attrName==="href"){let s=a.attrValue;s.toLowerCase().startsWith("data:")&&!yy.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,xy)}},Ta=e=>e===!1?null:typeof e=="function"?e:Al();var dg=/^\s*\|?[\s:|-]*-[\s:|-]*$/,cg=e=>e.includes("|"),pg=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(r=>r.trim())},by=e=>`| ${e.join(" | ")} |`,vy=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Cy=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),ug=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
3
+ `),r=!1;for(let o=0;o<t.length-1;o++){let n=t[o],a=t[o+1];if(!cg(n)||dg.test(n)||!dg.test(a))continue;let s=pg(n).length;if(s<1)continue;let i=vy(s);t[o+1]!==i&&(t[o+1]=i,r=!0);let c=o+2;for(;c<t.length;c++){let l=t[c];if(l.trim()===""||!cg(l))break;let p=by(Cy(pg(l),s));t[c]!==p&&(t[c]=p,r=!0)}o=c-1}return r?t.join(`
4
+ `):e};var Co="webmcp:",Ml=new Map,fg=e=>{var t;Ml.clear();for(let r of e){let o=(t=r.title)==null?void 0:t.trim();o&&Ml.set(r.name,o)}},as=e=>Ml.get(Ks(e)),Gs={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Tl=null,gg=e=>{Tl=e};function hg(e){if(e.length===0)return"0:empty";let t=e.map(r=>{var o,n;return[r.name,(o=r.description)!=null?o:"",r.parametersSchema?JSON.stringify(r.parametersSchema):"",(n=r.origin)!=null?n:"",r.annotations?JSON.stringify(r.annotations):""].join("")}).sort();return`${e.length}:${wy(t.join(""))}`}function mg(e,t){let r=3735928559^t,o=1103547991^t;for(let n=0;n<e.length;n++){let a=e.charCodeAt(n);r=Math.imul(r^a,2654435761),o=Math.imul(o^a,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&o)+(r>>>0)}function wy(e){let t=mg(e,0).toString(36),r=mg(e,2654435761).toString(36);return`${t}.${r}`}var Ea=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var r;this.confirmHandler=(r=t.onConfirm)!=null?r: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 r;try{r=await t.getTools()}catch(n){return Gs.warn("getTools() threw: shipping an empty WebMCP snapshot.",n),[]}fg(r);let o=typeof location!="undefined"?location.origin:"";return r.filter(n=>this.passesClientAllowlist(n.name)).map(n=>{let a={name:n.name,description:n.description,origin:"webmcp",...o?{pageOrigin:o}:{}},s=Ay(n.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,r,o){if(await this.ensureReady(),this.config.enabled!==!0)return vo("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let x=typeof document!="undefined"&&!!document.modelContext;return vo(x?"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 a=Ks(t),s;try{s=await n.getTools()}catch(x){let b=x instanceof Error?x.message:String(x);return vo(`Failed to read WebMCP registry: ${b}`)}fg(s);let i=s.find(x=>x.name===a);if(!i)return vo(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return vo(`WebMCP tool not allowed by client allowlist: ${a}`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let c=as(a),l={toolName:a,args:r,description:i.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(l))return vo("User declined the tool call.");if(o!=null&&o.aborted)return vo("Aborted by cancel()");let p=new AbortController,f=!1,u=setTimeout(()=>{f=!0,p.abort()},this.timeoutMs),m=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",m,{once:!0}));try{let x=await n.executeTool(i,ky(r),{signal:p.signal});return My(x)}catch(x){if(f)return vo(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let b=x instanceof Error?x.message:String(x);return vo(b)}finally{clearTimeout(u),o&&o.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}(Tl?await Tl():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Gs.warn("Failed to load @mcp-b/webmcp-polyfill: 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 r=t;return typeof r.getTools!="function"||typeof r.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Gs.warn("document.modelContext is present but does not expose getTools()/executeTool(): 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 o;let r=(o=this.confirmHandler)!=null?o:Ty;try{return await r(t)}catch(n){return Gs.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,n),!1}}passesClientAllowlist(t){let r=this.config.allowlist;return!r||r.length===0?!0:r.some(o=>Sy(t,o))}},Ks=e=>e.startsWith(Co)?e.slice(Co.length):e,vn=e=>e.startsWith(Co),Sy=(e,t)=>{if(t==="*")return!0;let r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)},Ay=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},My=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:Ly(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Ty=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ey(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
3
5
 
4
6
  Arguments:
5
7
  ${t}`:"")+(e.description?`
6
8
 
7
- ${e.description}`:"");return window.confirm(r)},cy=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)}},uy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},fy=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var yn=ya(Ks(),1);var S=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},Bo=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var Mt=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let i of Object.keys(s)){let p=s[i];p!=null&&(a[i]=p)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},ts=(...e)=>e.filter(Boolean).join(" ");var os="ask_user_question",rs=8,wa="data-persona-ask-sheet-for",yy="Other",by="Other\u2026",ug="Type your own answer here",fg="Send",vy="Next",Cy="Back",wy="Submit all",Sy="Skip",Ay=3,Tl="data-ask-current-index",El="data-ask-question-count",mg="data-ask-answers",kl="data-ask-grouped",gg="data-ask-layout",My=e=>e.layout==="pills"?"pills":"rows",Ty=e=>e.getAttribute(gg)==="pills"?"pills":"rows",cg=!1,hg=e=>e.replace(/["\\]/g,"\\$&"),Xo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===os,Xs=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},Jo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:r};try{let n=o.join(""),a=(0,yn.parse)(n,yn.STR|yn.OBJ|yn.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},ns=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>rs&&!cg&&(cg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${rs}.`)),t.slice(0,rs)},Ey=e=>{var t;return(t=ns(e)[0])!=null?t:null},ky=(e,t)=>{var r;return(r=ns(e)[t])!=null?r:null},xg=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},yg=(e,t,r)=>{if(e!=="rows")return null;let o=S("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=S("span","persona-ask-row-check");o.appendChild(n)}else{let n=S("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Ly=(e,t,r,o)=>{let a=S("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),r==="rows"){let s=S("span","persona-ask-row-content"),i=S("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let d=S("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let p=yg(r,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Py=e=>{let r=S("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 r.setAttribute("aria-hidden","true"),r},Ry=(e,t,r,o)=>{var u,g,c;let a=S("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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),p=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(p.length===0&&!r){for(let m=0;m<Ay;m++)a.appendChild(Py(o));return a}if(p.forEach((m,x)=>{a.appendChild(Ly(m,x,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?yy:by;if(o==="rows"){let x=S("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(p.length)),x.setAttribute("data-ask-other-row","true");let C=S("span","persona-ask-row-content"),R=document.createElement("input");R.type="text",R.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",R.placeholder=(u=t.freeTextPlaceholder)!=null?u:ug,R.setAttribute("data-ask-free-text-input","true"),R.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),C.appendChild(R),x.appendChild(C);let M=yg(o,s,p.length);M&&x.appendChild(M),a.appendChild(x)}else{let x=S("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(c=t.freeTextLabel)!=null?c:m,a.appendChild(x)}}return a},bg=(e,t)=>{var a,s;let o=S("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");o.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=e.freeTextPlaceholder)!=null?a:ug,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=S("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:fg,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Iy=e=>{var o;let t=S("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=S("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:fg,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Wy=(e,t,r)=>{var d,u,g,c;let o=S("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=S("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(d=r.backLabel)!=null?d:Cy,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=S("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=S("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=r.skipLabel)!=null?u:Sy,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=S("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?(g=r.submitAllLabel)!=null?g:wy:(c=r.nextLabel)!=null?c:vy,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},jn=e=>{let t=e.getAttribute(mg);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},vg=(e,t)=>{e.setAttribute(mg,JSON.stringify(t))},po=e=>{var r;let t=Number((r=e.getAttribute(Tl))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Hy=(e,t)=>{e.setAttribute(Tl,String(Math.max(0,Math.floor(t))))},Sa=e=>{var r;let t=Number((r=e.getAttribute(El))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},bn=e=>e.getAttribute(kl)==="true",By=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let o={};return t.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let p=r[i];(typeof p=="string"||Array.isArray(p))&&(o[s]=p)}}),o},Dy=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},Js=(e,t)=>{let{payload:r}=Jo(t),o=ns(r),n=jn(e),a={},s=new Set;return o.forEach((i,p)=>{let d=typeof(i==null?void 0:i.question)=="string"?i.question:"";d&&(s.has(d)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(n,p)&&(a[d]=n[p]))}),a},Cg=e=>{let t=jn(e),r=po(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(p=>n.add(p));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(p=>{var g;let d=(g=p.getAttribute("data-option-label"))!=null?g:"",u=n.has(d);p.setAttribute("aria-pressed",u?"true":"false"),p.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(a).map(p=>{var d;return(d=p.getAttribute("data-option-label"))!=null?d:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let p=i.closest('[data-ask-free-text-row="true"]');p==null||p.classList.remove("persona-hidden")}else i.value=""},wg=e=>{if(!bn(e))return;let t=jn(e),r=po(e),o=t[r],n=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Ll=(e,t,r)=>{let o=Xs(r),n=Ty(e),{payload:a,complete:s}=Jo(t),i=bn(e),p=po(e),d=Sa(e),u=i?ky(a,p):Ey(a),g=!!(u!=null&&u.multiSelect),c=e.querySelector('[data-ask-step-inline="true"]');c&&(c.textContent=i?`${p+1}/${d}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let A=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=A,x.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let A=Ry(u,o,s,n);C.replaceWith(A)}if(n!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(bg(o,n))}let R=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!R?e.appendChild(Iy(o)):(!g||i)&&R&&R.remove(),e.setAttribute("data-multi-select",g?"true":"false");let M=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=Wy(p,d,o);M?M.replaceWith(A):e.appendChild(A)}else M&&M.remove();Cg(e),wg(e)},Fy=(e,t,r)=>{let o=Xs(t),n=My(o),a=e.toolCall.id,s=ns(r),i=Math.max(1,s.length),p=i>1,d=By(e,s),u=p?Dy(e,i):0,g=S("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(wa,a),g.setAttribute("data-tool-call-id",a),g.setAttribute("data-message-id",e.id),g.setAttribute(El,String(i)),g.setAttribute(Tl,String(u)),g.setAttribute(kl,p?"true":"false"),g.setAttribute(gg,n),vg(g,d),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),xg(g,o);let c=S("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=S("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",c.appendChild(m);let x=S("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",c.appendChild(x),g.appendChild(c);let R=S("div",n==="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 R.setAttribute("data-ask-pill-list","true"),R.setAttribute("role","group"),g.appendChild(R),n!=="rows"&&g.appendChild(bg(o,n)),Ll(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Ny=(e,t,r)=>{let{payload:o}=Jo(t),n=Math.max(1,ns(o).length);n>Sa(e)&&(e.setAttribute(El,String(n)),n>1&&!bn(e)&&e.setAttribute(kl,"true")),Ll(e,t,r)},Sg=(e,t)=>{let r=S("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let o=Xs(t);xg(r,o);let n=S("span","persona-ask-stub-label"),{complete:a}=Jo(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Aa=(e,t,r)=>{if(!r||!Xo(e)||Xs(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${wa}]`).forEach(d=>{d.getAttribute(wa)!==n&&d.remove()});let s=r.querySelector(`[${wa}="${hg(n)}"]`);if(s){Ny(s,e,t);return}let{payload:i}=Jo(e),p=Fy(e,t,i);r.appendChild(p)},vn=(e,t)=>{if(!e)return;let r=t?`[${wa}="${hg(t)}"]`:`[${wa}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Pl=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),Cn=(e,t)=>{let r=jn(e),o=po(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,vg(e,r),Cg(e),wg(e)},Qs=(e,t,r,o)=>{let n=Sa(e),a=Math.max(0,Math.min(n-1,o));Hy(e,a),Ll(e,t,r)};var bo="suggest_replies";var Rl={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Ys={name:bo,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Rl,origin:"sdk",annotations:{readOnlyHint:!0}},Il=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),as=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===bo},Wl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let r=t==null?void 0:t.suggestions;if(!Array.isArray(r))return[];let o=r.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Zs=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!as(o))continue;let n=Wl((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},Ag=e=>{var r;let t=(r=e==null?void 0:e.features)==null?void 0:r.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Hl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:rs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Bl={name:os,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Hl,origin:"sdk",annotations:{readOnlyHint:!0}},ss=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(Bl),Ag(e)&&t.push(Ys),t};var Qo=ya(Ks(),1),ei=e=>e.replace(/\\n/g,`
8
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ma=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)}},Oy=e=>{var s,i;let t=(s=e.completedAt)!=null?s:Date.now(),r=(i=e.startedAt)!=null?i:t,n=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-r))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},Mg=e=>e.status==="complete"?Oy(e):e.status==="pending"?"Waiting":"",_y=e=>{var n,a,s;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(a=e.startedAt)!=null?a:e.completedAt)!=null?s:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Tg=e=>e.status==="complete"?_y(e):"Using tool...",ti=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ls=e=>{var r,o,n;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ti(t)},ri=e=>{var r,o,n;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ti(t)},Dl=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=ls(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},oi=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&is(o,r.slice(a,s.index),[]),s[1]!==void 0?is(o,s[1],["bold"]):s[2]!==void 0?is(o,s[2],["italic"]):s[3]!==void 0&&is(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&is(o,r.slice(a),[]),o},is=(e,t,r)=>{let o=t.split("{duration}");for(let n=0;n<o.length;n++)o[n]&&e.push({text:o[n],styles:r}),n<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},Uy=()=>{let e=null,t=0,r=o=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(n);if(a&&a[1])try{return a[1].replace(/\\n/g,`
9
+ ${e.description}`:"");return window.confirm(r)},Ey=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)}},ky=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ly=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Cn=Aa(Qs(),1);var C=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},Oo=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var At=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let i of Object.keys(s)){let c=s[i];c!=null&&(a[i]=c)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},ss=(...e)=>e.filter(Boolean).join(" ");var ls="ask_user_question",is=8,ka="data-persona-ask-sheet-for",Wy="Other",By="Other\u2026",bg="Type your own answer here",vg="Send",Dy="Next",Fy="Back",Ny="Submit all",Oy="Skip",_y=3,kl="data-ask-current-index",Ll="data-ask-question-count",Cg="data-ask-answers",Pl="data-ask-grouped",wg="data-ask-layout",Uy=e=>e.layout==="pills"?"pills":"rows",qy=e=>e.getAttribute(wg)==="pills"?"pills":"rows",yg=!1,Sg=e=>e.replace(/["\\]/g,"\\$&"),Qo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ls,Ys=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},Yo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:r};try{let n=o.join(""),a=(0,Cn.parse)(n,Cn.STR|Cn.OBJ|Cn.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},ds=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>is&&!yg&&(yg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${is}.`)),t.slice(0,is)},Vy=e=>{var t;return(t=ds(e)[0])!=null?t:null},zy=(e,t)=>{var r;return(r=ds(e)[t])!=null?r:null},Ag=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},Mg=(e,t,r)=>{if(e!=="rows")return null;let o=C("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=C("span","persona-ask-row-check");o.appendChild(n)}else{let n=C("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},$y=(e,t,r,o)=>{let a=C("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),r==="rows"){let s=C("span","persona-ask-row-content"),i=C("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let l=C("span","persona-ask-row-description");l.textContent=e.description,s.appendChild(l)}a.appendChild(s);let c=Mg(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},jy=e=>{let r=C("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 r.setAttribute("aria-hidden","true"),r},Gy=(e,t,r,o)=>{var p,f,u;let a=C("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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),c=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(c.length===0&&!r){for(let m=0;m<_y;m++)a.appendChild(jy(o));return a}if(c.forEach((m,x)=>{a.appendChild($y(m,x,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Wy:By;if(o==="rows"){let x=C("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(c.length)),x.setAttribute("data-ask-other-row","true");let b=C("span","persona-ask-row-content"),L=document.createElement("input");L.type="text",L.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",L.placeholder=(p=t.freeTextPlaceholder)!=null?p:bg,L.setAttribute("data-ask-free-text-input","true"),L.setAttribute("aria-label",(f=t.freeTextLabel)!=null?f:m),b.appendChild(L),x.appendChild(b);let E=Mg(o,s,c.length);E&&x.appendChild(E),a.appendChild(x)}else{let x=C("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(u=t.freeTextLabel)!=null?u:m,a.appendChild(x)}}return a},Tg=(e,t)=>{var a,s;let o=C("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");o.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=e.freeTextPlaceholder)!=null?a:bg,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=C("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:vg,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Ky=e=>{var o;let t=C("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=C("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:vg,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Xy=(e,t,r)=>{var l,p,f,u;let o=C("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=C("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(l=r.backLabel)!=null?l:Fy,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=C("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=C("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(p=r.skipLabel)!=null?p:Oy,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=C("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(f=r.submitAllLabel)!=null?f:Ny:(u=r.nextLabel)!=null?u:Dy,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},Xn=e=>{let t=e.getAttribute(Cg);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Eg=(e,t)=>{e.setAttribute(Cg,JSON.stringify(t))},po=e=>{var r;let t=Number((r=e.getAttribute(kl))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Jy=(e,t)=>{e.setAttribute(kl,String(Math.max(0,Math.floor(t))))},La=e=>{var r;let t=Number((r=e.getAttribute(Ll))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},wn=e=>e.getAttribute(Pl)==="true",Qy=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let o={};return t.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let c=r[i];(typeof c=="string"||Array.isArray(c))&&(o[s]=c)}}),o},Yy=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},Zs=(e,t)=>{let{payload:r}=Yo(t),o=ds(r),n=Xn(e),a={},s=new Set;return o.forEach((i,c)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(n,c)&&(a[l]=n[c]))}),a},kg=e=>{let t=Xn(e),r=po(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var f;let l=(f=c.getAttribute("data-option-label"))!=null?f:"",p=n.has(l);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let s=new Set(Array.from(a).map(c=>{var l;return(l=c.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},Lg=e=>{if(!wn(e))return;let t=Xn(e),r=po(e),o=t[r],n=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Rl=(e,t,r)=>{let o=Ys(r),n=qy(e),{payload:a,complete:s}=Yo(t),i=wn(e),c=po(e),l=La(e),p=i?zy(a,c):Vy(a),f=!!(p!=null&&p.multiSelect),u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${c+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let A=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=A,x.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let A=Gy(p,o,s,n);b.replaceWith(A)}if(n!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Tg(o,n))}let L=e.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!L?e.appendChild(Ky(o)):(!f||i)&&L&&L.remove(),e.setAttribute("data-multi-select",f?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=Xy(c,l,o);E?E.replaceWith(A):e.appendChild(A)}else E&&E.remove();kg(e),Lg(e)},Zy=(e,t,r)=>{let o=Ys(t),n=Uy(o),a=e.toolCall.id,s=ds(r),i=Math.max(1,s.length),c=i>1,l=Qy(e,s),p=c?Yy(e,i):0,f=C("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(ka,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",e.id),f.setAttribute(Ll,String(i)),f.setAttribute(kl,String(p)),f.setAttribute(Pl,c?"true":"false"),f.setAttribute(wg,n),Eg(f,l),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Ag(f,o);let u=C("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=C("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",u.appendChild(m);let x=C("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",u.appendChild(x),f.appendChild(u);let L=C("div",n==="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 L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),f.appendChild(L),n!=="rows"&&f.appendChild(Tg(o,n)),Rl(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},eb=(e,t,r)=>{let{payload:o}=Yo(t),n=Math.max(1,ds(o).length);n>La(e)&&(e.setAttribute(Ll,String(n)),n>1&&!wn(e)&&e.setAttribute(Pl,"true")),Rl(e,t,r)},Pg=(e,t)=>{let r=C("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let o=Ys(t);Ag(r,o);let n=C("span","persona-ask-stub-label"),{complete:a}=Yo(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Pa=(e,t,r)=>{if(!r||!Qo(e)||Ys(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${ka}]`).forEach(l=>{l.getAttribute(ka)!==n&&l.remove()});let s=r.querySelector(`[${ka}="${Sg(n)}"]`);if(s){eb(s,e,t);return}let{payload:i}=Yo(e),c=Zy(e,t,i);r.appendChild(c)},Sn=(e,t)=>{if(!e)return;let r=t?`[${ka}="${Sg(t)}"]`:`[${ka}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Il=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),An=(e,t)=>{let r=Xn(e),o=po(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,Eg(e,r),kg(e),Lg(e)},ei=(e,t,r,o)=>{let n=La(e),a=Math.max(0,Math.min(n-1,o));Jy(e,a),Rl(e,t,r)};var wo="suggest_replies";var Hl={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},ti={name:wo,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Hl,origin:"sdk",annotations:{readOnlyHint:!0}},Wl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),cs=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===wo},Bl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let r=t==null?void 0:t.suggestions;if(!Array.isArray(r))return[];let o=r.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},ri=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!cs(o))continue;let n=Bl((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},Rg=e=>{var r;let t=(r=e==null?void 0:e.features)==null?void 0:r.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Dl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:is,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Fl={name:ls,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Dl,origin:"sdk",annotations:{readOnlyHint:!0}},ps=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(Fl),Rg(e)&&t.push(ti),t};var Zo=Aa(Qs(),1),oi=e=>e.replace(/\\n/g,`
10
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Mn=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)}},tb=e=>{var s,i;let t=(s=e.completedAt)!=null?s:Date.now(),r=(i=e.startedAt)!=null?i:t,n=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-r))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},Ig=e=>e.status==="complete"?tb(e):e.status==="pending"?"Waiting":"",rb=e=>{var n,a,s;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(a=e.startedAt)!=null?a:e.completedAt)!=null?s:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Hg=e=>e.status==="complete"?rb(e):"Using tool...",ni=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},fs=e=>{var r,o,n;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ni(t)},ai=e=>{var r,o,n;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ni(t)},Nl=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=fs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},si=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&us(o,r.slice(a,s.index),[]),s[1]!==void 0?us(o,s[1],["bold"]):s[2]!==void 0?us(o,s[2],["italic"]):s[3]!==void 0&&us(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&us(o,r.slice(a),[]),o},us=(e,t,r)=>{let o=t.split("{duration}");for(let n=0;n<o.length;n++)o[n]&&e.push({text:o[n],styles:r}),n<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},ob=()=>{let e=null,t=0,r=o=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(n);if(a&&a[1])try{return a[1].replace(/\\n/g,`
9
11
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
10
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ds=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ni=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ai=()=>{var t;let e=Uy();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},si=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,Qo.parse)(r,Qo.STR|Qo.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?ei(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=ei(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Eg=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?ei(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ei(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,Qo.parse)(a,Qo.STR|Qo.OBJ),p=n(i);p!==null&&(t=p)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},ii=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var kg="4.0.0";var Gn=kg;var Vy="https://api.runtype.com/v1/dispatch",li="https://api.runtype.com";function zy(e){var a,s;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Fl=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 $y(e){switch(e){case"json":return si;case"regex-json":return ai;case"xml":return ii;default:return ni}}var Lg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function jy(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=Lg(r);if(!Lg(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ds(e);return ds(t)!==null&&s===null?t:e}var Kn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;this.apiUrl=(r=t.apiUrl)!=null?r:Vy,this.headers={"Content-Type":"application/json","X-Persona-Version":Gn,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:$y(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ca(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||li}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;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 o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let t=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Gn},body:JSON.stringify(r)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let n=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(n.sessionId),{sessionId:n.sessionId,expiresAt:new Date(n.expiresAt),flow:n.flow,config:{welcomeMessage:n.config.welcomeMessage,placeholder:n.config.placeholder,theme:n.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||li}/v1/client/feedback`}async sendFeedback(t){var s,i;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 n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Gn},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(p.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let p=await this.initSession();if(new Date>=new Date(p.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let d=await this.buildPayload(t.messages),u=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,g={sessionId:p.sessionId,messages:t.messages.filter(Fl).map(y=>{var w,b,T;return{id:y.id,role:y.role,content:(T=(b=(w=y.contentParts)!=null?w:y.llmContent)!=null?b:y.rawContent)!=null?T:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},c=d.clientTools,m=!!(c&&c.length>0),x=m?dg(c):void 0,C=this.clientToolsFingerprintSessionId===p.sessionId,R=m&&C&&this.lastSentClientToolsFingerprint===x,M=!1,A=null,L;for(let y=0;;y++){let b={...g,...m&&(M||!R)&&c?{clientTools:c}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",b),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Gn},body:JSON.stringify(b),signal:o.signal}),L.status===409&&y===0&&m){let T=await L.json().catch(()=>null);if((T==null?void 0:T.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}A=T!=null?T:{error:"Chat request failed"}}break}if(!L.ok){let y=A!=null?A:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let b=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:b}),b}if(L.status===429){let b=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:b}),b}let w=new Error(y.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!L.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=p.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(L.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(p){let d=p instanceof Error?p:new Error(String(p));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&r({type:"error",error:d}),d}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let p=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:p}),p}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let p=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:p}),p}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||li}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var d,u;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((d=this.config.apiUrl)==null?void 0:d.replace(/\/+$/,""))||li}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:r,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return s&&(p.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(p),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var a,s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Fl).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),u=new Date(p.createdAt).getTime();return d-u}).map(i=>{var p,d,u;return{role:i.role,content:(u=(d=(p=i.contentParts)!=null?p:i.llmContent)!=null?d:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),o={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},n=[...ss(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async p=>{try{let d=await p({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(i,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(i).length&&(o.context=i)}return o}async buildPayload(t){var a,s;let o={messages:t.slice().filter(Fl).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),u=new Date(p.createdAt).getTime();return d-u}).map(i=>{var p,d,u;return{role:i.role,content:(u=(d=(p=i.contentParts)!=null?p:i.llmContent)!=null?d:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},n=[...ss(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async p=>{try{let d=await p({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(i,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(i).length&&(o.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...o},config:this.config});if(i&&typeof i=="object"){let p=i;return o.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=o.clientTools),p}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return o}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...u!==void 0&&{partId:u}};return o.current=g,n(g),g},d=u=>o.current?o.current:p(u);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),p(i.partId)),i.partId!==void 0&&(s.current=i.partId);let u=d(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,n(u)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var ar,Co,yr,ze;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),p=0,d=()=>i+p++,u=H=>{let de=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,Te=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,Se=H.tools?H.tools.map(Le=>({...Le,chunks:Le.chunks?[...Le.chunks]:void 0})):void 0;return{...H,reasoning:de,toolCall:Te,tools:Se}},g=H=>{if(H.role!=="assistant"||H.variant)return!0;let de=Array.isArray(H.contentParts)&&H.contentParts.length>0,Te=typeof H.rawContent=="string"&&H.rawContent.trim()!=="";return typeof H.content=="string"&&H.content.trim()!==""||de||Te||!!H.stopReason},c=H=>{g(H)&&r({type:"message",message:u(H)})},m=null,x=null,C={current:null},R={current:null},M=null,A="",L=new Map,y=new Map,w=new Map,b=new Map,T=new Map,I={lastId:null,byStep:new Map},P={lastId:null,byCall:new Map},k=H=>{if(H==null)return null;try{return String(H)}catch{return null}},N=H=>{var de,Te,Se,Le,Ze;return k((Ze=(Le=(Se=(Te=(de=H.stepId)!=null?de:H.step_id)!=null?Te:H.step)!=null?Se:H.parentId)!=null?Le:H.flowStepId)!=null?Ze:H.flow_step_id)},U=H=>{var de,Te,Se,Le,Ze,Ke,dt;return k((dt=(Ke=(Ze=(Le=(Se=(Te=(de=H.callId)!=null?de:H.call_id)!=null?Te:H.requestId)!=null?Se:H.request_id)!=null?Le:H.toolCallId)!=null?Ze:H.tool_call_id)!=null?Ke:H.stepId)!=null?dt:H.step_id)},Y=o,he=!1,$e=()=>{if(m)return m;let H,de=M;return!he&&Y?(H=Y,he=!0):Y&&de?H=`${Y}_${de}`:H=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:H,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d()},c(m),m},Me=(H,de)=>{I.lastId=de,H&&I.byStep.set(H,de)},Ie=(H,de)=>{var Ze;let Te=(Ze=H.reasoningId)!=null?Ze:H.id,Se=N(H);if(Te){let Ke=String(Te);return Me(Se,Ke),Ke}if(Se){let Ke=I.byStep.get(Se);if(Ke)return I.lastId=Ke,Ke}if(I.lastId&&!de)return I.lastId;if(!de)return null;let Le=`reason-${d()}`;return Me(Se,Le),Le},qe=H=>{let de=b.get(H);if(de)return de;let Te={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:H,status:"streaming",chunks:[]}};return b.set(H,Te),c(Te),Te},Ee=(H,de)=>{P.lastId=de,H&&P.byCall.set(H,de)},Be=new Set,ae=new Map,Q=new Set,pe=new Map,ye=H=>{if(!H)return!1;let de=H.replace(/_+/g,"_").replace(/^_|_$/g,"");return de==="emit_artifact_markdown"||de==="emit_artifact_component"},ne=(H,de)=>{var Ze;let Te=(Ze=H.toolId)!=null?Ze:H.id,Se=U(H);if(Te){let Ke=String(Te);return Ee(Se,Ke),Ke}if(Se){let Ke=P.byCall.get(Se);if(Ke)return P.lastId=Ke,Ke}if(P.lastId&&!de)return P.lastId;if(!de)return null;let Le=`tool-${d()}`;return Ee(Se,Le),Le},K=H=>{let de=T.get(H);if(de)return de;let Te={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:H,status:"pending"}};return T.set(H,Te),c(Te),Te},oe=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let de=Number(H);if(!Number.isNaN(de)&&Number.isFinite(de))return de;let Te=Date.parse(H);if(!Number.isNaN(Te))return Te}return Date.now()},Ge=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},Z=new Map,se=new Map,We=new Map,Ct=(H,de,Te)=>{var dt;let Se=We.get(H);Se||(Se=[],We.set(H,Se));let Le=0,Ze=Se.length;for(;Le<Ze;){let It=Le+Ze>>>1;Se[It].seq<de?Le=It+1:Ze=It}((dt=Se[Le])==null?void 0:dt.seq)===de?Se[Le]={seq:de,text:Te}:Se.splice(Le,0,{seq:de,text:Te});let Ke="";for(let It=0;It<Se.length;It++)Ke+=Se[It].text;return Ke},Lt=(H,de)=>{let Te=Ge(de),Se=se.get(H.id),Le=jy(Se,Te);H.rawContent=Le;let Ze=Z.get(H.id),Ke=j=>{var Ae;let le=(Ae=H.content)!=null?Ae:"";j.trim()!==""&&(le.trim().length===0||j.startsWith(le)||j.trimStart().startsWith(le.trim()))&&(H.content=j)},dt=()=>{var j;if(Ze){let le=(j=Ze.close)==null?void 0:j.call(Ze);le instanceof Promise&&le.catch(()=>{})}Z.delete(H.id),se.delete(H.id),H.streaming=!1,c(H)};if(!Ze){Ke(Te),dt();return}let It=ds(Le);if(It!==null&&It.trim()!==""){Ke(It),dt();return}let z=j=>{var xt;let le=typeof j=="string"?j:(xt=j==null?void 0:j.text)!=null?xt:null;if(le!==null&&le.trim()!=="")return le;let Ae=Ze.getExtractedText();return Ae!==null&&Ae.trim()!==""?Ae:Te},ot;try{ot=Ze.processChunk(Le)}catch{Ke(Te),dt();return}if(ot instanceof Promise){ot.then(j=>{Ke(z(j)),dt()}).catch(()=>{Ke(Te),dt()});return}Ke(z(ot)),dt()},mt=null,Oe=(H,de,Te,Se)=>{var It;H.rawContent=de,Z.has(H.id)||Z.set(H.id,this.createStreamParser());let Le=Z.get(H.id),Ze=de.trim().startsWith("{")||de.trim().startsWith("[");if(Ze&&se.set(H.id,de),Le.__isPlainTextParser===!0){H.content=Se!==void 0?de:H.content+Te,se.delete(H.id),Z.delete(H.id),H.rawContent=void 0,c(H);return}let dt=Le.processChunk(de);if(dt instanceof Promise)dt.then(z=>{var j;let ot=typeof z=="string"?z:(j=z==null?void 0:z.text)!=null?j:null;ot!==null&&ot.trim()!==""?(H.content=ot,c(H)):!Ze&&!de.trim().startsWith("<")&&(H.content=Se!==void 0?de:H.content+Te,se.delete(H.id),Z.delete(H.id),H.rawContent=void 0,c(H))}).catch(()=>{H.content=Se!==void 0?de:H.content+Te,se.delete(H.id),Z.delete(H.id),H.rawContent=void 0,c(H)});else{let z=typeof dt=="string"?dt:(It=dt==null?void 0:dt.text)!=null?It:null;z!==null&&z.trim()!==""?(H.content=z,c(H)):!Ze&&!de.trim().startsWith("<")&&(H.content=Se!==void 0?de:H.content+Te,se.delete(H.id),Z.delete(H.id),H.rawContent=void 0,c(H))}},fe=(H,de)=>{var It,z;let Te=de!=null?de:H.content;if(Te==null||Te===""){H.streaming=!1,c(H);return}let Se=se.get(H.id),Le=Se!=null?Se:Ge(Te);H.rawContent=Le;let Ze=Z.get(H.id),Ke=null,dt=!1;if(Ze&&(Ke=Ze.getExtractedText(),Ke===null&&(Ke=ds(Le)),Ke===null)){let ot=Ze.processChunk(Le);ot instanceof Promise?(dt=!0,ot.then(j=>{var Ae;let le=typeof j=="string"?j:(Ae=j==null?void 0:j.text)!=null?Ae:null;le!==null&&(H.content=le,H.streaming=!1,Z.delete(H.id),se.delete(H.id),c(H))}).catch(()=>{})):Ke=typeof ot=="string"?ot:(It=ot==null?void 0:ot.text)!=null?It:null}if(!dt){Ke!==null&&Ke.trim()!==""?H.content=Ke:se.has(H.id)||(H.content=Ge(Te));let ot=Z.get(H.id);if(ot){let j=(z=ot.close)==null?void 0:z.call(ot);j instanceof Promise&&j.catch(()=>{}),Z.delete(H.id)}se.delete(H.id),H.streaming=!1,c(H)}},Ye=(H,de,Te)=>{let Se=y.get(H);if(Se)return Se;let Le={id:`nested-${de}-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:H,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:de}};return y.set(H,Le),c(Le),Le},X=[],ie,ve=new Map,Ve=0,Pt="agent",we=null,ce=null,xr=new Map,Rt=(ar=this.config.iterationDisplay)!=null?ar:"separate";for(ie=()=>{var H,de,Te,Se,Le,Ze,Ke,dt,It,z,ot,j,le,Ae,xt,Zt,er,fr,Ht,et,Wt,st,Gt,to,Ar,tr,Wr,wo,yt,Or,So,Fo,uo,gt,Ln,Ao,Pn,Hr,aa,rn,No,on,nn,Rn,In,an,vt,_r,Ur,Mr,St,ro,oo,qr,sn,Oo,ln,Vr,Bt,Tr,no,dn,_o,pn,Mo,zr,ge,it,Xt,sr,To,Ua,Uo,Wn,Eo,_,sa,ko,Lo,qo,Po,fo,ia,Is,$r,jr,mo,go,Hn,Vo,br,Ro,la,Bn,da,Ws,pa,Hs,ca,ft,qa,ao,Br,Bs,Ds;for(let cn=0;cn<X.length;cn++){let tt=X[cn].payloadType,E=X[cn].payload;if(tt==="reasoning_start"){let V=typeof E.id=="string"?E.id:null,q=typeof E.parentToolCallId=="string"&&E.parentToolCallId?E.parentToolCallId:null;if(V&&q){L.set(V,q),Ye(V,q,"reasoning");continue}let G=(H=Ie(E,!0))!=null?H:`reason-${d()}`,me=qe(G);me.reasoning=(de=me.reasoning)!=null?de:{id:G,status:"streaming",chunks:[]},me.reasoning.startedAt=(Se=me.reasoning.startedAt)!=null?Se:oe((Te=E.startedAt)!=null?Te:E.timestamp),me.reasoning.completedAt=void 0,me.reasoning.durationMs=void 0,(E.scope==="loop"||E.scope==="turn")&&(me.reasoning.scope=E.scope),me.streaming=!0,me.reasoning.status="streaming",c(me)}else if(tt==="reasoning_delta"){let V=typeof E.id=="string"?E.id:null;if(V&&L.has(V)&&y.has(V)){let Fe=y.get(V),Je=(Ke=(Ze=(Le=E.reasoningText)!=null?Le:E.text)!=null?Ze:E.delta)!=null?Ke:"";Je&&E.hidden!==!0&&Fe.reasoning&&(Fe.reasoning.chunks.push(String(Je)),c(Fe));continue}let q=(It=(dt=Ie(E,!1))!=null?dt:Ie(E,!0))!=null?It:`reason-${d()}`,G=qe(q);G.reasoning=(z=G.reasoning)!=null?z:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(j=G.reasoning.startedAt)!=null?j:oe((ot=E.startedAt)!=null?ot:E.timestamp);let me=(xt=(Ae=(le=E.reasoningText)!=null?le:E.text)!=null?Ae:E.delta)!=null?xt:"";if(me&&E.hidden!==!0){let Fe=typeof E.sequenceIndex=="number"?E.sequenceIndex:void 0;if(Fe!==void 0){let Je=Ct(q,Fe,String(me));G.reasoning.chunks=[Je]}else G.reasoning.chunks.push(String(me))}if(G.reasoning.status=E.done?"complete":"streaming",E.done){G.reasoning.completedAt=oe((Zt=E.completedAt)!=null?Zt:E.timestamp);let Fe=(er=G.reasoning.startedAt)!=null?er:Date.now();G.reasoning.durationMs=Math.max(0,((fr=G.reasoning.completedAt)!=null?fr:Date.now())-Fe)}G.streaming=G.reasoning.status!=="complete",c(G)}else if(tt==="reasoning_complete"){let V=typeof E.id=="string"?E.id:null;if(V&&L.has(V)&&y.has(V)){let Je=y.get(V);if(Je.reasoning){let Tt=typeof E.text=="string"?E.text:"";Tt&&Je.reasoning.chunks.length===0&&Je.reasoning.chunks.push(Tt),Je.reasoning.status="complete",Je.streaming=!1,c(Je)}L.delete(V),y.delete(V);continue}let q=(et=(Ht=Ie(E,!1))!=null?Ht:Ie(E,!0))!=null?et:`reason-${d()}`,G=typeof E.text=="string"?E.text:"";!b.get(q)&&(G||E.scope==="loop")&&qe(q);let me=b.get(q);if(me!=null&&me.reasoning){(E.scope==="loop"||E.scope==="turn")&&(me.reasoning.scope=E.scope),G&&me.reasoning.chunks.length===0&&me.reasoning.chunks.push(G),me.reasoning.status="complete",me.reasoning.completedAt=oe((Wt=E.completedAt)!=null?Wt:E.timestamp);let Je=(st=me.reasoning.startedAt)!=null?st:Date.now();me.reasoning.durationMs=Math.max(0,((Gt=me.reasoning.completedAt)!=null?Gt:Date.now())-Je),me.streaming=!1,c(me)}let Fe=N(E);Fe&&I.byStep.delete(Fe)}else if(tt==="tool_start"){m&&(m.streaming=!1,c(m),m=null),typeof E.iteration=="number"&&(Ve=E.iteration);let V=(Ar=(to=typeof E.toolCallId=="string"?E.toolCallId:void 0)!=null?to:ne(E,!0))!=null?Ar:`tool-${d()}`,q=(tr=E.toolName)!=null?tr:E.name;if(ye(q)){Be.add(V);continue}Ee(U(E),V);let G=K(V),me=(Wr=G.toolCall)!=null?Wr:{id:V,status:"pending"};me.name=q!=null?q:me.name,me.status="running",E.parameters!==void 0?me.args=E.parameters:E.args!==void 0&&(me.args=E.args),me.startedAt=(yt=me.startedAt)!=null?yt:oe((wo=E.startedAt)!=null?wo:E.timestamp),me.completedAt=void 0,me.durationMs=void 0,G.toolCall=me,G.streaming=!0,E.executionId&&(G.agentMetadata={executionId:E.executionId,iteration:E.iteration}),c(G)}else if(tt==="tool_output_delta"){let V=(So=(Or=ne(E,!1))!=null?Or:ne(E,!0))!=null?So:`tool-${d()}`;if(Be.has(V))continue;let q=K(V),G=(Fo=q.toolCall)!=null?Fo:{id:V,status:"running"};G.startedAt=(gt=G.startedAt)!=null?gt:oe((uo=E.startedAt)!=null?uo:E.timestamp);let me=(Pn=(Ao=(Ln=E.text)!=null?Ln:E.delta)!=null?Ao:E.message)!=null?Pn:"";me&&(G.chunks=(Hr=G.chunks)!=null?Hr:[],G.chunks.push(String(me))),G.status="running",q.toolCall=G,q.streaming=!0;let Fe=E.agentContext;(Fe||E.executionId)&&(q.agentMetadata=(No=q.agentMetadata)!=null?No:{executionId:(aa=Fe==null?void 0:Fe.executionId)!=null?aa:E.executionId,iteration:(rn=Fe==null?void 0:Fe.iteration)!=null?rn:E.iteration}),c(q)}else if(tt==="tool_complete"){let V=(nn=(on=ne(E,!1))!=null?on:ne(E,!0))!=null?nn:`tool-${d()}`;if(Be.has(V)){Be.delete(V);continue}let q=K(V),G=(Rn=q.toolCall)!=null?Rn:{id:V,status:"running"};G.status="complete",E.result!==void 0&&(G.result=E.result),typeof E.duration=="number"&&(G.duration=E.duration),G.completedAt=oe((In=E.completedAt)!=null?In:E.timestamp);let me=(an=E.duration)!=null?an:E.executionTime;if(typeof me=="number")G.durationMs=me;else{let Tt=(vt=G.startedAt)!=null?vt:Date.now();G.durationMs=Math.max(0,((_r=G.completedAt)!=null?_r:Date.now())-Tt)}q.toolCall=G,q.streaming=!1;let Fe=E.agentContext;(Fe||E.executionId)&&(q.agentMetadata=(St=q.agentMetadata)!=null?St:{executionId:(Ur=Fe==null?void 0:Fe.executionId)!=null?Ur:E.executionId,iteration:(Mr=Fe==null?void 0:Fe.iteration)!=null?Mr:E.iteration}),c(q);let Je=U(E);Je&&P.byCall.delete(Je)}else if(tt==="await"&&E.toolName){let V=typeof E.toolCallId=="string"&&E.toolCallId.length>0?E.toolCallId:void 0,q=(ro=V!=null?V:E.toolId)!=null?ro:`local-${d()}`,G=K(q),me=E.toolName,Fe=E.origin==="webmcp"&&!xn(me)?`webmcp:${me}`:me,Je=xn(Fe),Tt=(oo=G.toolCall)!=null?oo:{id:q,status:"pending"};Tt.name=Fe,Tt.args=E.parameters,Tt.status=Je?"running":"complete",Tt.chunks=(qr=Tt.chunks)!=null?qr:[],Tt.startedAt=(ln=Tt.startedAt)!=null?ln:oe((Oo=(sn=E.startedAt)!=null?sn:E.timestamp)!=null?Oo:E.awaitedAt),Je?(Tt.completedAt=void 0,Tt.duration=void 0,Tt.durationMs=void 0):Tt.completedAt=(Vr=Tt.completedAt)!=null?Vr:Tt.startedAt,G.toolCall=Tt,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Tr=E.executionId)!=null?Tr:(Bt=G.agentMetadata)==null?void 0:Bt.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},c(G)}else if(tt==="text_start"){let V=typeof E.id=="string"?E.id:null,q=typeof E.parentToolCallId=="string"&&E.parentToolCallId?E.parentToolCallId:null;if(V&&q){L.set(V,q);continue}let G=m;G&&(Pt==="flow"?(fe(G),mt=G):(G.streaming=!1,c(G)),m=null),M=typeof E.id=="string"?E.id:M,A=""}else if(tt==="text_delta"){let V=typeof E.id=="string"?E.id:null,q=V?L.get(V):void 0;if(V&&q){let me=typeof E.delta=="string"?E.delta:"",Fe=((no=w.get(V))!=null?no:"")+me;if(w.set(V,Fe),Fe.trim()==="")continue;let Je=Ye(V,q);Je.agentMetadata={...Je.agentMetadata,executionId:E.executionId,parentToolId:q},Oe(Je,Fe,me,void 0);continue}if(M=typeof E.id=="string"?E.id:M,Pt==="flow"){let me=typeof E.delta=="string"?E.delta:"";if(A+=me,A.trim()==="")continue;let Fe=$e();Fe.agentMetadata={executionId:E.executionId,iteration:E.iteration},Oe(Fe,A,me,void 0),x=Fe;continue}let G=$e();G.content+=(dn=E.delta)!=null?dn:"",G.agentMetadata={executionId:E.executionId,iteration:E.iteration,turnId:we!=null?we:void 0,agentName:ce==null?void 0:ce.agentName},x=G,c(G)}else if(tt==="text_complete"){let V=typeof E.id=="string"?E.id:null;if(V&&L.has(V)){let G=y.get(V);G&&fe(G),L.delete(V),w.delete(V),y.delete(V);continue}let q=m;q&&(Pt==="flow"?(fe(q),mt=q):(((_o=q.content)!=null?_o:"")===""&&typeof E.text=="string"&&(q.content=E.text),q.streaming=!1,c(q)),m=null),M=null,A=""}else if(tt==="step_complete"){let V=E.stepType,q=E.executionType;if(V==="tool"||q==="context")continue;if(E.success===!1){let G=E.error,me=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((pn=G.message)!=null?pn:"Step failed"):"Step failed";r({type:"error",error:new Error(me)});let Fe=m;Fe&&Fe.streaming&&(Fe.streaming=!1,c(Fe)),r({type:"status",status:"idle"});continue}{let G=mt;mt=null;let me=E.stopReason,Fe=(Mo=E.result)==null?void 0:Mo.response;if(G)me&&(G.stopReason=me),Fe!=null?Lt(G,Fe):G.streaming!==!1&&(Z.delete(G.id),se.delete(G.id),G.streaming=!1,c(G));else{let Je=Fe!=null&&Fe!=="";if(Je||me){let Tt=$e();me&&(Tt.stopReason=me),Je?fe(Tt,Fe):(Tt.streaming=!1,c(Tt))}}continue}}else if(tt==="execution_start")Pt=E.kind==="flow"?"flow":"agent",Pt==="agent"&&(ce={executionId:E.executionId,agentId:(zr=E.agentId)!=null?zr:"virtual",agentName:(ge=E.agentName)!=null?ge:"",status:"running",currentIteration:0,maxTurns:(it=E.maxTurns)!=null?it:1,startedAt:oe(E.startedAt)});else if(tt==="turn_start"){let V=typeof E.iteration=="number"?E.iteration:Ve;if(V!==Ve){if(ce&&(ce.currentIteration=V),Rt==="separate"&&V>1){let q=m;q&&(q.streaming=!1,c(q),xr.set(V-1,q),m=null)}Ve=V}we=typeof E.id=="string"?E.id:null,x=null}else if(tt==="tool_input_delta"){let V=(Xt=E.toolCallId)!=null?Xt:P.lastId;if(V){let q=T.get(V);q!=null&&q.toolCall&&(q.toolCall.chunks=(sr=q.toolCall.chunks)!=null?sr:[],q.toolCall.chunks.push((To=E.delta)!=null?To:""),c(q))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let V=E.stopReason,q=m!=null?m:x;if(V&&q!==null){let G=E.id;(!G||((Ua=q.agentMetadata)==null?void 0:Ua.turnId)===G)&&(q.stopReason=V,c(q))}we===E.id&&(we=null)}else if(tt==="media_start"){let V=String(E.id);ve.set(V,{mediaType:typeof E.mediaType=="string"?E.mediaType:void 0,role:typeof E.role=="string"?E.role:void 0,toolCallId:E.toolCallId,parts:[]})}else if(tt==="media_delta"){let V=ve.get(String(E.id));V&&typeof E.delta=="string"&&V.parts.push(E.delta)}else if(tt==="media_complete"){let V=String(E.id),q=ve.get(V);ve.delete(V);let G=(Wn=(Uo=typeof E.mediaType=="string"?E.mediaType:void 0)!=null?Uo:q==null?void 0:q.mediaType)!=null?Wn:"application/octet-stream",me=typeof E.data=="string"?E.data:void 0,Fe=typeof E.url=="string"?E.url:q&&q.parts.length>0?q.parts.join(""):void 0,Je=null;if(me)Je={type:"media",data:me,mediaType:G};else if(Fe){let Gr=G.toLowerCase();Je={type:Gr==="image"||Gr.startsWith("image/")?"image-url":"file-url",url:Fe,mediaType:G}}let Tt=(Eo=E.toolCallId)!=null?Eo:q==null?void 0:q.toolCallId,zo=Je?[Je]:[],Dr=[];for(let Gr of zo){if(!Gr||typeof Gr!="object")continue;let mr=Gr,un=typeof mr.type=="string"?mr.type:void 0,$o=typeof mr.mediaType=="string"?mr.mediaType.toLowerCase():"",gr=null,Fr="";if(un==="media"){let Kr=typeof mr.data=="string"?mr.data:void 0;if(!Kr)continue;Fr=$o.length>0?$o:"application/octet-stream",gr=`data:${Fr};base64,${Kr}`}else if(un==="image-url"){let Kr=typeof mr.url=="string"?mr.url:void 0;if(!Kr)continue;Fr=$o,gr=Kr}else if(un==="file-url"){let Kr=typeof mr.url=="string"?mr.url:void 0;if(!Kr)continue;Fr=$o,gr=Kr}else continue;if(gr)if(un==="image-url"||Fr.startsWith("image/"))Dr.push({type:"image",image:gr,...Fr.includes("/")?{mimeType:Fr}:{}});else if(Fr.startsWith("audio/"))Dr.push({type:"audio",audio:gr,mimeType:Fr});else if(Fr.startsWith("video/"))Dr.push({type:"video",video:gr,mimeType:Fr});else{let Kr=Fr||"application/octet-stream";Dr.push({type:"file",data:gr,mimeType:Kr,filename:zy(Kr)})}}if(Dr.length>0){let Gr=d(),mr=Tt,$o={id:`agent-media-${typeof mr=="string"&&mr.length>0?`${mr}-${Gr}`:String(Gr)}`,role:"assistant",content:"",contentParts:Dr,createdAt:new Date().toISOString(),streaming:!1,sequence:Gr,agentMetadata:{executionId:E.executionId,iteration:typeof E.iteration=="number"?E.iteration:Ve}};c($o);let gr=m;gr&&(gr.streaming=!1,c(gr)),m=null,C.current=null}}else if(tt==="execution_complete"){let V=(_=E.kind)!=null?_:Pt;V==="agent"&&ce&&(ce.status=E.success?"complete":"error",ce.completedAt=oe(E.completedAt),ce.stopReason=E.stopReason);let q=m;q&&(V==="flow"&&q.streaming!==!1?fe(q):(q.streaming=!1,c(q)),m=null),M=null,A="",mt=null,r({type:"status",status:"idle"})}else if(tt==="execution_error"){let V=typeof E.error=="string"?E.error:(ko=(sa=E.error)==null?void 0:sa.message)!=null?ko:"Execution error";r({type:"error",error:new Error(V)})}else if(tt!=="ping"){if(tt==="approval_start"){let V=(Lo=E.approvalId)!=null?Lo:`approval-${d()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:V,status:"pending",agentId:(qo=ce==null?void 0:ce.agentId)!=null?qo:"virtual",executionId:(fo=(Po=E.executionId)!=null?Po:ce==null?void 0:ce.executionId)!=null?fo:"",toolName:(ia=E.toolName)!=null?ia:"",toolType:E.toolType,description:($r=E.description)!=null?$r:`Execute ${(Is=E.toolName)!=null?Is:"tool"}`,...typeof E.reason=="string"&&E.reason?{reason:E.reason}:{},parameters:E.parameters}};c(q)}else if(tt==="step_await"&&E.awaitReason==="approval_required"){let V=(jr=E.approvalId)!=null?jr:`approval-${d()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:V,status:"pending",agentId:(mo=ce==null?void 0:ce.agentId)!=null?mo:"virtual",executionId:(Hn=(go=E.executionId)!=null?go:ce==null?void 0:ce.executionId)!=null?Hn:"",toolName:(Vo=E.toolName)!=null?Vo:"",toolType:E.toolType,description:(Ro=E.description)!=null?Ro:`Execute ${(br=E.toolName)!=null?br:"tool"}`,...typeof E.reason=="string"&&E.reason?{reason:E.reason}:{},parameters:E.parameters}};c(q)}else if(tt==="approval_complete"){let V=E.approvalId;if(V){let G={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:V,status:(la=E.decision)!=null?la:"approved",agentId:(Bn=ce==null?void 0:ce.agentId)!=null?Bn:"virtual",executionId:(Ws=(da=E.executionId)!=null?da:ce==null?void 0:ce.executionId)!=null?Ws:"",toolName:(pa=E.toolName)!=null?pa:"",description:(Hs=E.description)!=null?Hs:"",resolvedAt:Date.now()}};c(G)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let V=E.artifactType,q=String(E.id),G=typeof E.title=="string"?E.title:void 0;if(r({type:"artifact_start",id:q,artifactType:V,title:G,component:typeof E.component=="string"?E.component:void 0}),pe.set(q,{markdown:"",title:G}),!Q.has(q)){Q.add(q);let me={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:V,status:"streaming"}})};ae.set(q,me),c(me)}}else if(tt==="artifact_delta"){let V=String(E.id),q=typeof E.delta=="string"?E.delta:String((ca=E.delta)!=null?ca:"");r({type:"artifact_delta",id:V,artDelta:q});let G=pe.get(V);G&&(G.markdown+=q)}else if(tt==="artifact_update"){let V=E.props&&typeof E.props=="object"&&!Array.isArray(E.props)?E.props:{};r({type:"artifact_update",id:String(E.id),props:V,component:typeof E.component=="string"?E.component:void 0})}else if(tt==="artifact_complete"){let V=String(E.id);r({type:"artifact_complete",id:V});let q=ae.get(V);if(q){q.streaming=!1;try{let G=JSON.parse((ft=q.rawContent)!=null?ft:"{}");if(G.props){G.props.status="complete";let me=pe.get(V);me!=null&&me.markdown&&(G.props.markdown=me.markdown)}q.rawContent=JSON.stringify(G)}catch{}pe.delete(V),c(q),ae.delete(V)}}}else if(tt==="transcript_insert"){let V=E.message;if(!V||typeof V!="object")continue;let q=String((qa=V.id)!=null?qa:`msg-${d()}`),G=V.role,Fe={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:d()};if(c(Fe),Fe.rawContent)try{let Je=JSON.parse(Fe.rawContent),Tt=(ao=Je==null?void 0:Je.props)==null?void 0:ao.artifactId;typeof Tt=="string"&&Q.add(Tt)}catch{}m=null,C.current=null,Z.delete(q),se.delete(q)}else if(tt==="error"){if(E.recoverable===!1&&E.error!=null&&E.error!==""){let V=typeof E.error=="string"?E.error:((Br=E.error)==null?void 0:Br.message)!=null?String(E.error.message):"Execution error";r({type:"error",error:new Error(V)});let q=m;q&&q.streaming&&(q.streaming=!1,c(q)),r({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let V=null;if(E.error instanceof Error)V=E.error;else if(tt==="dispatch_error"){let q=(Bs=E.message)!=null?Bs:E.error;q!=null&&q!==""&&(V=new Error(String(q)))}else{let q=E.error;typeof q=="string"&&q!==""?V=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(V=new Error(String((Ds=q.message)!=null?Ds:q)))}if(V){r({type:"error",error:V});let q=m;q&&q.streaming&&(q.streaming=!1,c(q)),r({type:"status",status:"idle"})}}}}}X.length=0};;){let{done:H,value:de}=await n.read();if(H)break;s+=a.decode(de,{stream:!0});let Te=s.split(`
12
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ms=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ii=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},li=()=>{var t;let e=ob();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},di=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,Zo.parse)(r,Zo.STR|Zo.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?oi(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=oi(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Wg=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?oi(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?oi(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,Zo.parse)(a,Zo.STR|Zo.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},ci=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Bg="4.2.0";var Jn=Bg;var ab="https://api.runtype.com/v1/dispatch",pi="https://api.runtype.com";function sb(e){var a,s;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Ol=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 ib(e){switch(e){case"json":return di;case"regex-json":return li;case"xml":return ci;default:return ii}}var Dg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function lb(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=Dg(r);if(!Dg(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ms(e);return ms(t)!==null&&s===null?t:e}var Qn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;this.apiUrl=(r=t.apiUrl)!=null?r:ab,this.headers={"Content-Type":"application/json","X-Persona-Version":Jn,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:ib(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ea(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||pi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;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 o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let t=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn},body:JSON.stringify(r)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let n=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(n.sessionId),{sessionId:n.sessionId,expiresAt:new Date(n.expiresAt),flow:n.flow,config:{welcomeMessage:n.config.welcomeMessage,placeholder:n.config.placeholder,theme:n.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||pi}/v1/client/feedback`}async sendFeedback(t){var s,i;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 n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,f={sessionId:c.sessionId,messages:t.messages.filter(Ol).map(y=>{var S,v,M;return{id:y.id,role:y.role,content:(M=(v=(S=y.contentParts)!=null?S:y.llmContent)!=null?v:y.rawContent)!=null?M:y.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}},u=l.clientTools,m=!!(u&&u.length>0),x=m?hg(u):void 0,b=this.clientToolsFingerprintSessionId===c.sessionId,L=m&&b&&this.lastSentClientToolsFingerprint===x,E=!1,A=null,T;for(let y=0;;y++){let v={...f,...m&&(E||!L)&&u?{clientTools:u}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn},body:JSON.stringify(v),signal:o.signal}),T.status===409&&y===0&&m){let M=await T.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=M!=null?M:{error:"Chat request failed"}}break}if(!T.ok){let y=A!=null?A:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(T.status===429){let v=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let S=new Error(y.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!T.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(T.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let l=c instanceof Error?c:new Error(String(c));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||pi}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var l,p;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||pi}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var a,s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Ol).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,c)=>{let l=new Date(i.createdAt).getTime(),p=new Date(c.createdAt).getTime();return l-p}).map(i=>{var c,l,p;return{role:i.role,content:(p=(l=(c=i.contentParts)!=null?c:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),o={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},n=[...ps(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async c=>{try{let l=await c({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(o.context=i)}return o}async buildPayload(t){var a,s;let o={messages:t.slice().filter(Ol).sort((i,c)=>{let l=new Date(i.createdAt).getTime(),p=new Date(c.createdAt).getTime();return l-p}).map(i=>{var c,l,p;return{role:i.role,content:(p=(l=(c=i.contentParts)!=null?c:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},n=[...ps(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async c=>{try{let l=await c({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(o.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...o},config:this.config});if(i&&typeof i=="object"){let c=i;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return o}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=f,n(f),f},l=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var fr,Dt,Yt,Uo;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,l=()=>i+c++,p=F=>{let j=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,He=F.tools?F.tools.map(Ue=>({...Ue,chunks:Ue.chunks?[...Ue.chunks]:void 0})):void 0;return{...F,reasoning:j,toolCall:de,tools:He}},f=F=>{if(F.role!=="assistant"||F.variant)return!0;let j=Array.isArray(F.contentParts)&&F.contentParts.length>0,de=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||j||de||!!F.stopReason},u=F=>{f(F)&&r({type:"message",message:p(F)})},m=null,x=null,b={current:null},L={current:null},E=null,A="",T=new Map,y=new Map,S=new Map,v=new Map,M=new Map,I={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},R=F=>{if(F==null)return null;try{return String(F)}catch{return null}},D=F=>{var j,de,He,Ue,We;return R((We=(Ue=(He=(de=(j=F.stepId)!=null?j:F.step_id)!=null?de:F.step)!=null?He:F.parentId)!=null?Ue:F.flowStepId)!=null?We:F.flow_step_id)},O=F=>{var j,de,He,Ue,We,Ee,st;return R((st=(Ee=(We=(Ue=(He=(de=(j=F.callId)!=null?j:F.call_id)!=null?de:F.requestId)!=null?He:F.request_id)!=null?Ue:F.toolCallId)!=null?We:F.tool_call_id)!=null?Ee:F.stepId)!=null?st:F.step_id)},Q=o,me=!1,ce=()=>{if(m)return m;let F,j=E;return!me&&Q?(F=Q,me=!0):Q&&j?F=`${Q}_${j}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(m),m},ee=(F,j)=>{I.lastId=j,F&&I.byStep.set(F,j)},Ce=(F,j)=>{var We;let de=(We=F.reasoningId)!=null?We:F.id,He=D(F);if(de){let Ee=String(de);return ee(He,Ee),Ee}if(He){let Ee=I.byStep.get(He);if(Ee)return I.lastId=Ee,Ee}if(I.lastId&&!j)return I.lastId;if(!j)return null;let Ue=`reason-${l()}`;return ee(He,Ue),Ue},Ie=F=>{let j=v.get(F);if(j)return j;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 v.set(F,de),u(de),de},le=(F,j)=>{H.lastId=j,F&&H.byCall.set(F,j)},ve=new Set,ae=new Map,se=new Set,pe=new Map,ze=F=>{if(!F)return!1;let j=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},_e=(F,j)=>{var We;let de=(We=F.toolId)!=null?We:F.id,He=O(F);if(de){let Ee=String(de);return le(He,Ee),Ee}if(He){let Ee=H.byCall.get(He);if(Ee)return H.lastId=Ee,Ee}if(H.lastId&&!j)return H.lastId;if(!j)return null;let Ue=`tool-${l()}`;return le(He,Ue),Ue},K=F=>{let j=M.get(F);if(j)return j;let de={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return M.set(F,de),u(de),de},J=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let j=Number(F);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let de=Date.parse(F);if(!Number.isNaN(de))return de}return Date.now()},Se=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},Y=new Map,ie=new Map,Re=new Map,rt=(F,j,de)=>{var st;let He=Re.get(F);He||(He=[],Re.set(F,He));let Ue=0,We=He.length;for(;Ue<We;){let Pt=Ue+We>>>1;He[Pt].seq<j?Ue=Pt+1:We=Pt}((st=He[Ue])==null?void 0:st.seq)===j?He[Ue]={seq:j,text:de}:He.splice(Ue,0,{seq:j,text:de});let Ee="";for(let Pt=0;Pt<He.length;Pt++)Ee+=He[Pt].text;return Ee},bt=(F,j)=>{let de=Se(j),He=ie.get(F.id),Ue=lb(He,de);F.rawContent=Ue;let We=Y.get(F.id),Ee=W=>{var Me;let ne=(Me=F.content)!=null?Me:"";W.trim()!==""&&(ne.trim().length===0||W.startsWith(ne)||W.trimStart().startsWith(ne.trim()))&&(F.content=W)},st=()=>{var W;if(We){let ne=(W=We.close)==null?void 0:W.call(We);ne instanceof Promise&&ne.catch(()=>{})}Y.delete(F.id),ie.delete(F.id),F.streaming=!1,u(F)};if(!We){Ee(de),st();return}let Pt=ms(Ue);if(Pt!==null&&Pt.trim()!==""){Ee(Pt),st();return}let gt=W=>{var Mt;let ne=typeof W=="string"?W:(Mt=W==null?void 0:W.text)!=null?Mt:null;if(ne!==null&&ne.trim()!=="")return ne;let Me=We.getExtractedText();return Me!==null&&Me.trim()!==""?Me:de},Rt;try{Rt=We.processChunk(Ue)}catch{Ee(de),st();return}if(Rt instanceof Promise){Rt.then(W=>{Ee(gt(W)),st()}).catch(()=>{Ee(de),st()});return}Ee(gt(Rt)),st()},qt=null,Gt=(F,j,de,He)=>{var Pt;F.rawContent=j,Y.has(F.id)||Y.set(F.id,this.createStreamParser());let Ue=Y.get(F.id),We=j.trim().startsWith("{")||j.trim().startsWith("[");if(We&&ie.set(F.id,j),Ue.__isPlainTextParser===!0){F.content=He!==void 0?j:F.content+de,ie.delete(F.id),Y.delete(F.id),F.rawContent=void 0,u(F);return}let st=Ue.processChunk(j);if(st instanceof Promise)st.then(gt=>{var W;let Rt=typeof gt=="string"?gt:(W=gt==null?void 0:gt.text)!=null?W:null;Rt!==null&&Rt.trim()!==""?(F.content=Rt,u(F)):!We&&!j.trim().startsWith("<")&&(F.content=He!==void 0?j:F.content+de,ie.delete(F.id),Y.delete(F.id),F.rawContent=void 0,u(F))}).catch(()=>{F.content=He!==void 0?j:F.content+de,ie.delete(F.id),Y.delete(F.id),F.rawContent=void 0,u(F)});else{let gt=typeof st=="string"?st:(Pt=st==null?void 0:st.text)!=null?Pt:null;gt!==null&&gt.trim()!==""?(F.content=gt,u(F)):!We&&!j.trim().startsWith("<")&&(F.content=He!==void 0?j:F.content+de,ie.delete(F.id),Y.delete(F.id),F.rawContent=void 0,u(F))}},at=(F,j)=>{var Pt,gt;let de=j!=null?j:F.content;if(de==null||de===""){F.streaming=!1,u(F);return}let He=ie.get(F.id),Ue=He!=null?He:Se(de);F.rawContent=Ue;let We=Y.get(F.id),Ee=null,st=!1;if(We&&(Ee=We.getExtractedText(),Ee===null&&(Ee=ms(Ue)),Ee===null)){let Rt=We.processChunk(Ue);Rt instanceof Promise?(st=!0,Rt.then(W=>{var Me;let ne=typeof W=="string"?W:(Me=W==null?void 0:W.text)!=null?Me:null;ne!==null&&(F.content=ne,F.streaming=!1,Y.delete(F.id),ie.delete(F.id),u(F))}).catch(()=>{})):Ee=typeof Rt=="string"?Rt:(Pt=Rt==null?void 0:Rt.text)!=null?Pt:null}if(!st){Ee!==null&&Ee.trim()!==""?F.content=Ee:ie.has(F.id)||(F.content=Se(de));let Rt=Y.get(F.id);if(Rt){let W=(gt=Rt.close)==null?void 0:gt.call(Rt);W instanceof Promise&&W.catch(()=>{}),Y.delete(F.id)}ie.delete(F.id),F.streaming=!1,u(F)}},Ne=(F,j,de)=>{let He=y.get(F);if(He)return He;let Ue={id:`nested-${j}-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...de?{variant:de}:{},...de==="reasoning"?{reasoning:{id:F,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:j}};return y.set(F,Ue),u(Ue),Ue},G=[],je,$e=new Map,ye=0,we="agent",Qe=null,Xe=null,Ae=new Map,Oe=(fr=this.config.iterationDisplay)!=null?fr:"separate";for(je=()=>{var F,j,de,He,Ue,We,Ee,st,Pt,gt,Rt,W,ne,Me,Mt,Ye,Vt,br,xt,yt,It,vt,mr,_t,Ur,Er,kr,Cr,Lr,fo,Ct,Ao,Mo,qo,mo,ct,Hn,To,Wn,Fr,ca,nn,Vo,an,sn,Bn,Dn,ln,ht,qr,Vr,Pr,wt,ro,oo,zr,dn,zo,cn,$r,Ht,Rr,no,pn,$o,un,he,Nr,Eo,pt,ir,lr,ko,ja,jo,Fn,Lo,q,pa,Po,Ro,Go,Io,go,ua,Fs,jr,Gr,ho,xo,Nn,Ko,wr,Ho,fa,On,ma,Ns,ga,Os,ha,dt,Ga,ao,Or;for(let xa=0;xa<G.length;xa++){let ot=G[xa].payloadType,k=G[xa].payload;if(ot==="reasoning_start"){let z=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if(z&&V){T.set(z,V),Ne(z,V,"reasoning");continue}let X=(F=Ce(k,!0))!=null?F:`reason-${l()}`,ge=Ie(X);ge.reasoning=(j=ge.reasoning)!=null?j:{id:X,status:"streaming",chunks:[]},ge.reasoning.startedAt=(He=ge.reasoning.startedAt)!=null?He:J((de=k.startedAt)!=null?de:k.timestamp),ge.reasoning.completedAt=void 0,ge.reasoning.durationMs=void 0,(k.scope==="loop"||k.scope==="turn")&&(ge.reasoning.scope=k.scope),ge.streaming=!0,ge.reasoning.status="streaming",u(ge)}else if(ot==="reasoning_delta"){let z=typeof k.id=="string"?k.id:null;if(z&&T.has(z)&&y.has(z)){let De=y.get(z),ut=(Ee=(We=(Ue=k.reasoningText)!=null?Ue:k.text)!=null?We:k.delta)!=null?Ee:"";ut&&k.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(ut)),u(De));continue}let V=(Pt=(st=Ce(k,!1))!=null?st:Ce(k,!0))!=null?Pt:`reason-${l()}`,X=Ie(V);X.reasoning=(gt=X.reasoning)!=null?gt:{id:V,status:"streaming",chunks:[]},X.reasoning.startedAt=(W=X.reasoning.startedAt)!=null?W:J((Rt=k.startedAt)!=null?Rt:k.timestamp);let ge=(Mt=(Me=(ne=k.reasoningText)!=null?ne:k.text)!=null?Me:k.delta)!=null?Mt:"";if(ge&&k.hidden!==!0){let De=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(De!==void 0){let ut=rt(V,De,String(ge));X.reasoning.chunks=[ut]}else X.reasoning.chunks.push(String(ge))}if(X.reasoning.status=k.done?"complete":"streaming",k.done){X.reasoning.completedAt=J((Ye=k.completedAt)!=null?Ye:k.timestamp);let De=(Vt=X.reasoning.startedAt)!=null?Vt:Date.now();X.reasoning.durationMs=Math.max(0,((br=X.reasoning.completedAt)!=null?br:Date.now())-De)}X.streaming=X.reasoning.status!=="complete",u(X)}else if(ot==="reasoning_complete"){let z=typeof k.id=="string"?k.id:null;if(z&&T.has(z)&&y.has(z)){let ut=y.get(z);if(ut.reasoning){let Lt=typeof k.text=="string"?k.text:"";Lt&&ut.reasoning.chunks.length===0&&ut.reasoning.chunks.push(Lt),ut.reasoning.status="complete",ut.streaming=!1,u(ut)}T.delete(z),y.delete(z);continue}let V=(yt=(xt=Ce(k,!1))!=null?xt:Ce(k,!0))!=null?yt:`reason-${l()}`,X=typeof k.text=="string"?k.text:"";!v.get(V)&&(X||k.scope==="loop")&&Ie(V);let ge=v.get(V);if(ge!=null&&ge.reasoning){(k.scope==="loop"||k.scope==="turn")&&(ge.reasoning.scope=k.scope),X&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(X),ge.reasoning.status="complete",ge.reasoning.completedAt=J((It=k.completedAt)!=null?It:k.timestamp);let ut=(vt=ge.reasoning.startedAt)!=null?vt:Date.now();ge.reasoning.durationMs=Math.max(0,((mr=ge.reasoning.completedAt)!=null?mr:Date.now())-ut),ge.streaming=!1,u(ge)}let De=D(k);De&&I.byStep.delete(De)}else if(ot==="tool_start"){m&&(m.streaming=!1,u(m),m=null),typeof k.iteration=="number"&&(ye=k.iteration);let z=(Ur=(_t=typeof k.toolCallId=="string"?k.toolCallId:void 0)!=null?_t:_e(k,!0))!=null?Ur:`tool-${l()}`,V=(Er=k.toolName)!=null?Er:k.name;if(ze(V)){ve.add(z);continue}le(O(k),z);let X=K(z),ge=(kr=X.toolCall)!=null?kr:{id:z,status:"pending"};ge.name=V!=null?V:ge.name,ge.status="running",k.parameters!==void 0?ge.args=k.parameters:k.args!==void 0&&(ge.args=k.args),ge.startedAt=(Lr=ge.startedAt)!=null?Lr:J((Cr=k.startedAt)!=null?Cr:k.timestamp),ge.completedAt=void 0,ge.durationMs=void 0,X.toolCall=ge,X.streaming=!0,k.executionId&&(X.agentMetadata={executionId:k.executionId,iteration:k.iteration}),u(X)}else if(ot==="tool_output_delta"){let z=(Ct=(fo=_e(k,!1))!=null?fo:_e(k,!0))!=null?Ct:`tool-${l()}`;if(ve.has(z))continue;let V=K(z),X=(Ao=V.toolCall)!=null?Ao:{id:z,status:"running"};X.startedAt=(qo=X.startedAt)!=null?qo:J((Mo=k.startedAt)!=null?Mo:k.timestamp);let ge=(Hn=(ct=(mo=k.text)!=null?mo:k.delta)!=null?ct:k.message)!=null?Hn:"";ge&&(X.chunks=(To=X.chunks)!=null?To:[],X.chunks.push(String(ge))),X.status="running",V.toolCall=X,V.streaming=!0;let De=k.agentContext;(De||k.executionId)&&(V.agentMetadata=(ca=V.agentMetadata)!=null?ca:{executionId:(Wn=De==null?void 0:De.executionId)!=null?Wn:k.executionId,iteration:(Fr=De==null?void 0:De.iteration)!=null?Fr:k.iteration}),u(V)}else if(ot==="tool_complete"){let z=(Vo=(nn=_e(k,!1))!=null?nn:_e(k,!0))!=null?Vo:`tool-${l()}`;if(ve.has(z)){ve.delete(z);continue}let V=K(z),X=(an=V.toolCall)!=null?an:{id:z,status:"running"};X.status="complete",k.result!==void 0&&(X.result=k.result),typeof k.duration=="number"&&(X.duration=k.duration),X.completedAt=J((sn=k.completedAt)!=null?sn:k.timestamp);let ge=(Bn=k.duration)!=null?Bn:k.executionTime;if(typeof ge=="number")X.durationMs=ge;else{let Lt=(Dn=X.startedAt)!=null?Dn:Date.now();X.durationMs=Math.max(0,((ln=X.completedAt)!=null?ln:Date.now())-Lt)}V.toolCall=X,V.streaming=!1;let De=k.agentContext;(De||k.executionId)&&(V.agentMetadata=(Vr=V.agentMetadata)!=null?Vr:{executionId:(ht=De==null?void 0:De.executionId)!=null?ht:k.executionId,iteration:(qr=De==null?void 0:De.iteration)!=null?qr:k.iteration}),u(V);let ut=O(k);ut&&H.byCall.delete(ut)}else if(ot==="await"&&k.toolName){let z=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,V=(Pr=z!=null?z:k.toolId)!=null?Pr:`local-${l()}`,X=K(V),ge=k.toolName,De=k.origin==="webmcp"&&!vn(ge)?`webmcp:${ge}`:ge,ut=vn(De),Lt=(wt=X.toolCall)!=null?wt:{id:V,status:"pending"};Lt.name=De,Lt.args=k.parameters,Lt.status=ut?"running":"complete",Lt.chunks=(ro=Lt.chunks)!=null?ro:[],Lt.startedAt=(dn=Lt.startedAt)!=null?dn:J((zr=(oo=k.startedAt)!=null?oo:k.timestamp)!=null?zr:k.awaitedAt),ut?(Lt.completedAt=void 0,Lt.duration=void 0,Lt.durationMs=void 0):Lt.completedAt=(zo=Lt.completedAt)!=null?zo:Lt.startedAt,X.toolCall=Lt,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:($r=k.executionId)!=null?$r:(cn=X.agentMetadata)==null?void 0:cn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},u(X)}else if(ot==="text_start"){let z=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if(z&&V){T.set(z,V);continue}let X=m;X&&(we==="flow"?(at(X),qt=X):(X.streaming=!1,u(X)),m=null),E=typeof k.id=="string"?k.id:E,A=""}else if(ot==="text_delta"){let z=typeof k.id=="string"?k.id:null,V=z?T.get(z):void 0;if(z&&V){let ge=typeof k.delta=="string"?k.delta:"",De=((Ht=S.get(z))!=null?Ht:"")+ge;if(S.set(z,De),De.trim()==="")continue;let ut=Ne(z,V);ut.agentMetadata={...ut.agentMetadata,executionId:k.executionId,parentToolId:V},Gt(ut,De,ge,void 0);continue}if(E=typeof k.id=="string"?k.id:E,we==="flow"){let ge=typeof k.delta=="string"?k.delta:"";if(A+=ge,A.trim()==="")continue;let De=ce();De.agentMetadata={executionId:k.executionId,iteration:k.iteration},Gt(De,A,ge,void 0),x=De;continue}let X=ce();X.content+=(Rr=k.delta)!=null?Rr:"",X.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:Qe!=null?Qe:void 0,agentName:Xe==null?void 0:Xe.agentName},x=X,u(X)}else if(ot==="text_complete"){let z=typeof k.id=="string"?k.id:null;if(z&&T.has(z)){let X=y.get(z);X&&at(X),T.delete(z),S.delete(z),y.delete(z);continue}let V=m;V&&(we==="flow"?(at(V),qt=V):(((no=V.content)!=null?no:"")===""&&typeof k.text=="string"&&(V.content=k.text),V.streaming=!1,u(V)),m=null),E=null,A=""}else if(ot==="step_complete"){let z=k.stepType,V=k.executionType;if(z==="tool"||V==="context")continue;if(k.success===!1){let X=k.error,ge=typeof X=="string"&&X!==""?X:X!=null&&typeof X=="object"&&"message"in X?String((pn=X.message)!=null?pn:"Step failed"):"Step failed";r({type:"error",error:new Error(ge)});let De=m;De&&De.streaming&&(De.streaming=!1,u(De)),r({type:"status",status:"idle"});continue}{let X=qt;qt=null;let ge=k.stopReason,De=($o=k.result)==null?void 0:$o.response;if(X)ge&&(X.stopReason=ge),De!=null?bt(X,De):X.streaming!==!1&&(Y.delete(X.id),ie.delete(X.id),X.streaming=!1,u(X));else{let ut=De!=null&&De!=="";if(ut||ge){let Lt=ce();ge&&(Lt.stopReason=ge),ut?at(Lt,De):(Lt.streaming=!1,u(Lt))}}continue}}else if(ot==="execution_start")we=k.kind==="flow"?"flow":"agent",we==="agent"&&(Xe={executionId:k.executionId,agentId:(un=k.agentId)!=null?un:"virtual",agentName:(he=k.agentName)!=null?he:"",status:"running",currentIteration:0,maxTurns:(Nr=k.maxTurns)!=null?Nr:1,startedAt:J(k.startedAt)});else if(ot==="turn_start"){let z=typeof k.iteration=="number"?k.iteration:ye;if(z!==ye){if(Xe&&(Xe.currentIteration=z),Oe==="separate"&&z>1){let V=m;V&&(V.streaming=!1,u(V),Ae.set(z-1,V),m=null)}ye=z}Qe=typeof k.id=="string"?k.id:null,x=null}else if(ot==="tool_input_delta"){let z=(Eo=k.toolCallId)!=null?Eo:H.lastId;if(z){let V=M.get(z);V!=null&&V.toolCall&&(V.toolCall.chunks=(pt=V.toolCall.chunks)!=null?pt:[],V.toolCall.chunks.push((ir=k.delta)!=null?ir:""),u(V))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let z=k.stopReason,V=m!=null?m:x;if(z&&V!==null){let X=k.id;(!X||((lr=V.agentMetadata)==null?void 0:lr.turnId)===X)&&(V.stopReason=z,u(V))}Qe===k.id&&(Qe=null)}else if(ot==="media_start"){let z=String(k.id);$e.set(z,{mediaType:typeof k.mediaType=="string"?k.mediaType:void 0,role:typeof k.role=="string"?k.role:void 0,toolCallId:k.toolCallId,parts:[]})}else if(ot==="media_delta"){let z=$e.get(String(k.id));z&&typeof k.delta=="string"&&z.parts.push(k.delta)}else if(ot==="media_complete"){let z=String(k.id),V=$e.get(z);$e.delete(z);let X=(ja=(ko=typeof k.mediaType=="string"?k.mediaType:void 0)!=null?ko:V==null?void 0:V.mediaType)!=null?ja:"application/octet-stream",ge=typeof k.data=="string"?k.data:void 0,De=typeof k.url=="string"?k.url:V&&V.parts.length>0?V.parts.join(""):void 0,ut=null;if(ge)ut={type:"media",data:ge,mediaType:X};else if(De){let gr=X.toLowerCase();ut={type:gr==="image"||gr.startsWith("image/")?"image-url":"file-url",url:De,mediaType:X}}let Lt=(jo=k.toolCallId)!=null?jo:V==null?void 0:V.toolCallId,Kr=ut?[ut]:[],Wo=[];for(let gr of Kr){if(!gr||typeof gr!="object")continue;let Zt=gr,fn=typeof Zt.type=="string"?Zt.type:void 0,mn=typeof Zt.mediaType=="string"?Zt.mediaType.toLowerCase():"",Ir=null,Hr="";if(fn==="media"){let Sr=typeof Zt.data=="string"?Zt.data:void 0;if(!Sr)continue;Hr=mn.length>0?mn:"application/octet-stream",Ir=`data:${Hr};base64,${Sr}`}else if(fn==="image-url"){let Sr=typeof Zt.url=="string"?Zt.url:void 0;if(!Sr)continue;Hr=mn,Ir=Sr}else if(fn==="file-url"){let Sr=typeof Zt.url=="string"?Zt.url:void 0;if(!Sr)continue;Hr=mn,Ir=Sr}else continue;if(Ir)if(fn==="image-url"||Hr.startsWith("image/"))Wo.push({type:"image",image:Ir,...Hr.includes("/")?{mimeType:Hr}:{}});else if(Hr.startsWith("audio/"))Wo.push({type:"audio",audio:Ir,mimeType:Hr});else if(Hr.startsWith("video/"))Wo.push({type:"video",video:Ir,mimeType:Hr});else{let Sr=Hr||"application/octet-stream";Wo.push({type:"file",data:Ir,mimeType:Sr,filename:sb(Sr)})}}if(Wo.length>0){let gr=l(),Zt=Lt,mn={id:`agent-media-${typeof Zt=="string"&&Zt.length>0?`${Zt}-${gr}`:String(gr)}`,role:"assistant",content:"",contentParts:Wo,createdAt:new Date().toISOString(),streaming:!1,sequence:gr,agentMetadata:{executionId:k.executionId,iteration:typeof k.iteration=="number"?k.iteration:ye}};u(mn);let Ir=m;Ir&&(Ir.streaming=!1,u(Ir)),m=null,b.current=null}}else if(ot==="execution_complete"){let z=(Fn=k.kind)!=null?Fn:we;z==="agent"&&Xe&&(Xe.status=k.success?"complete":"error",Xe.completedAt=J(k.completedAt),Xe.stopReason=k.stopReason);let V=m;V&&(z==="flow"&&V.streaming!==!1?at(V):(V.streaming=!1,u(V)),m=null),E=null,A="",qt=null,r({type:"status",status:"idle"})}else if(ot==="execution_error"){let z=typeof k.error=="string"?k.error:(q=(Lo=k.error)==null?void 0:Lo.message)!=null?q:"Execution error";r({type:"error",error:new Error(z)})}else if(ot!=="ping"){if(ot==="approval_start"){let z=(pa=k.approvalId)!=null?pa:`approval-${l()}`,V={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Po=Xe==null?void 0:Xe.agentId)!=null?Po:"virtual",executionId:(Go=(Ro=k.executionId)!=null?Ro:Xe==null?void 0:Xe.executionId)!=null?Go:"",toolName:(Io=k.toolName)!=null?Io:"",toolType:k.toolType,description:(ua=k.description)!=null?ua:`Execute ${(go=k.toolName)!=null?go:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(ot==="step_await"&&k.awaitReason==="approval_required"){let z=(Fs=k.approvalId)!=null?Fs:`approval-${l()}`,V={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(jr=Xe==null?void 0:Xe.agentId)!=null?jr:"virtual",executionId:(ho=(Gr=k.executionId)!=null?Gr:Xe==null?void 0:Xe.executionId)!=null?ho:"",toolName:(xo=k.toolName)!=null?xo:"",toolType:k.toolType,description:(Ko=k.description)!=null?Ko:`Execute ${(Nn=k.toolName)!=null?Nn:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(ot==="approval_complete"){let z=k.approvalId;if(z){let X={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(wr=k.decision)!=null?wr:"approved",agentId:(Ho=Xe==null?void 0:Xe.agentId)!=null?Ho:"virtual",executionId:(On=(fa=k.executionId)!=null?fa:Xe==null?void 0:Xe.executionId)!=null?On:"",toolName:(ma=k.toolName)!=null?ma:"",description:(Ns=k.description)!=null?Ns:"",resolvedAt:Date.now()}};u(X)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let z=k.artifactType,V=String(k.id),X=typeof k.title=="string"?k.title:void 0;if(r({type:"artifact_start",id:V,artifactType:z,title:X,component:typeof k.component=="string"?k.component:void 0}),pe.set(V,{markdown:"",title:X}),!se.has(V)){se.add(V);let ge={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:V,title:X,artifactType:z,status:"streaming"}})};ae.set(V,ge),u(ge)}}else if(ot==="artifact_delta"){let z=String(k.id),V=typeof k.delta=="string"?k.delta:String((ga=k.delta)!=null?ga:"");r({type:"artifact_delta",id:z,artDelta:V});let X=pe.get(z);X&&(X.markdown+=V)}else if(ot==="artifact_update"){let z=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};r({type:"artifact_update",id:String(k.id),props:z,component:typeof k.component=="string"?k.component:void 0})}else if(ot==="artifact_complete"){let z=String(k.id);r({type:"artifact_complete",id:z});let V=ae.get(z);if(V){V.streaming=!1;try{let X=JSON.parse((Os=V.rawContent)!=null?Os:"{}");if(X.props){X.props.status="complete";let ge=pe.get(z);ge!=null&&ge.markdown&&(X.props.markdown=ge.markdown)}V.rawContent=JSON.stringify(X)}catch{}pe.delete(z),u(V),ae.delete(z)}}}else if(ot==="transcript_insert"){let z=k.message;if(!z||typeof z!="object")continue;let V=String((ha=z.id)!=null?ha:`msg-${l()}`),X=z.role,De={id:V,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(u(De),De.rawContent)try{let ut=JSON.parse(De.rawContent),Lt=(dt=ut==null?void 0:ut.props)==null?void 0:dt.artifactId;typeof Lt=="string"&&se.add(Lt)}catch{}m=null,b.current=null,Y.delete(V),ie.delete(V)}else if(ot==="error"){if(k.recoverable===!1&&k.error!=null&&k.error!==""){let z=typeof k.error=="string"?k.error:((Ga=k.error)==null?void 0:Ga.message)!=null?String(k.error.message):"Execution error";r({type:"error",error:new Error(z)});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let z=null;if(k.error instanceof Error)z=k.error;else if(ot==="dispatch_error"){let V=(ao=k.message)!=null?ao:k.error;V!=null&&V!==""&&(z=new Error(String(V)))}else{let V=k.error;typeof V=="string"&&V!==""?z=new Error(V):V!=null&&typeof V=="object"&&"message"in V&&(z=new Error(String((Or=V.message)!=null?Or:V)))}if(z){r({type:"error",error:z});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}}}}G.length=0};;){let{done:F,value:j}=await n.read();if(F)break;s+=a.decode(j,{stream:!0});let de=s.split(`
11
13
 
12
- `);s=(Co=Te.pop())!=null?Co:"";for(let Se of Te){let Le=Se.split(`
13
- `),Ze="message",Ke="";for(let z of Le)z.startsWith("event:")?Ze=z.replace("event:","").trim():z.startsWith("data:")&&(Ke+=z.replace("data:","").trim());if(!Ke)continue;let dt;try{dt=JSON.parse(Ke)}catch(z){r({type:"error",error:z instanceof Error?z:new Error("Failed to parse chat stream payload")});continue}let It=Ze!=="message"?Ze:(yr=dt.type)!=null?yr:"message";if((ze=this.onSSEEvent)==null||ze.call(this,It,dt),this.parseSSEEvent){C.current=m;let z=await this.handleCustomSSEEvent(dt,r,C,c,d,R);if(C.current&&C.current!==m&&(m=C.current),z)continue}X.push({payloadType:It,payload:dt}),ie()}}ie()}};function Pg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ta(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Xn(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var di="[Image]";function Rg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ig(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Wg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Hg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ps(e){return{type:"text",text:e}}function Bg(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 Dg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Fg(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Ng=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Gy=["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"],Yo=[...Ng,...Gy];function Ky(e){return Ng.includes(e)||e.startsWith("image/")}function pi(e){return Ky(e.type)}async function Og(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;pi(e)?t({type:"image",image:n,mimeType:e.type,alt:e.name}):t({type:"file",data:n,mimeType:e.type,filename:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function _g(e,t=Yo,r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Xy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Ug(e,t){let r=Xy(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]||r||"FILE"}var ci=class{constructor(t=24e3,r={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var n;this.sampleRate=t;let o=Math.max(0,(n=r.prebufferMs)!=null?n:0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let o=r.AudioContext||r.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let n=new Uint8Array(this.remainder.length+t.length);n.set(this.remainder),n.set(t,this.remainder.length),r=n,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let o=this.pcmToFloat32(r);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),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.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let r of t)this.scheduleSamples(r)}scheduleSamples(t){if(t.length===0)return;let r=this.ensureContext(),o=r.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let n=r.createBufferSource();n.buffer=o,n.connect(r.destination);let a=r.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),n.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(n),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of s)i()}n.onended=()=>{let s=this.activeSources.indexOf(n);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),o=new Float32Array(r),n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<r;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var qg=16e3,Jy=24e3,Qy=4096,Yy=1380533830;function Zy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Yy?new Uint8Array(e,44):new Uint8Array(e)}function eb(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var cs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,p;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let d=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:qg,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){d.getTracks().forEach(C=>C.stop());return}this.mediaStream=d;let u=window.AudioContext||window.webkitAudioContext,g=new u({sampleRate:qg});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let c=(p=this.config)!=null&&p.createPlaybackEngine?await this.config.createPlaybackEngine():new ci(Jy);if(n!==this.callGeneration){c.destroy(),d.getTracks().forEach(C=>C.stop()),g.close().catch(()=>{});return}this.playback=c,c.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${eb(o)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(m,["runtype.bearer",r]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(g,d,x,n))},x.onmessage=C=>this.handleMessage(C,n),x.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=C=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(C.code!==1e3){let R=C.code?` (code ${C.code})`:"";this.emitError(new Error(`Voice connection closed${R}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(d){throw this.cleanup(),this.emitError(d),this.emitStatus("error"),d}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(Qy,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let u=0;u<p.length;u++){let g=Math.max(-1,Math.min(1,p[u]));d[u]=g<0?g*32768:g*32767}o.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,r){if(r!==this.callGeneration||!this.playback)return;let o=Zy(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(r=>r(t))}emitError(t){this.errorCallbacks.forEach(r=>r(t))}emitTranscript(t,r,o){this.transcriptCallbacks.forEach(n=>n(t,r,o))}emitMetrics(t){this.metricsCallbacks.forEach(r=>r(t))}};var Jn=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,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(p=>p[0]).map(p=>p.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(p=>p({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}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 wn(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new cs(e.runtype);case"browser":if(!Jn.isSupported())throw new Error("Browser speech recognition not supported");return new Jn(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let r=typeof t=="function"?t():t;if(!r||typeof r.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return r}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ui(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return wn({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return wn({type:"runtype",runtype:e.runtype});if(Jn.isSupported())return wn({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function us(e){try{return ui(e),!0}catch{return!1}}function Ea(e){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(a=>a.name===o);if(n)return n}return(r=e.find(o=>o.lang.startsWith("en")))!=null?r:e[0]}var Sn=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,r){var s;if(!e.isSupported()){(s=r.onError)==null||s.call(r,new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let i=a.find(p=>p.name===t.voice);i&&(n.voice=i)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):Ea(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var d,u;let p=i.error;p==="canceled"||p==="interrupted"?(d=r.onEnd)==null||d.call(r):(u=r.onError)==null||u.call(r,new Error(p||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Qn=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,r;return(r=(t=this.engine)==null?void 0:t.supportsPause)!=null?r:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,r){var o,n;if(this.activeId===t){if(this.state==="playing"){(o=this.engine)!=null&&o.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(n=this.engine)==null||n.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,r)}async play(t,r){var n;let o=++this.generation;(n=this.engine)==null||n.stop(),this.set(t,"loading");try{if(!this.engine){let a=await this.resolveEngine();if(o!==this.generation)return;if(!a){this.set(null,"idle");return}this.engine=a}this.engine.speak(r,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,r;this.stop(),(r=(t=this.engine)==null?void 0:t.destroy)==null||r.call(t),this.engine=null,this.listeners.clear()}set(t,r){this.activeId=r==="idle"?null:t,this.state=r;for(let o of this.listeners)o(this.activeId,this.state)}};function Nl(e){if(!e)return"";let t=tb(e);return Vg(t!==null?t:e)}function tb(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Vg(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
14
+ `);s=(Dt=de.pop())!=null?Dt:"";for(let He of de){let Ue=He.split(`
15
+ `),We="message",Ee="";for(let gt of Ue)gt.startsWith("event:")?We=gt.replace("event:","").trim():gt.startsWith("data:")&&(Ee+=gt.replace("data:","").trim());if(!Ee)continue;let st;try{st=JSON.parse(Ee)}catch(gt){r({type:"error",error:gt instanceof Error?gt:new Error("Failed to parse chat stream payload")});continue}let Pt=We!=="message"?We:(Yt=st.type)!=null?Yt:"message";if((Uo=this.onSSEEvent)==null||Uo.call(this,Pt,st),this.parseSSEEvent){b.current=m;let gt=await this.handleCustomSSEEvent(st,r,b,u,l,L);if(b.current&&b.current!==m&&(m=b.current),gt)continue}G.push({payloadType:Pt,payload:st}),je()}}je()}};function Fg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ra(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Yn(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ui="[Image]";function Ng(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Og(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function _g(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Ug(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function gs(e){return{type:"text",text:e}}function qg(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 Vg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function zg(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var $g=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],db=["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"],en=[...$g,...db];function cb(e){return $g.includes(e)||e.startsWith("image/")}function fi(e){return cb(e.type)}async function jg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;fi(e)?t({type:"image",image:n,mimeType:e.type,alt:e.name}):t({type:"file",data:n,mimeType:e.type,filename:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Gg(e,t=en,r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function pb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Kg(e,t){let r=pb(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]||r||"FILE"}var mi=class{constructor(t=24e3,r={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var n;this.sampleRate=t;let o=Math.max(0,(n=r.prebufferMs)!=null?n:0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let o=r.AudioContext||r.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let n=new Uint8Array(this.remainder.length+t.length);n.set(this.remainder),n.set(t,this.remainder.length),r=n,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let o=this.pcmToFloat32(r);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),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.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let r of t)this.scheduleSamples(r)}scheduleSamples(t){if(t.length===0)return;let r=this.ensureContext(),o=r.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let n=r.createBufferSource();n.buffer=o,n.connect(r.destination);let a=r.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),n.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(n),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of s)i()}n.onended=()=>{let s=this.activeSources.indexOf(n);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),o=new Float32Array(r),n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<r;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var Xg=16e3,ub=24e3,fb=4096,mb=1380533830;function gb(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===mb?new Uint8Array(e,44):new Uint8Array(e)}function hb(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var hs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Xg,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){l.getTracks().forEach(b=>b.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,f=new p({sampleRate:Xg});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new mi(ub);if(n!==this.callGeneration){u.destroy(),l.getTracks().forEach(b=>b.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${hb(o)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(m,["runtype.bearer",r]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,l,x,n))},x.onmessage=b=>this.handleMessage(b,n),x.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=b=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(b.code!==1e3){let L=b.code?` (code ${b.code})`:"";this.emitError(new Error(`Voice connection closed${L}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(fb,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),l=new Int16Array(c.length);for(let p=0;p<c.length;p++){let f=Math.max(-1,Math.min(1,c[p]));l[p]=f<0?f*32768:f*32767}o.send(l.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,r){if(r!==this.callGeneration||!this.playback)return;let o=gb(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(r=>r(t))}emitError(t){this.errorCallbacks.forEach(r=>r(t))}emitTranscript(t,r,o){this.transcriptCallbacks.forEach(n=>n(t,r,o))}emitMetrics(t){this.metricsCallbacks.forEach(r=>r(t))}};var Zn=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,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(c=>c[0]).map(c=>c.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(c=>c({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}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 Tn(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new hs(e.runtype);case"browser":if(!Zn.isSupported())throw new Error("Browser speech recognition not supported");return new Zn(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let r=typeof t=="function"?t():t;if(!r||typeof r.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return r}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function gi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Tn({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Tn({type:"runtype",runtype:e.runtype});if(Zn.isSupported())return Tn({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 gi(e),!0}catch{return!1}}function Ia(e){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(a=>a.name===o);if(n)return n}return(r=e.find(o=>o.lang.startsWith("en")))!=null?r:e[0]}var En=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,r){var s;if(!e.isSupported()){(s=r.onError)==null||s.call(r,new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let i=a.find(c=>c.name===t.voice);i&&(n.voice=i)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):Ia(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var l,p;let c=i.error;c==="canceled"||c==="interrupted"?(l=r.onEnd)==null||l.call(r):(p=r.onError)==null||p.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var ea=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,r;return(r=(t=this.engine)==null?void 0:t.supportsPause)!=null?r:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,r){var o,n;if(this.activeId===t){if(this.state==="playing"){(o=this.engine)!=null&&o.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(n=this.engine)==null||n.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,r)}async play(t,r){var n;let o=++this.generation;(n=this.engine)==null||n.stop(),this.set(t,"loading");try{if(!this.engine){let a=await this.resolveEngine();if(o!==this.generation)return;if(!a){this.set(null,"idle");return}this.engine=a}this.engine.speak(r,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,r;this.stop(),(r=(t=this.engine)==null?void 0:t.destroy)==null||r.call(t),this.engine=null,this.listeners.clear()}set(t,r){this.activeId=r==="idle"?null:t,this.state=r;for(let o of this.listeners)o(this.activeId,this.state)}};function _l(e){if(!e)return"";let t=xb(e);return Jg(t!==null?t:e)}function xb(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Jg(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
14
16
  `),t=t.replace(/\n{2,}/g,`
15
- `),t.trim()}var Ol=null,zg=e=>{Ol=e},_l=()=>Ol?Ol():import("./runtype-tts-entry");var rb=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function ob(e,t){return rb.some(r=>e[r]!==t[r])}function $g(e,t){let r=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(r);let o="Sorry: 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 r.message?`${o}
17
+ `),t.trim()}var Ul=null,Qg=e=>{Ul=e},ql=()=>Ul?Ul():import("./runtype-tts-entry");var yb=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function bb(e,t){return yb.some(r=>e[r]!==t[r])}function Yg(e,t){let r=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(r);let o="Sorry: 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 r.message?`${o}
16
18
 
17
- _Details: ${r.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]}),jg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Gg=e=>xn(e)||e===bo,ka=class{constructor(t={},r){this.config=t;this.callbacks=r;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.readAloud=new Qn(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,p,d,u,g;if(t.type==="message"){this.upsertMessage(t.message);let c=t.message.toolCall,m=!!(c!=null&&c.name)&&(xn(c.name)||c.name===bo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.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:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let c=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((p=this.agentExecution)==null?void 0:p.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":c||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((d=this.agentExecution)==null?void 0:d.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Kn(t),this.wireDefaultWebMcpConfirm();for(let a of(n=t.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,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),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var n,a,s,i,p;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let r=(n=t.host)!=null?n:this.config.apiUrl,o=(p=t.agentId)!=null?p:(i=(s=(a=this.config.voiceRecognition)==null?void 0:a.provider)==null?void 0:s.runtype)==null?void 0:i.agentId;!r||!o||!this.config.clientToken||_l().catch(()=>{})}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 us((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,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=Sn.isSupported()?new Sn({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let p=(o=t.host)!=null?o:this.config.apiUrl,d=(i=t.agentId)!=null?i:(s=(a=(n=this.config.voiceRecognition)==null?void 0:n.provider)==null?void 0:a.runtype)==null?void 0:s.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(p&&d&&u)return _l().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:m})=>{let x=new c({host:p,agentId:d,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&r?new m(x,r,{onFallback:C=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${C.message}`)}):x});if(g&&r)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),r}return r}setupVoice(t){var r,o;try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=wn(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,p,d)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:p,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:p,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:p,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var p,d;(d=(p=this.config.voiceRecognition)==null?void 0:p.onMetrics)==null||d.call(p,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var p,d;this.voiceStatus=i,this.voiceActive=i==="listening",(d=(p=this.callbacks).onVoiceStatusChanged)==null||d.call(p,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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 r,o,n,a,s,i,p,d,u,g;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:(a=(n=t.runtype)==null?void 0:n.clientToken)!=null?a:this.config.clientToken,host:(i=(s=t.runtype)==null?void 0:s.host)!=null?i:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(d=t.runtype)==null?void 0:d.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((u=t.browser)==null?void 0:u.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(r=(t=this.callbacks).onError)==null||r.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}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,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r={...this.config,...t};if(!ob(this.config,r)){this.config=r,this.client.updateConfig(r);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=r,this.client=new Kn(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:p,streaming:d=!1,voiceProcessing:u,rawContent:g}=t,m={id:s!=null?s:r==="user"?Ta():r==="assistant"?Xn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:d,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};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 r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:p,createdAt:d,sequence:u,streaming:g=!1,voiceProcessing:c,rawContent:m}=o,C={id:p!=null?p:n==="user"?Ta():n==="assistant"?Xn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:d!=null?d:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...c!==void 0&&{voiceProcessing:c},...m!==void 0&&{rawContent:m}};r.push(C)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:p}=t,d={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async sendMessage(t,r){var d,u,g,c,m;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(d=this.abortController)==null||d.abort(),this.abortWebMcpResolves();let n=Ta(),a=Xn(),s={id:n,role:"user",content:o||di,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let p=[...this.messages];try{await this.client.dispatch({messages:p,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let R=$g(x,this.config.errorMessage);if(R){let M={id:a,role:"assistant",createdAt:new Date().toISOString(),content:R,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,x):(m=(c=this.callbacks).onError)==null||m.call(c,new Error(String(x))))}}async continueConversation(){var n,a,s,i,p;if(this.streaming)return;(n=this.abortController)==null||n.abort();let t=Xn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let g=$g(d,this.config.errorMessage);if(g){let c={id:t,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(c)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,d):(p=(i=this.callbacks).onError)==null||p.call(i,new Error(String(d))))}}async connectStream(t,r){var n,a,s;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(n=this.abortController)==null||n.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,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(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var u,g,c,m,x;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(C=>C.id===n),i={id:n,role:"assistant",content:"",createdAt:(u=s==null?void 0:s.createdAt)!=null?u:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let C;if(d?C=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):C=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),C){let R=null;if(C instanceof Response){if(!C.ok){let M=await C.json().catch(()=>null);throw new Error((c=M==null?void 0:M.error)!=null?c:`Approval request failed: ${C.status}`)}R=C.body}else C instanceof ReadableStream&&(R=C);R?await this.connectStream(R,{allowReentry:!0}):(r==="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(C){let R=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,R||(x=(m=this.callbacks).onError)==null||x.call(m,C instanceof Error?C:new Error(String(C)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var u,g,c,m,x,C,R,M,A,L,y,w;let o=this.messages.find(b=>b.id===t.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let n=(g=t.agentMetadata)==null?void 0:g.executionId,a=(c=t.toolCall)==null?void 0:c.name;if(!n||!a){(x=(m=this.callbacks).onError)==null||x.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let b=(C=t.toolCall)==null?void 0:C.args,T=Array.isArray(b==null?void 0:b.questions)?b.questions:[];if(T.length===1){let I=typeof((R=T[0])==null?void 0:R.question)=="string"?T[0].question:"";I&&(s={[I]:r})}}this.markAskUserQuestionResolved(t,s),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,p=(A=t.toolCall)==null?void 0:A.args,d=Array.isArray(p==null?void 0:p.questions)?p.questions:[];if(d.length===0){let b=typeof r=="string"?r:Object.entries(r).map(([T,I])=>`${T}: ${Array.isArray(I)?I.join(", "):I}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:b,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let b=s!=null?s:{};d.forEach((T,I)=>{let P=typeof(T==null?void 0:T.question)=="string"?T.question:"";if(!P)return;let k=b[P],N=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${I}`,role:"assistant",content:P,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${I}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let b=await this.client.resumeFlow(n,{[a]:r});if(!b.ok){let T=await b.json().catch(()=>null);throw new Error((L=T==null?void 0:T.error)!=null?L:`Resume failed: ${b.status}`)}b.body?await this.connectStream(b.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(b){let T=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(w=(y=this.callbacks).onError)==null||w.call(y,b instanceof Error?b:new Error(String(b)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==bo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var p,d,u,g;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async c=>{var w,b,T,I,P,k,N;let m=(w=c.toolCall)==null?void 0:w.name,x=(b=c.toolCall)==null?void 0:b.id;if(!m||!x)return null;let C=`${t}:${x}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(C),o.push(C);let R=this.markWebMcpToolRunning(c),M=(I=(T=c.agentMetadata)==null?void 0:T.webMcpToolCallId)!=null?I:m;if(m===bo)return{dedupeKey:C,resumeKey:M,output:Il(),toolMessage:c,startedAt:R,completedAt:Date.now()};let A=new AbortController;this.webMcpResolveControllers.add(A),n.push(A);let L=this.client.executeWebMcpToolCall(m,(P=c.toolCall)==null?void 0:P.args,A.signal),y;if(!L)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await L}catch(U){let Y=U instanceof Error&&(U.name==="AbortError"||U.message.includes("aborted")||U.message.includes("abort"));return Y||(N=(k=this.callbacks).onError)==null||N.call(k,U instanceof Error?U:new Error(String(U))),this.markWebMcpToolComplete(c,fs(Y?"Aborted by cancel()":jg(U)),R),this.webMcpInflightKeys.delete(C),null}return A.signal.aborted?(this.markWebMcpToolComplete(c,fs("Aborted by cancel()"),R),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:M,output:y,toolMessage:c,startedAt:R,completedAt:Date.now()}})),i=[];try{if(i=s.filter(x=>x!==null),i.length===0)return;let c={};for(let x of i)c[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,c,{signal:a.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((p=x==null?void 0:x.error)!=null?p:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((d=x.toolMessage.toolCall)==null?void 0:d.name)===bo?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,c instanceof Error?c:new Error(String(c)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,fs("Aborted by cancel()"),x.startedAt)}finally{for(let c of o)this.webMcpInflightKeys.delete(c);for(let c of n)this.webMcpResolveControllers.delete(c);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,C,R,M,A,L,y,w,b,T,I,P;let r=(x=t.agentMetadata)==null?void 0:x.executionId,o=(C=t.toolCall)==null?void 0:C.name,n=(R=t.toolCall)==null?void 0:R.id;if(!r){(A=(M=this.callbacks).onError)==null||A.call(M,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let k=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);try{await this.resumeWithToolOutput(r,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(k)}catch(N){(y=(L=this.callbacks).onError)==null||y.call(L,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(k)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===bo,u=(w=t.toolCall)==null?void 0:w.args,g=d?null:this.client.executeWebMcpToolCall(o,u,p),c="execute",m=s;try{let k;if(d?k=Il():g?k=await g:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),p.aborted){this.markWebMcpToolComplete(t,fs("Aborted by cancel()"),s);return}let N=(T=(b=t.agentMetadata)==null?void 0:b.webMcpToolCallId)!=null?T:o;c="resume",await this.resumeWithToolOutput(r,N,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,k,s,m,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(k){let N=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(c==="execute"||N||p.aborted)&&this.markWebMcpToolComplete(t,fs(N||p.aborted?"Aborted by cancel()":jg(k)),s),N||(P=(I=this.callbacks).onError)==null||P.call(I,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,o,n){var s,i;let a=await this.client.resumeFlow(t,{[r]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let p=await a.json().catch(()=>null);throw new Error((s=p==null?void 0:p.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),a.body?await this.connectStream(a.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 n;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}let o={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(n=t.props)!=null?n:{}};return this.artifacts.set(r,o),this.selectedArtifactId=r,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,o;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:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!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 o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let n=Nl(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ea(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=Nl(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var u,g,c,m,x,C,R,M,A,L,y,w,b,T,I;if(a!==o)return n;let s={...n,...r};if(((u=n.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=n.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(c=s.agentMetadata)!=null?c:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let P=n.approval,k=r.approval;s.approval={...P,...k,executionId:k.executionId||P.executionId,toolName:k.toolName||P.toolName,description:k.description||P.description,toolType:(m=k.toolType)!=null?m:P.toolType,reason:(x=k.reason)!=null?x:P.reason,parameters:(C=k.parameters)!=null?C:P.parameters}}let i=(R=r.toolCall)==null?void 0:R.name,p=(M=r.agentMetadata)==null?void 0:M.executionId,d=(A=r.toolCall)==null?void 0:A.id;if(i&&Gg(i)&&p&&d&&((L=r.agentMetadata)==null?void 0:L.awaitingLocalTool)===!0){let P=`${p}:${d}`,k=this.webMcpInflightKeys.has(P),N=this.webMcpResolvedKeys.has(P),U=(y=n.toolCall)==null?void 0:y.name,Y=((w=n.agentMetadata)==null?void 0:w.executionId)===p&&((b=n.toolCall)==null?void 0:b.id)===d&&U!==void 0&&Gg(U)&&((T=n.toolCall)==null?void 0:T.status)==="complete";(k||N||Y)&&(s.agentMetadata={...(I=s.agentMetadata)!=null?I:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),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((r,o)=>{var p,d;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(p=r.sequence)!=null?p:0,i=(d=o.sequence)!=null?d:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var Ul=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var ql=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Vl=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var zl=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var $l=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var jl=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Gl=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var Kl=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var Xl=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var Jl=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var Ql=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Yl=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var Zl=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var ed=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var td=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var rd=[["path",{d:"M20 6 9 17l-5-5"}]];var od=[["path",{d:"m6 9 6 6 6-6"}]];var nd=[["path",{d:"m15 18-6-6 6-6"}]];var ad=[["path",{d:"m9 18 6-6-6-6"}]];var sd=[["path",{d:"m18 15-6-6-6 6"}]];var fi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var mi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var id=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var ld=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var dd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var pd=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var cd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var ud=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var fd=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var gi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var hi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var md=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var gd=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var hd=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var xd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var yd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var bd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var vd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var Cd=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var wd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var Sd=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Ad=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var Md=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var xi=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Td=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Ed=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var kd=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Ld=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Pd=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Rd=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var yi=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Id=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Wd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var Hd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Bd=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var Dd=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var bi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Fd=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Nd=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Od=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var _d=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Ud=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var qd=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Vd=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var zd=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var $d=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var jd=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Gd=[["path",{d:"M5 12h14"}]];var Kd=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var Xd=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var Jd=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var Qd=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Yd=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Zd=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var ep=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var tp=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var rp=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var op=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var np=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var ap=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var sp=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var ip=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var lp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var dp=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var pp=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var cp=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var up=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var fp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var vi=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var mp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var gp=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var hp=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var xp=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Ci=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var yp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var bp=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var vp=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var Cp=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var wp=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var Sp=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Ap=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Mp=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var Tp=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Ep=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var wi=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var kp=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Lp=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Pp=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Rp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Ip=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var Wp=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var Hp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Bp=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var nb={activity:Ul,"arrow-down":ql,"arrow-up":jl,"arrow-up-right":$l,bot:Ql,"chevron-down":od,"chevron-up":sd,"chevron-right":ad,"chevron-left":nd,check:rd,clipboard:ld,"clipboard-copy":id,copy:pd,file:vd,"file-code":xd,"file-spreadsheet":yd,"file-text":bd,"image-plus":Id,loader:Fd,"loader-circle":bi,mic:$d,paperclip:Qd,"refresh-cw":ap,search:lp,send:dp,"shield-alert":up,"shield-check":fp,"shield-x":vi,square:yp,"thumbs-down":Sp,"thumbs-up":Ap,upload:Lp,"volume-2":Rp,x:Hp,user:Pp,mail:Od,phone:tp,calendar:ed,clock:dd,building:Yl,"map-pin":_d,lock:Nd,key:Bd,"credit-card":cd,"at-sign":Gl,hash:kd,globe:Ed,link:Dd,"circle-check":fi,"circle-x":mi,"triangle-alert":wi,info:Hd,ban:Kl,shield:mp,"arrow-left":Vl,"arrow-right":zl,"external-link":gd,ellipsis:hi,"ellipsis-vertical":gi,menu:qd,house:yi,plus:op,minus:Gd,pencil:Zd,trash:Ep,"trash-2":Tp,save:ip,download:fd,share:cp,funnel:xi,settings:pp,"rotate-cw":sp,maximize:Ud,minimize:jd,"shopping-cart":hp,"shopping-bag":gp,package:Jd,truck:kp,tag:wp,gift:Td,receipt:np,wallet:Wp,store:vp,"dollar-sign":ud,percent:ep,play:rp,pause:Yd,"volume-x":Ip,camera:td,image:Wd,film:wd,headphones:Ld,"message-circle":Vd,"message-square":zd,bell:Xl,heart:Pd,star:bp,eye:hd,"eye-off":md,bookmark:Jl,"calendar-days":Zl,history:Rd,timer:Mp,folder:Md,"folder-open":Ad,files:Cd,sparkles:Ci,zap:Bp,sun:Cp,moon:Xd,flag:Sd,monitor:Kd,smartphone:xp},be=(e,t=24,r="currentColor",o=2)=>{let n=nb[e];return n?ab(n,t,r,o):(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 ab(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let p=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([d,u])=>{d!=="stroke"&&p.setAttribute(d,String(u))}),n.appendChild(p)}),n}var Si={allowedTypes:Yo,maxFileSize:10*1024*1024,maxFiles:4};function sb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ib(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 Yn=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Si.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Si.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Si.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:Si.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 r,o,n,a,s,i,p;if(t.length){for(let d of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,d,"count");continue}let u=_g(d,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(n=u.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,d,g);continue}try{let g=await Og(d),c=pi(d)?URL.createObjectURL(d):null,m={id:sb(),file:d,previewUrl:c,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(p=(i=this.config).onAttachmentsChange)==null||p.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(p=>p.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=pi(t.file),o=S("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",r&&t.previewUrl){let s=S("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=S("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=ib(t.file.type),p=be(i,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let d=S("span");d.textContent=Ug(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",s.appendChild(d),o.appendChild(s)}let n=S("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=be("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){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:r})}};var Kg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ms(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];Kg(a)&&Kg(n)?r[o]=ms(a,n):r[o]=n}return r}var Yr="min(440px, calc(100vw - 24px))",Ai="440px",lb={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:Yr,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)"},Ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:lb,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 Xg(e,t){if(!(!e&&!t))return e?t?ms(e,t):e:t}function Mi(e){var t,r,o,n,a,s,i,p,d,u,g,c,m,x,C,R,M,A,L,y,w;return e?{...Ft,...e,theme:Xg(Ft.theme,e.theme),darkTheme:Xg(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(t=Ft.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=Ft.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{...Ft.copy,...e.copy},sendButton:{...Ft.sendButton,...e.sendButton},statusIndicator:{...Ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var ae,Q,pe,ye,ne,K,oe,Ge,Z,se;let b=(ae=Ft.features)==null?void 0:ae.artifacts,T=(Q=e.features)==null?void 0:Q.artifacts,I=(pe=Ft.features)==null?void 0:pe.scrollToBottom,P=(ye=e.features)==null?void 0:ye.scrollToBottom,k=(ne=Ft.features)==null?void 0:ne.scrollBehavior,N=(K=e.features)==null?void 0:K.scrollBehavior,U=(oe=Ft.features)==null?void 0:oe.streamAnimation,Y=(Ge=e.features)==null?void 0:Ge.streamAnimation,he=(Z=Ft.features)==null?void 0:Z.askUserQuestion,$e=(se=e.features)==null?void 0:se.askUserQuestion,Me=b===void 0&&T===void 0?void 0:{...b,...T,layout:{...b==null?void 0:b.layout,...T==null?void 0:T.layout}},Ie=I===void 0&&P===void 0?void 0:{...I,...P},qe=k===void 0&&N===void 0?void 0:{...k,...N},Ee=U===void 0&&Y===void 0?void 0:{...U,...Y},Be=he===void 0&&$e===void 0?void 0:{...he,...$e,styles:{...he==null?void 0:he.styles,...$e==null?void 0:$e.styles}};return{...Ft.features,...e.features,...Ie!==void 0?{scrollToBottom:Ie}:{},...qe!==void 0?{scrollBehavior:qe}:{},...Me!==void 0?{artifacts:Me}:{},...Ee!==void 0?{streamAnimation:Ee}:{},...Be!==void 0?{askUserQuestion:Be}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:Ft.suggestionChips,suggestionChipsConfig:{...Ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ft.layout,...e.layout,header:{...(s=Ft.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(p=Ft.layout)==null?void 0:p.messages,...(d=e.layout)==null?void 0:d.messages,avatar:{...(g=(u=Ft.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(c=e.layout)==null?void 0:c.messages)==null?void 0:m.avatar},timestamp:{...(C=(x=Ft.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(M=(R=e.layout)==null?void 0:R.messages)==null?void 0:M.timestamp}},slots:{...(A=Ft.layout)==null?void 0:A.slots,...(L=e.layout)==null?void 0:L.slots}},markdown:{...Ft.markdown,...e.markdown,options:{...(y=Ft.markdown)==null?void 0:y.options,...(w=e.markdown)==null?void 0:w.options}},messageActions:{...Ft.messageActions,...e.messageActions}}:Ft}var Dp={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"}},Fp={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"}},Np={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:Yr,maxWidth:Ai,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 La(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?La(e,o):o}function Ti(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let p=La(e,s);p!==void 0&&(t[i]={path:i,value:p,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Op(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:r}}function Jg(e,t){let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?r[o]=Jg(a,n):r[o]=n}return r}function db(e,t){return t?Jg(e,t):e}function Pa(e,t={}){var n,a,s,i,p,d,u,g,c,m,x,C,R;let r={palette:Dp,semantic:Fp,components:Np},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(p=e==null?void 0:e.palette)==null?void 0:p.borders},radius:{...r.palette.radius,...(d=e==null?void 0:e.palette)==null?void 0:d.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...r.semantic.colors.interactive,...(c=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:c.interactive},feedback:{...r.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...r.semantic.typography,...(R=e==null?void 0:e.semantic)==null?void 0:R.typography}},components:db(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let M=Op(o);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let M of t.plugins)o=M.transform(o);return o}function Ei(e){var C,R,M,A,L,y,w,b,T,I,P,k,N,U,Y,he,$e,Me,Ie,qe,Ee,Be,ae,Q,pe,ye,ne,K,oe,Ge,Z,se,We,Ct,Lt,mt,Oe,fe,Ye,X,ie,ve,Ve,Pt,we,ce,xr,Rt,ar,Co,yr,ze,H,de,Te,Se,Le,Ze,Ke,dt,It,z,ot,j,le,Ae,xt,Zt,er,fr,Ht,et,Wt,st,Gt,to,Ar,tr,Wr,wo,yt,Or,So,Fo,uo,gt,Ln,Ao,Pn,Hr,aa,rn,No,on,nn,Rn,In,an,vt,_r,Ur,Mr,St,ro,oo,qr,sn,Oo,ln,Vr,Bt,Tr,no,dn,_o,pn,Mo,zr;let t=Ti(e),r={};for(let[ge,it]of Object.entries(t)){let Xt=ge.replace(/\./g,"-");r[`--persona-${Xt}`]=it.value}r["--persona-primary"]=(C=r["--persona-semantic-colors-primary"])!=null?C:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(R=r["--persona-semantic-colors-secondary"])!=null?R:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(M=r["--persona-semantic-colors-accent"])!=null?M:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(A=r["--persona-semantic-colors-surface"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(L=r["--persona-semantic-colors-background"])!=null?L:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(w=r["--persona-semantic-colors-text"])!=null?w:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(b=r["--persona-semantic-colors-text-muted"])!=null?b:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(T=r["--persona-semantic-colors-text-inverse"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(I=r["--persona-semantic-colors-border"])!=null?I:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(P=r["--persona-semantic-colors-divider"])!=null?P:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(k=r["--persona-components-voice-recording-indicator"])!=null?k:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(N=r["--persona-components-voice-recording-background"])!=null?N:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(U=r["--persona-components-voice-processing-icon"])!=null?U:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Y=r["--persona-components-voice-speaking-icon"])!=null?Y:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(he=r["--persona-components-approval-requested-background"])!=null?he:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=($e=r["--persona-components-approval-requested-border"])!=null?$e:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(Me=r["--persona-components-approval-requested-text"])!=null?Me:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Ie=r["--persona-components-approval-requested-shadow"])!=null?Ie:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-approval-approve-bg"]=(qe=r["--persona-components-approval-approve-background"])!=null?qe:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Ee=r["--persona-components-approval-deny-background"])!=null?Ee:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(Be=r["--persona-components-attachment-image-background"])!=null?Be:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(ae=r["--persona-components-attachment-image-border"])!=null?ae:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(Q=r["--persona-semantic-typography-fontFamily"])!=null?Q:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(pe=r["--persona-semantic-typography-fontSize"])!=null?pe:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(ye=r["--persona-semantic-typography-fontWeight"])!=null?ye:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(ne=r["--persona-semantic-typography-lineHeight"])!=null?ne:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(K=r["--persona-palette-radius-sm"])!=null?K:"0.125rem",r["--persona-radius-md"]=(oe=r["--persona-palette-radius-md"])!=null?oe:"0.375rem",r["--persona-radius-lg"]=(Ge=r["--persona-palette-radius-lg"])!=null?Ge:"0.5rem",r["--persona-radius-xl"]=(Z=r["--persona-palette-radius-xl"])!=null?Z:"0.75rem",r["--persona-radius-full"]=(se=r["--persona-palette-radius-full"])!=null?se:"9999px",r["--persona-launcher-radius"]=(Ct=(We=r["--persona-components-launcher-borderRadius"])!=null?We:r["--persona-palette-radius-full"])!=null?Ct:"9999px",r["--persona-launcher-bg"]=(Lt=r["--persona-components-launcher-background"])!=null?Lt:r["--persona-primary"],r["--persona-launcher-fg"]=(mt=r["--persona-components-launcher-foreground"])!=null?mt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(Oe=r["--persona-components-launcher-border"])!=null?Oe:r["--persona-border"],r["--persona-button-primary-bg"]=(fe=r["--persona-components-button-primary-background"])!=null?fe:r["--persona-primary"],r["--persona-button-primary-fg"]=(Ye=r["--persona-components-button-primary-foreground"])!=null?Ye:r["--persona-text-inverse"],r["--persona-button-radius"]=(ie=(X=r["--persona-components-button-primary-borderRadius"])!=null?X:r["--persona-palette-radius-full"])!=null?ie:"9999px",r["--persona-panel-radius"]=(Ve=(ve=r["--persona-components-panel-borderRadius"])!=null?ve:r["--persona-radius-xl"])!=null?Ve:"0.75rem",r["--persona-panel-border"]=(Pt=r["--persona-components-panel-border"])!=null?Pt:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(ce=(we=r["--persona-components-panel-shadow"])!=null?we:r["--persona-palette-shadows-xl"])!=null?ce:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(xr=r["--persona-components-launcher-shadow"])!=null?xr:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(ar=(Rt=r["--persona-components-input-borderRadius"])!=null?Rt:r["--persona-radius-lg"])!=null?ar:"0.5rem",r["--persona-message-user-radius"]=(yr=(Co=r["--persona-components-message-user-borderRadius"])!=null?Co:r["--persona-radius-lg"])!=null?yr:"0.5rem",r["--persona-message-assistant-radius"]=(H=(ze=r["--persona-components-message-assistant-borderRadius"])!=null?ze:r["--persona-radius-lg"])!=null?H:"0.5rem",r["--persona-header-bg"]=(de=r["--persona-components-header-background"])!=null?de:r["--persona-surface"],r["--persona-header-border"]=(Te=r["--persona-components-header-border"])!=null?Te:r["--persona-divider"],r["--persona-header-icon-bg"]=(Se=r["--persona-components-header-iconBackground"])!=null?Se:r["--persona-primary"],r["--persona-header-icon-fg"]=(Le=r["--persona-components-header-iconForeground"])!=null?Le:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Ze=r["--persona-components-header-titleForeground"])!=null?Ze:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Ke=r["--persona-components-header-subtitleForeground"])!=null?Ke:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(dt=r["--persona-components-header-actionIconForeground"])!=null?dt:r["--persona-muted"];let o=(It=e.components)==null?void 0:It.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(z=e.components)==null?void 0:z.introCard;r["--persona-intro-card-bg"]=(ot=r["--persona-components-introCard-background"])!=null?ot:r["--persona-surface"],r["--persona-intro-card-radius"]=(j=r["--persona-components-introCard-borderRadius"])!=null?j:"1rem",r["--persona-intro-card-padding"]=(le=r["--persona-components-introCard-padding"])!=null?le:"1.5rem",r["--persona-intro-card-shadow"]=(xt=(Ae=n==null?void 0:n.shadow)!=null?Ae:r["--persona-components-introCard-shadow"])!=null?xt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Zt=r["--persona-components-input-background"])!=null?Zt:r["--persona-surface"],r["--persona-input-placeholder"]=(er=r["--persona-components-input-placeholder"])!=null?er:r["--persona-text-muted"],r["--persona-message-user-bg"]=(fr=r["--persona-components-message-user-background"])!=null?fr:r["--persona-accent"],r["--persona-message-user-text"]=(Ht=r["--persona-components-message-user-text"])!=null?Ht:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(et=r["--persona-components-message-user-shadow"])!=null?et:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Wt=r["--persona-components-message-assistant-background"])!=null?Wt:r["--persona-surface"],r["--persona-message-assistant-text"]=(st=r["--persona-components-message-assistant-text"])!=null?st:r["--persona-text"],r["--persona-message-assistant-border"]=(Gt=r["--persona-components-message-assistant-border"])!=null?Gt:r["--persona-border"],r["--persona-message-assistant-shadow"]=(to=r["--persona-components-message-assistant-shadow"])!=null?to:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(tr=(Ar=r["--persona-components-scrollToBottom-background"])!=null?Ar:r["--persona-button-primary-bg"])!=null?tr:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(wo=(Wr=r["--persona-components-scrollToBottom-foreground"])!=null?Wr:r["--persona-button-primary-fg"])!=null?wo:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(yt=r["--persona-components-scrollToBottom-border"])!=null?yt:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(Or=r["--persona-components-scrollToBottom-size"])!=null?Or:"40px",r["--persona-scroll-to-bottom-radius"]=(uo=(Fo=(So=r["--persona-components-scrollToBottom-borderRadius"])!=null?So:r["--persona-button-radius"])!=null?Fo:r["--persona-radius-full"])!=null?uo:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Ln=(gt=r["--persona-components-scrollToBottom-shadow"])!=null?gt:r["--persona-palette-shadows-sm"])!=null?Ln:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Ao=r["--persona-components-scrollToBottom-padding"])!=null?Ao:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(Pn=r["--persona-components-scrollToBottom-gap"])!=null?Pn:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(aa=(Hr=r["--persona-components-scrollToBottom-fontSize"])!=null?Hr:r["--persona-palette-typography-fontSize-sm"])!=null?aa:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(rn=r["--persona-components-scrollToBottom-iconSize"])!=null?rn:"14px",r["--persona-tool-bubble-shadow"]=(No=r["--persona-components-toolBubble-shadow"])!=null?No:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(on=r["--persona-components-reasoningBubble-shadow"])!=null?on:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(nn=r["--persona-components-composer-shadow"])!=null?nn:"none",r["--persona-md-inline-code-bg"]=(Rn=r["--persona-components-markdown-inlineCode-background"])!=null?Rn:r["--persona-container"],r["--persona-md-inline-code-color"]=(In=r["--persona-components-markdown-inlineCode-foreground"])!=null?In:r["--persona-text"],r["--persona-md-link-color"]=(vt=(an=r["--persona-components-markdown-link-foreground"])!=null?an:r["--persona-accent"])!=null?vt:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let p=r["--persona-components-markdown-heading-h2-fontWeight"];p&&(r["--persona-md-h2-weight"]=p);let d=r["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(r["--persona-md-prose-font-family"]=d),r["--persona-md-code-block-bg"]=(_r=r["--persona-components-markdown-codeBlock-background"])!=null?_r:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Ur=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Ur:r["--persona-border"],r["--persona-md-code-block-text-color"]=(Mr=r["--persona-components-markdown-codeBlock-textColor"])!=null?Mr:"inherit",r["--persona-md-table-header-bg"]=(St=r["--persona-components-markdown-table-headerBackground"])!=null?St:r["--persona-container"],r["--persona-md-table-border-color"]=(ro=r["--persona-components-markdown-table-borderColor"])!=null?ro:r["--persona-border"],r["--persona-md-hr-color"]=(oo=r["--persona-components-markdown-hr-color"])!=null?oo:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(qr=r["--persona-components-markdown-blockquote-borderColor"])!=null?qr:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(sn=r["--persona-components-markdown-blockquote-background"])!=null?sn:"transparent",r["--persona-md-blockquote-text-color"]=(Oo=r["--persona-components-markdown-blockquote-textColor"])!=null?Oo:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(ln=r["--persona-components-collapsibleWidget-container"])!=null?ln:r["--persona-surface"],r["--cw-surface"]=(Vr=r["--persona-components-collapsibleWidget-surface"])!=null?Vr:r["--persona-surface"],r["--cw-border"]=(Bt=r["--persona-components-collapsibleWidget-border"])!=null?Bt:r["--persona-border"],r["--persona-message-border"]=(Tr=r["--persona-components-message-border"])!=null?Tr:r["--persona-border"];let u=e.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(r["--persona-icon-btn-bg"]=g.background),g.border&&(r["--persona-icon-btn-border"]=g.border),g.color&&(r["--persona-icon-btn-color"]=g.color),g.padding&&(r["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(r["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(r["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(r["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(r["--persona-icon-btn-active-border"]=g.activeBorder));let c=u==null?void 0:u.labelButton;c&&(c.background&&(r["--persona-label-btn-bg"]=c.background),c.border&&(r["--persona-label-btn-border"]=c.border),c.color&&(r["--persona-label-btn-color"]=c.color),c.padding&&(r["--persona-label-btn-padding"]=c.padding),c.borderRadius&&(r["--persona-label-btn-radius"]=c.borderRadius),c.hoverBackground&&(r["--persona-label-btn-hover-bg"]=c.hoverBackground),c.fontSize&&(r["--persona-label-btn-font-size"]=c.fontSize),c.gap&&(r["--persona-label-btn-gap"]=c.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(r["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(r["--persona-toggle-group-radius"]=m.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let ge=x.toolbar;ge.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=ge.iconHoverColor),ge.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=ge.iconHoverBackground),ge.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=ge.iconPadding),ge.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=ge.iconBorderRadius),ge.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=ge.iconBorder),ge.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=ge.toggleGroupGap),ge.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=ge.toggleBorderRadius),ge.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=ge.copyBackground),ge.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=ge.copyBorder),ge.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=ge.copyColor),ge.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=ge.copyBorderRadius),ge.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=ge.copyPadding),ge.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=ge.copyMenuBackground,r["--persona-dropdown-bg"]=(no=r["--persona-dropdown-bg"])!=null?no:ge.copyMenuBackground),ge.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=ge.copyMenuBorder,r["--persona-dropdown-border"]=(dn=r["--persona-dropdown-border"])!=null?dn:ge.copyMenuBorder),ge.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=ge.copyMenuShadow,r["--persona-dropdown-shadow"]=(_o=r["--persona-dropdown-shadow"])!=null?_o:ge.copyMenuShadow),ge.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=ge.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(pn=r["--persona-dropdown-radius"])!=null?pn:ge.copyMenuBorderRadius),ge.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ge.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Mo=r["--persona-dropdown-item-hover-bg"])!=null?Mo:ge.copyMenuItemHoverBackground),ge.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=ge.iconBackground),ge.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=ge.toolbarBorder)}if(x!=null&&x.tab){let ge=x.tab;ge.background&&(r["--persona-artifact-tab-bg"]=ge.background),ge.activeBackground&&(r["--persona-artifact-tab-active-bg"]=ge.activeBackground),ge.activeBorder&&(r["--persona-artifact-tab-active-border"]=ge.activeBorder),ge.borderRadius&&(r["--persona-artifact-tab-radius"]=ge.borderRadius),ge.textColor&&(r["--persona-artifact-tab-color"]=ge.textColor),ge.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=ge.hoverBackground),ge.listBackground&&(r["--persona-artifact-tab-list-bg"]=ge.listBackground),ge.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=ge.listBorderColor),ge.listPadding&&(r["--persona-artifact-tab-list-padding"]=ge.listPadding)}if(x!=null&&x.pane){let ge=x.pane;if(ge.toolbarBackground){let it=(zr=La(e,ge.toolbarBackground))!=null?zr:ge.toolbarBackground;r["--persona-artifact-toolbar-bg"]=it}}return r}var Qg={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 pb={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"}}},Yg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},gs=()=>{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"},cb=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":gs()},_p=e=>cb(e),ub=e=>Pa(e),fb=e=>{var r;let t=Pa(void 0,{validate:!1});return Pa({...e,palette:{...t.palette,colors:{...pb.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Ra=e=>{let t=_p(e),r=Yg(e==null?void 0:e.theme),o=Yg(e==null?void 0:e.darkTheme);return t==="dark"?fb(ms(r!=null?r:{},o!=null?o:{})):ub(r)},mb=e=>Ei(e),An=(e,t)=>{let r=Ra(t),o=mb(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},ki=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(gs())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(gs());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(r=>r())}};var Zg=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:c=>c.getAttribute("im-preserve")==="true",shouldReAppend:c=>c.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(c,m,x={}){c=u(c);let C=g(m),R=d(c,C,x),M=n(R,()=>i(R,c,C,A=>A.morphStyle==="innerHTML"?(a(A,c,C),Array.from(c.childNodes)):o(A,c,C)));return R.pantry.remove(),M}function o(c,m,x){let C=g(m);return a(c,C,x,m,m.nextSibling),Array.from(C.childNodes)}function n(c,m){var L;if(!c.config.restoreFocus)return m();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return m();let{id:C,selectionStart:R,selectionEnd:M}=x,A=m();return C&&C!==((L=document.activeElement)==null?void 0:L.getAttribute("id"))&&(x=c.target.querySelector(`[id="${C}"]`),x==null||x.focus()),x&&!x.selectionEnd&&M&&x.setSelectionRange(R,M),A}let a=(function(){function c(y,w,b,T=null,I=null){w instanceof HTMLTemplateElement&&b instanceof HTMLTemplateElement&&(w=w.content,b=b.content),T||(T=w.firstChild);for(let P of b.childNodes){if(T&&T!=I){let N=x(y,P,T,I);if(N){N!==T&&R(y,T,N),s(N,P,y),T=N.nextSibling;continue}}if(P instanceof Element){let N=P.getAttribute("id");if(y.persistentIds.has(N)){let U=M(w,N,T,y);s(U,P,y),T=U.nextSibling;continue}}let k=m(w,P,T,y);k&&(T=k.nextSibling)}for(;T&&T!=I;){let P=T;T=T.nextSibling,C(y,P)}}function m(y,w,b,T){if(T.callbacks.beforeNodeAdded(w)===!1)return null;if(T.idMap.has(w)){let I=document.createElement(w.tagName);return y.insertBefore(I,b),s(I,w,T),T.callbacks.afterNodeAdded(I),I}else{let I=document.importNode(w,!0);return y.insertBefore(I,b),T.callbacks.afterNodeAdded(I),I}}let x=(function(){function y(T,I,P,k){let N=null,U=I.nextSibling,Y=0,he=P;for(;he&&he!=k;){if(b(he,I)){if(w(T,he,I))return he;N===null&&(T.idMap.has(he)||(N=he))}if(N===null&&U&&b(he,U)&&(Y++,U=U.nextSibling,Y>=2&&(N=void 0)),T.activeElementAndParents.includes(he))break;he=he.nextSibling}return N||null}function w(T,I,P){let k=T.idMap.get(I),N=T.idMap.get(P);if(!N||!k)return!1;for(let U of k)if(N.has(U))return!0;return!1}function b(T,I){var N,U,Y;let P=T,k=I;return P.nodeType===k.nodeType&&P.tagName===k.tagName&&(!((N=P.getAttribute)!=null&&N.call(P,"id"))||((U=P.getAttribute)==null?void 0:U.call(P,"id"))===((Y=k.getAttribute)==null?void 0:Y.call(k,"id")))}return y})();function C(y,w){var b;if(y.idMap.has(w))L(y.pantry,w,null);else{if(y.callbacks.beforeNodeRemoved(w)===!1)return;(b=w.parentNode)==null||b.removeChild(w),y.callbacks.afterNodeRemoved(w)}}function R(y,w,b){let T=w;for(;T&&T!==b;){let I=T;T=T.nextSibling,C(y,I)}return T}function M(y,w,b,T){var P,k;let I=((k=(P=T.target).getAttribute)==null?void 0:k.call(P,"id"))===w&&T.target||T.target.querySelector(`[id="${w}"]`)||T.pantry.querySelector(`[id="${w}"]`);return A(I,T),L(y,I,b),I}function A(y,w){let b=y.getAttribute("id");for(;y=y.parentNode;){let T=w.idMap.get(y);T&&(T.delete(b),T.size||w.idMap.delete(y))}}function L(y,w,b){if(y.moveBefore)try{y.moveBefore(w,b)}catch{y.insertBefore(w,b)}else y.insertBefore(w,b)}return c})(),s=(function(){function c(A,L,y){return y.ignoreActive&&A===document.activeElement?null:(y.callbacks.beforeNodeMorphed(A,L)===!1||(A instanceof HTMLHeadElement&&y.head.ignore||(A instanceof HTMLHeadElement&&y.head.style!=="morph"?p(A,L,y):(m(A,L,y),M(A,y)||a(y,A,L))),y.callbacks.afterNodeMorphed(A,L)),A)}function m(A,L,y){let w=L.nodeType;if(w===1){let b=A,T=L,I=b.attributes,P=T.attributes;for(let k of P)R(k.name,b,"update",y)||b.getAttribute(k.name)!==k.value&&b.setAttribute(k.name,k.value);for(let k=I.length-1;0<=k;k--){let N=I[k];if(N&&!T.hasAttribute(N.name)){if(R(N.name,b,"remove",y))continue;b.removeAttribute(N.name)}}M(b,y)||x(b,T,y)}(w===8||w===3)&&A.nodeValue!==L.nodeValue&&(A.nodeValue=L.nodeValue)}function x(A,L,y){if(A instanceof HTMLInputElement&&L instanceof HTMLInputElement&&L.type!=="file"){let w=L.value,b=A.value;C(A,L,"checked",y),C(A,L,"disabled",y),L.hasAttribute("value")?b!==w&&(R("value",A,"update",y)||(A.setAttribute("value",w),A.value=w)):R("value",A,"remove",y)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&L instanceof HTMLOptionElement)C(A,L,"selected",y);else if(A instanceof HTMLTextAreaElement&&L instanceof HTMLTextAreaElement){let w=L.value,b=A.value;if(R("value",A,"update",y))return;w!==b&&(A.value=w),A.firstChild&&A.firstChild.nodeValue!==w&&(A.firstChild.nodeValue=w)}}function C(A,L,y,w){let b=L[y],T=A[y];if(b!==T){let I=R(y,A,"update",w);I||(A[y]=L[y]),b?I||A.setAttribute(y,""):R(y,A,"remove",w)||A.removeAttribute(y)}}function R(A,L,y,w){return A==="value"&&w.ignoreActiveValue&&L===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(A,L,y)===!1}function M(A,L){return!!L.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return c})();function i(c,m,x,C){if(c.head.block){let R=m.querySelector("head"),M=x.querySelector("head");if(R&&M){let A=p(R,M,c);return Promise.all(A).then(()=>{let L=Object.assign(c,{head:{block:!1,ignore:!0}});return C(L)})}}return C(c)}function p(c,m,x){let C=[],R=[],M=[],A=[],L=new Map;for(let w of m.children)L.set(w.outerHTML,w);for(let w of c.children){let b=L.has(w.outerHTML),T=x.head.shouldReAppend(w),I=x.head.shouldPreserve(w);b||I?T?R.push(w):(L.delete(w.outerHTML),M.push(w)):x.head.style==="append"?T&&(R.push(w),A.push(w)):x.head.shouldRemove(w)!==!1&&R.push(w)}A.push(...L.values());let y=[];for(let w of A){let b=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(b)!==!1){if("href"in b&&b.href||"src"in b&&b.src){let T,I=new Promise(function(P){T=P});b.addEventListener("load",function(){T()}),y.push(I)}c.appendChild(b),x.callbacks.afterNodeAdded(b),C.push(b)}}for(let w of R)x.callbacks.beforeNodeRemoved(w)!==!1&&(c.removeChild(w),x.callbacks.afterNodeRemoved(w));return x.head.afterHeadMorphed(c,{added:C,kept:M,removed:R}),y}let d=(function(){function c(y,w,b){let{persistentIds:T,idMap:I}=A(y,w),P=m(b),k=P.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(k))throw`Do not understand how to morph style ${k}`;return{target:y,newContent:w,config:P,morphStyle:k,ignoreActive:P.ignoreActive,ignoreActiveValue:P.ignoreActiveValue,restoreFocus:P.restoreFocus,idMap:I,persistentIds:T,pantry:x(),activeElementAndParents:C(y),callbacks:P.callbacks,head:P.head}}function m(y){let w=Object.assign({},t);return Object.assign(w,y),w.callbacks=Object.assign({},t.callbacks,y.callbacks),w.head=Object.assign({},t.head,y.head),w}function x(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function C(y){let w=[],b=document.activeElement;if((b==null?void 0:b.tagName)!=="BODY"&&y.contains(b))for(;b&&(w.push(b),b!==y);)b=b.parentElement;return w}function R(y){var b;let w=Array.from(y.querySelectorAll("[id]"));return(b=y.getAttribute)!=null&&b.call(y,"id")&&w.push(y),w}function M(y,w,b,T){for(let I of T){let P=I.getAttribute("id");if(w.has(P)){let k=I;for(;k;){let N=y.get(k);if(N==null&&(N=new Set,y.set(k,N)),N.add(P),k===b)break;k=k.parentElement}}}}function A(y,w){let b=R(y),T=R(w),I=L(b,T),P=new Map;M(P,I,y,b);let k=w.__idiomorphRoot||w;return M(P,I,k,T),{persistentIds:I,idMap:P}}function L(y,w){let b=new Set,T=new Map;for(let{id:P,tagName:k}of y)T.has(P)?b.add(P):T.set(P,k);let I=new Set;for(let{id:P,tagName:k}of w)I.has(P)?b.add(P):T.get(P)===k&&I.add(P);for(let P of b)I.delete(P);return I}return c})(),{normalizeElement:u,normalizeParent:g}=(function(){let c=new WeakSet;function m(M){return M instanceof Document?M.documentElement:M}function x(M){if(M==null)return document.createElement("div");if(typeof M=="string")return x(R(M));if(c.has(M))return M;if(M instanceof Node){if(M.parentNode)return new C(M);{let A=document.createElement("div");return A.append(M),A}}else{let A=document.createElement("div");for(let L of[...M])A.append(L);return A}}class C{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],L=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;L&&L!=this.nextSibling;)A.push(L),L=L.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((L,y)=>{if(y instanceof Element){y.matches(A)&&L.push(y);let w=y.querySelectorAll(A);for(let b=0;b<w.length;b++)L.push(w[b])}return L},[])}insertBefore(A,L){return this.realParentNode.insertBefore(A,L)}moveBefore(A,L){return this.realParentNode.moveBefore(A,L)}get __idiomorphRoot(){return this.originalNode}}function R(M){let A=new DOMParser,L=M.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(L.match(/<\/html>/)||L.match(/<\/head>/)||L.match(/<\/body>/)){let y=A.parseFromString(M,"text/html");if(L.match(/<\/html>/))return c.add(y),y;{let w=y.firstChild;return w&&c.add(w),w}}else{let w=A.parseFromString("<body><template>"+M+"</template></body>","text/html").body.querySelector("template").content;return c.add(w),w}}return{normalizeElement:m,normalizeParent:x}})();return{morph:r,defaults:t}})();var Li=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;Zg.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let p=(s=n.textContent)!=null?s:"",d=(i=a.textContent)!=null?i:"";if(p!==d)return}return!1}}}}})};var eh=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Pi={index:-1,draft:""};function th(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...Pi}}}function rh(e,t){var r,o,n,a,s,i,p,d,u,g,c,m,x,C,R,M,A,L,y,w,b,T,I,P,k,N,U,Y,he,$e,Me,Ie,qe,Ee,Be,ae,Q,pe;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(p=(i=e.rawContent)==null?void 0:i.length)!=null?p:0,(u=(d=e.llmContent)==null?void 0:d.length)!=null?u:0,(c=(g=e.approval)==null?void 0:g.status)!=null?c:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(R=(C=e.toolCall)==null?void 0:C.name)!=null?R:"",(L=(A=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:A.length)!=null?L:0,(T=(b=(w=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:w[e.toolCall.chunks.length-1])==null?void 0:b.slice(-32))!=null?T:"",typeof((I=e.toolCall)==null?void 0:I.args)=="string"?e.toolCall.args.length:(P=e.toolCall)!=null&&P.args?JSON.stringify(e.toolCall.args).length:0,(U=(N=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:N.length)!=null?U:0,(Me=($e=(he=(Y=e.reasoning)==null?void 0:Y.chunks)==null?void 0:he[e.reasoning.chunks.length-1])==null?void 0:$e.length)!=null?Me:0,(Be=(Ee=(qe=(Ie=e.reasoning)==null?void 0:Ie.chunks)==null?void 0:qe[e.reasoning.chunks.length-1])==null?void 0:Ee.slice(-32))!=null?Be:"",(Q=(ae=e.contentParts)==null?void 0:ae.length)!=null?Q:0,(pe=e.stopReason)!=null?pe:"",t].join("\0")}function oh(){return new Map}function nh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function ah(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function sh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function Ri(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Zo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Zn(e,t){return Zo(e)-e.scrollTop<=t}function Ii(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,u=r-o;return s||Math.abs(u)<a?{action:"none",delta:u,nextLastScrollTop:r}:!t&&n&&(!d||u>0)?{action:"resume",delta:u,nextLastScrollTop:r}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:r}:t&&p&&!n?{action:"pause",delta:u,nextLastScrollTop:r}:{action:"none",delta:u,nextLastScrollTop:r}}function Wi(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}function ih(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function lh(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),r=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:r}}function dh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var wr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Sr=1e5,Mn=Sr+1;var hs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},gb=["pre","code","a","script","style"],Hi=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:hs.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:hs.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:hs.speed,duration:(n=e==null?void 0:e.duration)!=null?n:hs.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:hs.buffer}},ch=[{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"}],xs=new Map;for(let e of ch)xs.set(e.name,e);var ea=e=>{xs.set(e.name,e)},Vp=e=>{ch.some(t=>t.name===e)||xs.delete(e)},zp=()=>Array.from(xs.keys()),ys=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=xs.get(e))!=null?o:null},Bi=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
18
- `);return a<0?"":e.slice(0,a)}return e},hb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},xb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},Up=/\s/,yb=(e,t)=>{let r=e.parentNode;for(;r;){if(r.nodeType===1){let o=r;if(t.has(o.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},bb=(e,t,r)=>{var p;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(p=e.nodeValue)!=null?p:"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(Up.test(a[i])){let d=i;for(;d<a.length&&Up.test(a[d]);)d+=1;s.appendChild(o.createTextNode(a.slice(i,d))),i=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let u=i;for(;u<a.length&&!Up.test(a[u]);)d.appendChild(hb(o,a[u],t,r.value)),r.value+=1,u+=1;s.appendChild(d),i=u}n.replaceChild(s,e)},vb=(e,t,r)=>{var p;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(p=e.nodeValue)!=null?p:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let d of i)d&&(/^\s+$/.test(d)?s.appendChild(o.createTextNode(d)):(s.appendChild(xb(o,d,t,r.value)),r.value+=1));n.replaceChild(s,e)},bs=(e,t,r,o)=>{var g,c;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((g=o==null?void 0:o.skipTags)!=null?g:gb).map(m=>m.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],p=s.nextNode();for(;p;)yb(p,a)||i.push(p),p=s.nextNode();let d={value:(c=o==null?void 0:o.startIndex)!=null?c:0},u=t==="char"?bb:vb;for(let m of i)u(m,r,d);return n.innerHTML},Di=(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},vs=(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 r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},ph=new WeakMap,Cb=(e,t)=>{var a;if(!e.styles)return;let r=ph.get(t);if(r||(r=new Set,ph.set(t,r)),r.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:(a=t.ownerDocument)!=null?a:document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)},qp=new WeakMap,wb=(e,t)=>{if(!e.onAttach)return;let r=qp.get(t);if(r||(r=new Map,qp.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},uh=e=>{let t=qp.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},$p=(e,t)=>{Cb(e,t),wb(e,t)};function jp(e,t=Sr){let r=e.style.position,o=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=o,e.style.isolation=n}}var Cs=0,Tn=null;function Gp(e=document){var r;if(Cs++,Cs===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Tn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Cs=Math.max(0,Cs-1),Cs===0&&Tn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Tn.originalOverflow,n.style.position=Tn.originalPosition,n.style.top=Tn.originalTop,n.style.width=Tn.originalWidth,a.scrollTo(0,Tn.scrollY),Tn=null}}}var ws={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},nr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},En=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},Zr=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:ws.side,width:(n=t==null?void 0:t.width)!=null?n:ws.width,animate:(a=t==null?void 0:t.animate)!=null?a:ws.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:ws.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:ws.maxHeight}};var vo={"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 Sb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Fi=(e,t={})=>{var R,M,A,L,y,w;let{showClose:r=!0,wrapperClassName:o=Sb,buttonSize:n,iconSize:a="28px"}=t,s=(R=e==null?void 0:e.launcher)!=null?R:{},i=(M=n!=null?n:s.closeButtonSize)!=null?M:"32px",p=S("div",o),d=(A=s.closeButtonTooltipText)!=null?A:"Close chat",u=(L=s.closeButtonShowTooltip)!=null?L:!0,g=(y=s.closeButtonIconName)!=null?y:"x",c=(w=s.closeButtonIconText)!=null?w:"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=Mt("button",{className:ts("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||Ir.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),C=be(g,a,"currentColor",1);if(C?(C.style.display="block",x.appendChild(C)):x.textContent=c,p.appendChild(x),u&&d){let b=null,T=()=>{if(b)return;let P=x.ownerDocument,k=P.body;if(!k)return;b=Bo(P,"div","persona-clear-chat-tooltip"),b.textContent=d;let N=Bo(P,"div");N.className="persona-clear-chat-tooltip-arrow",b.appendChild(N);let U=x.getBoundingClientRect();b.style.position="fixed",b.style.zIndex=String(Mn),b.style.left=`${U.left+U.width/2}px`,b.style.top=`${U.top-8}px`,b.style.transform="translate(-50%, -100%)",k.appendChild(b)},I=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};p.addEventListener("mouseenter",T),p.addEventListener("mouseleave",I),x.addEventListener("focus",T),x.addEventListener("blur",I),p._cleanupTooltip=()=>{I(),p.removeEventListener("mouseenter",T),p.removeEventListener("mouseleave",I),x.removeEventListener("focus",T),x.removeEventListener("blur",I)}}return{button:x,wrapper:p}},Ab="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ni=(e,t={})=>{var b,T,I,P,k,N,U,Y,he,$e,Me,Ie,qe;let{wrapperClassName:r=Ab,buttonSize:o,iconSize:n="20px"}=t,s=(T=((b=e==null?void 0:e.launcher)!=null?b:{}).clearChat)!=null?T:{},i=(I=o!=null?o:s.size)!=null?I:"32px",p=(P=s.iconName)!=null?P:"refresh-cw",d=(k=s.iconColor)!=null?k:"",u=(N=s.backgroundColor)!=null?N:"",g=(U=s.borderWidth)!=null?U:"",c=(Y=s.borderColor)!=null?Y:"",m=(he=s.borderRadius)!=null?he:"",x=($e=s.paddingX)!=null?$e:"",C=(Me=s.paddingY)!=null?Me:"",R=(Ie=s.tooltipText)!=null?Ie:"Clear chat",M=(qe=s.showTooltip)!=null?qe:!0,A=S("div",r),L=!!(g||c),y=Mt("button",{className:ts("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!L&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":R},style:{height:i,width:i,color:d||Ir.actionIconColor,backgroundColor:u||void 0,border:L?`${g||"0px"} solid ${c||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),w=be(p,n,"currentColor",1);if(w&&(w.style.display="block",y.appendChild(w)),A.appendChild(y),M&&R){let Ee=null,Be=()=>{if(Ee)return;let Q=y.ownerDocument,pe=Q.body;if(!pe)return;Ee=Bo(Q,"div","persona-clear-chat-tooltip"),Ee.textContent=R;let ye=Bo(Q,"div");ye.className="persona-clear-chat-tooltip-arrow",Ee.appendChild(ye);let ne=y.getBoundingClientRect();Ee.style.position="fixed",Ee.style.zIndex=String(Mn),Ee.style.left=`${ne.left+ne.width/2}px`,Ee.style.top=`${ne.top-8}px`,Ee.style.transform="translate(-50%, -100%)",pe.appendChild(Ee)},ae=()=>{Ee&&Ee.parentNode&&(Ee.parentNode.removeChild(Ee),Ee=null)};A.addEventListener("mouseenter",Be),A.addEventListener("mouseleave",ae),y.addEventListener("focus",Be),y.addEventListener("blur",ae),A._cleanupTooltip=()=>{ae(),A.removeEventListener("mouseenter",Be),A.removeEventListener("mouseleave",ae),y.removeEventListener("focus",Be),y.removeEventListener("blur",ae)}}return{button:y,wrapper:A}};var Ir={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))"},en=e=>{var w,b,T,I,P,k,N,U,Y,he,$e,Me,Ie,qe,Ee,Be;let{config:t,showClose:r=!0}=e,o=Mt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),n=(w=t==null?void 0:t.launcher)!=null?w:{},a=(b=n.headerIconSize)!=null?b:"48px",s=(T=n.closeButtonPlacement)!=null?T:"inline",i=(I=n.headerIconHidden)!=null?I:!1,p=n.headerIconName,d=Mt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(p){let ae=parseFloat(a)||24,Q=be(p,ae*.6,"currentColor",1);Q?d.replaceChildren(Q):d.textContent=(k=(P=t==null?void 0:t.launcher)==null?void 0:P.agentIconText)!=null?k:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let ae=S("img");ae.src=t.launcher.iconUrl,ae.alt="",ae.className="persona-rounded-xl persona-object-cover",ae.style.height=a,ae.style.width=a,d.replaceChildren(ae)}else d.textContent=(Y=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?Y:"\u{1F4AC}";let u=S("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Mt("span",{className:"persona-text-base persona-font-semibold",text:($e=(he=t==null?void 0:t.launcher)==null?void 0:he.title)!=null?$e:"Chat Assistant",style:{color:Ir.titleColor}}),c=Mt("span",{className:"persona-text-xs",text:(Ie=(Me=t==null?void 0:t.launcher)==null?void 0:Me.subtitle)!=null?Ie:"Here to help you get answers fast",style:{color:Ir.subtitleColor}});u.append(g,c),i?o.append(u):o.append(d,u);let m=(qe=n.clearChat)!=null?qe:{},x=(Ee=m.enabled)!=null?Ee:!0,C=(Be=m.placement)!=null?Be:"inline",R=null,M=null;if(x){let Q=Ni(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});R=Q.button,M=Q.wrapper,C==="top-right"&&(M.style.right="48px"),C==="inline"&&o.appendChild(M)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&C==="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:L,wrapper:y}=Fi(t,{showClose:r,wrapperClassName:A});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:d,headerTitle:g,headerSubtitle:c,closeButton:L,closeButtonWrapper:y,clearChatButton:R,clearChatButtonWrapper:M}},ta=(e,t,r)=>{var s,i,p,d;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(d=(p=o.clearChat)==null?void 0:p.placement)!=null?d:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function kn(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=S("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Mn)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of t){if(m.dividerBefore){let R=document.createElement("hr");s.appendChild(R)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let R=be(m.icon,16,"currentColor",1.5);R&&x.appendChild(R)}let C=document.createElement("span");C.textContent=m.label,x.appendChild(C),x.addEventListener("click",R=>{R.stopPropagation(),u(),r(m.id)}),s.appendChild(x)}let i=null;function p(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function d(){p(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!s.contains(x.target)&&!o.contains(x.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){s.classList.add("persona-hidden"),i==null||i(),i=null}function g(){s.classList.contains("persona-hidden")?d():u()}function c(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:u,toggle:g,destroy:c}}function cr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,p=S("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",r),p.title=r;let d=be(t,o!=null?o:16,"currentColor",n!=null?n:2);if(d&&p.appendChild(d),s&&p.addEventListener("click",s),i)for(let[u,g]of Object.entries(i))p.setAttribute(u,g);return p}function Ss(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let u=S("button",d);if(u.type="button",u.setAttribute("aria-label",r),t){let c=be(t,a!=null?a:14,"currentColor",2);c&&u.appendChild(c)}let g=S("span");if(g.textContent=r,u.appendChild(g),i&&u.addEventListener("click",i),p)for(let[c,m]of Object.entries(p))u.setAttribute(c,m);return u}function fh(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=S("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function p(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===s?"true":"false")}for(let u of t){let g;u.icon?g=cr({icon:u.icon,label:u.label,onClick:()=>{s=u.id,p(),o(u.id)}}):(g=S("button","persona-icon-btn"),g.type="button",g.setAttribute("aria-label",u.label),g.title=u.label,g.textContent=u.label,g.addEventListener("click",()=>{s=u.id,p(),o(u.id)})),g.setAttribute("aria-pressed",u.id===s?"true":"false"),i.push({id:u.id,btn:g}),a.appendChild(g)}function d(u){s=u,p()}return{element:a,setSelected:d}}function Oi(e){var m,x;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:p}=e,d=S("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let u=S("span","persona-combo-btn-label");u.textContent=t,d.appendChild(u);let g=be(r,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",d.appendChild(g)),p&&(d.style.borderRadius=(m=p.borderRadius)!=null?m:"10px",d.style.padding=(x=p.padding)!=null?x:"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{var C,R;d.style.backgroundColor=(C=p.background)!=null?C:"",d.style.borderColor=(R=p.border)!=null?R:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let c=kn({items:o,onSelect:C=>{d.setAttribute("aria-expanded","false"),n(C)},anchor:d,position:a,portal:s});return s||d.appendChild(c.element),d.addEventListener("click",C=>{C.stopPropagation();let R=!c.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",R?"false":"true"),c.toggle()}),d.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),d.click())}),{element:d,setLabel:C=>{u.textContent=C,d.setAttribute("aria-label",C)},open:()=>{d.setAttribute("aria-expanded","true"),c.show()},close:()=>{d.setAttribute("aria-expanded","false"),c.hide()},toggle:()=>{let C=!c.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",C?"false":"true"),c.toggle()},destroy:()=>{c.destroy(),d.remove()}}}var Kp=e=>{var o;let t=en({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(r){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>r()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function Mb(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=S("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",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let p=be(s.icon,14,"currentColor",2);p&&i.appendChild(p)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let p=S("div","persona-relative");p.appendChild(i);let d=kn({items:s.menuItems,onSelect:u=>r==null?void 0:r(u),anchor:p,position:"bottom-left"});p.appendChild(d.element),i.addEventListener("click",u=>{u.stopPropagation(),d.toggle()}),e.appendChild(p)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var Xp=e=>{var A,L,y,w,b,T,I,P,k;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(A=t==null?void 0:t.launcher)!=null?A:{},i=S("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=n==null?void 0:n.titleMenu,d,u;if(p)d=Oi({label:(L=s.title)!=null?L:"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Ir.titleColor,u=(y=d.querySelector(".persona-combo-btn-label"))!=null?y:d;else{if(d=S("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=S("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Ir.titleColor,u.textContent=(w=s.title)!=null?w:"Chat Assistant",d.appendChild(u),Mb(d,n==null?void 0:n.trailingActions,(b=n==null?void 0:n.onAction)!=null?b:a),n!=null&&n.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let U=n.onTitleClick;d.addEventListener("click",Y=>{Y.target.closest("button")||U()}),d.addEventListener("keydown",Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),U())})}let N=n==null?void 0:n.titleRowHover;N&&(d.style.borderRadius=(T=N.borderRadius)!=null?T:"10px",d.style.padding=(I=N.padding)!=null?I:"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{var U,Y;d.style.backgroundColor=(U=N.background)!=null?U:"",d.style.borderColor=(Y=N.border)!=null?Y:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let g=(P=s.closeButtonSize)!=null?P:"32px",c=S("div",""),m=S("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=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none",m.style.color=s.closeButtonColor||Ir.actionIconColor;let x=(k=s.closeButtonIconName)!=null?k:"x",C=be(x,"28px","currentColor",1);C?m.appendChild(C):m.textContent="\xD7",o&&m.addEventListener("click",o),c.appendChild(m),i.appendChild(c);let R=S("div");R.style.display="none";let M=S("span");return M.style.display="none",{header:i,iconHolder:R,headerTitle:u,headerSubtitle:M,closeButton:m,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}},_i={default:Kp,minimal:Xp},Jp=e=>{var t;return(t=_i[e])!=null?t:_i.default},Ia=(e,t,r)=>{var s,i,p;if(t!=null&&t.render){let d=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=S("div");u.style.display="none";let g=S("span"),c=S("span"),m=S("button");m.style.display="none";let x=S("div");return x.style.display="none",{header:d,iconHolder:u,headerTitle:g,headerSubtitle:c,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=Jp(o)({config:e,showClose:(p=(i=t==null?void 0:t.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?p:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Ui=e=>{var s,i;let t=S("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.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 r=3,o=20;t.style.maxHeight=`${r*o}px`,t.style.overflowY="auto";let n=()=>{let p=parseFloat(t.style.maxHeight);return Number.isFinite(p)&&p>0?p:r*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let p=Math.min(t.scrollHeight,n());t.style.height=`${p}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:a}},qi=e=>{var w,b,T,I,P,k,N,U,Y,he,$e,Me;let t=(w=e==null?void 0:e.sendButton)!=null?w:{},r=(b=t.useIcon)!=null?b:!1,o=(T=t.iconText)!=null?T:"\u2191",n=t.iconName,a=(I=t.stopIconName)!=null?I:"square",s=(P=t.tooltipText)!=null?P:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",p=(U=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?U:"Send",d=(he=(Y=e==null?void 0:e.copy)==null?void 0:Y.stopButtonLabel)!=null?he:"Stop",u=($e=t.showTooltip)!=null?$e:!1,g=(Me=t.size)!=null?Me:"40px",c=t.backgroundColor,m=t.textColor,x=S("div","persona-send-button-wrapper"),C=Mt("button",{className:ts("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!c&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?g:void 0,height:r?g:void 0,minWidth:r?g:void 0,minHeight:r?g:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:r&&c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),R=null,M=null;if(r){let Ie=parseFloat(g)||24,qe=(m==null?void 0:m.trim())||"currentColor";n?(R=be(n,Ie,qe,2),R?C.appendChild(R):C.textContent=o):C.textContent=o,M=be(a,Ie,qe,2)}else C.textContent=p;let A=null;u&&s&&(A=S("div","persona-send-button-tooltip"),A.textContent=s,x.appendChild(A)),C.setAttribute("aria-label",s),x.appendChild(C);let L="send";return{button:C,wrapper:x,setMode:Ie=>{if(Ie===L)return;L=Ie;let qe=Ie==="stop"?i:s;if(C.setAttribute("aria-label",qe),A&&(A.textContent=qe),r){if(R&&M){let Ee=Ie==="stop"?M:R;C.replaceChildren(Ee)}}else C.textContent=Ie==="stop"?d:p}}},Vi=e=>{var A,L,y,w,b,T,I,P,k,N,U,Y;let t=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((L=t.provider)==null?void 0:L.type)==="runtype";if(!(o||n))return null;let s=(w=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?w:"40px",i=(b=t.iconName)!=null?b:"mic",p=(T=t.iconSize)!=null?T:s,d=parseFloat(p)||24,u=(P=t.backgroundColor)!=null?P:(I=e==null?void 0:e.sendButton)==null?void 0:I.backgroundColor,g=(N=t.iconColor)!=null?N:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor,c=S("div","persona-send-button-wrapper"),m=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=be(i,d,g||"currentColor",1.5);C?m.appendChild(C):m.textContent="\u{1F3A4}",c.appendChild(m);let R=(U=t.tooltipText)!=null?U:"Start voice recognition";if(((Y=t.showTooltip)!=null?Y:!1)&&R){let he=S("div","persona-send-button-tooltip");he.textContent=R,c.appendChild(he)}return{button:m,wrapper:c}},zi=e=>{var x,C,R,M,A,L,y,w;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(R=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?R:"40px",o=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=S("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((M=t.allowedTypes)!=null?M:Yo).join(","),n.multiple=((A=t.maxFiles)!=null?A:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(L=t.buttonIconName)!=null?L:"paperclip",s=r,i=parseFloat(s)||40,p=Math.round(i*.6),d=S("div","persona-send-button-wrapper"),u=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let g=be(a,p,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",b=>{b.preventDefault(),n.click()}),d.appendChild(u);let c=(w=t.buttonTooltipText)!=null?w:"Attach file",m=S("div","persona-send-button-tooltip");return m.textContent=c,d.appendChild(m),{button:u,wrapper:d,input:n,previewsContainer:o}},$i=e=>{var s,i,p;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=S("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(p=t.idleText)!=null?p:"Online";if(t.idleLink){let d=S("a");d.href=t.idleLink,d.target="_blank",d.rel="noopener noreferrer",d.textContent=a,d.style.color="inherit",d.style.textDecoration="none",o.appendChild(d)}else o.textContent=a;return o},ji=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Wa=e=>{var x,C,R,M,A,L;let{config:t}=e,r=Mt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=ji(),n=Mt("form",{className:"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",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=Ui(t);s();let i=qi(t),p=Vi(t),d=zi(t),u=$i(t);d&&(d.previewsContainer.style.gap="8px",n.append(d.previewsContainer,d.input)),n.append(a);let g=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),c=S("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=S("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&c.append(d.wrapper),p&&m.append(p.wrapper),m.append(i.wrapper),g.append(c,m),n.append(g),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(p==null?void 0:p.button)&&y.target!==(p==null?void 0:p.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),r.append(o,n,u),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=p==null?void 0:p.button)!=null?x:null,micButtonWrapper:(C=p==null?void 0:p.wrapper)!=null?C:null,statusText:u,attachmentButton:(R=d==null?void 0:d.button)!=null?R:null,attachmentButtonWrapper:(M=d==null?void 0:d.wrapper)!=null?M:null,attachmentInput:(A=d==null?void 0:d.input)!=null?A:null,attachmentPreviewsContainer:(L=d==null?void 0:d.previewsContainer)!=null?L:null,actionsRow:g,leftActions:c,rightActions:m,setSendButtonMode:i.setMode}};var mh=()=>{let e=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=S("span","persona-pill-peek__icon"),r=be("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=S("span","persona-pill-peek__text"),n=S("span","persona-pill-peek__caret"),a=be("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},gh=e=>{var x,C,R,M,A,L;let{config:t}=e,r=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ji();o.style.display="none";let n=$i(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=Ui(t);a.style.maxHeight="100px",s();let i=qi(t),p=Vi(t),d=zi(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let u=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=S("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&g.append(d.wrapper);let c=S("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&c.append(p.wrapper),c.append(i.wrapper),u.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(p==null?void 0:p.button)&&y.target!==(p==null?void 0:p.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),d&&u.append(d.input),u.append(g,a,c),d&&r.append(d.previewsContainer),r.append(u,o,n);let m=u;return{footer:r,suggestions:o,composerForm:u,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=p==null?void 0:p.button)!=null?x:null,micButtonWrapper:(C=p==null?void 0:p.wrapper)!=null?C:null,statusText:n,attachmentButton:(R=d==null?void 0:d.button)!=null?R:null,attachmentButtonWrapper:(M=d==null?void 0:d.wrapper)!=null?M:null,attachmentInput:(A=d==null?void 0:d.input)!=null?A:null,attachmentPreviewsContainer:(L=d==null?void 0:d.previewsContainer)!=null?L:null,actionsRow:m,leftActions:g,rightActions:c,setSendButtonMode:i.setMode}};var hh=e=>{var u,g,c,m,x,C,R,M,A,L,y,w,b,T,I,P,k;let t=(g=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?g:!0,r=nr(e);if(En(e)){let N=(m=(c=e==null?void 0:e.launcher)==null?void 0:c.composerBar)!=null?m:{},U=S("div","persona-widget-wrapper persona-fixed persona-transition");U.setAttribute("data-persona-composer-bar",""),U.dataset.state="collapsed",U.dataset.expandedSize=(x=N.expandedSize)!=null?x:"anchored",U.style.zIndex=String((R=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?R:Sr);let Y=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Y.style.width="100%",U.appendChild(Y);let he=S("div","persona-widget-pill-root");return he.setAttribute("data-persona-composer-bar",""),he.dataset.state="collapsed",he.dataset.expandedSize=(M=N.expandedSize)!=null?M:"anchored",he.style.zIndex=String((L=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?L:Sr),{wrapper:U,panel:Y,pillRoot:he}}if(r){let N=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),U=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(U),{wrapper:N,panel:U}}if(!t){let N=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),U=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Y=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?w:"100%";return N.style.width=Y,U.style.width="100%",N.appendChild(U),{wrapper:N,panel:U}}let n=(b=e==null?void 0:e.launcher)!=null?b:{},a=n.position&&vo[n.position]?vo[n.position]:vo["bottom-right"],s=S("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((I=(T=e==null?void 0:e.launcher)==null?void 0:T.zIndex)!=null?I:Sr);let i=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=(k=(P=e==null?void 0:e.launcher)==null?void 0:P.width)!=null?k:e==null?void 0:e.launcherWidth,d=p!=null?p:Yr;return i.style.width=d,i.style.maxWidth=d,s.appendChild(i),{wrapper:s,panel:i}},Tb=(e,t)=>{var y,w,b,T,I,P,k,N,U;let r=S("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=Fi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(b=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:w.enabled)!=null?b:!0,s=null,i=null;if(a){let Y=Ni(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=Y.button,i=Y.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Mt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let u=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(I=(T=e==null?void 0:e.copy)==null?void 0:T.welcomeTitle)!=null?I:"Hello \u{1F44B}"}),g=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),c=Mt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,g),m=S("div","persona-flex persona-flex-col persona-gap-3"),x=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((U=e==null?void 0:e.copy)==null?void 0:U.showWelcomeCard)!==!1||(c.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(c,m);let R=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),M=gh({config:e}),{root:A,textNode:L}=mh();return r.append(p,n,d,R),i&&r.appendChild(i),{container:r,body:d,messagesWrapper:m,composerOverlay:R,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:u,introSubtitle:g,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("span"),header:p,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,peekBanner:A,peekTextNode:L}},xh=(e,t=!0)=>{var R,M,A,L,y,w,b,T,I;if(En(e))return Tb(e,t);let r=Mt("div",{className:"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",attrs:{"data-persona-theme-zone":"container"}}),o=(R=e==null?void 0:e.layout)==null?void 0:R.header,n=((M=e==null?void 0:e.layout)==null?void 0:M.showHeader)!==!1,a=o?Ia(e,o,{showClose:t}):en({config:e,showClose:t}),s=Mt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let i=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(L=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?L:"Hello \u{1F44B}"}),p=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(w=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?w:"Ask anything about your account or products."}),d=Mt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:nr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,p),u=S("div","persona-flex persona-flex-col persona-gap-3"),g=(b=e==null?void 0:e.layout)==null?void 0:b.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((T=e==null?void 0:e.copy)==null?void 0:T.showWelcomeCard)!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,u);let m=Wa({config:e}),x=((I=e==null?void 0:e.layout)==null?void 0:I.showFooter)!==!1;n?ta(r,a,e):(a.header.style.display="none",ta(r,a,e)),r.append(s);let C=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return x||(m.footer.style.display="none"),r.append(m.footer),r.append(C),{container:r,body:s,messagesWrapper:u,composerOverlay:C,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:i,introSubtitle:p,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.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 Qp=(e,t)=>{let r=S("button");r.type="button",r.innerHTML=`
19
+ _Details: ${r.message}_`:o}var ys=e=>({isError:!0,content:[{type:"text",text:e}]}),Zg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,eh=e=>vn(e)||e===wo,Ha=class{constructor(t={},r){this.config=t;this.callbacks=r;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.readAloud=new ea(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,l,p,f;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall,m=!!(u!=null&&u.name)&&(vn(u.name)||u.name===wo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.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:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(f=(p=this.callbacks).onError)==null||f.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Qn(t),this.wireDefaultWebMcpConfirm();for(let a of(n=t.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,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),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var n,a,s,i,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let r=(n=t.host)!=null?n:this.config.apiUrl,o=(c=t.agentId)!=null?c:(i=(s=(a=this.config.voiceRecognition)==null?void 0:a.provider)==null?void 0:s.runtype)==null?void 0:i.agentId;!r||!o||!this.config.clientToken||ql().catch(()=>{})}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,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=En.isSupported()?new En({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(o=t.host)!=null?o:this.config.apiUrl,l=(i=t.agentId)!=null?i:(s=(a=(n=this.config.voiceRecognition)==null?void 0:n.provider)==null?void 0:a.runtype)==null?void 0:s.agentId,p=this.config.clientToken,f=t.browserFallback!==!1;if(c&&l&&p)return ql().then(({RuntypeSpeechEngine:u,FallbackSpeechEngine:m})=>{let x=new u({host:c,agentId:l,clientToken:p,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&r?new m(x,r,{onFallback:b=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${b.message}`)}):x});if(f&&r)return p&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),r}return r}setupVoice(t){var r,o;try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Tn(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,c,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:c,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,l;(l=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||l.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,l;this.voiceStatus=i,this.voiceActive=i==="listening",(l=(c=this.callbacks).onVoiceStatusChanged)==null||l.call(c,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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 r,o,n,a,s,i,c,l,p,f;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:(a=(n=t.runtype)==null?void 0:n.clientToken)!=null?a:this.config.clientToken,host:(i=(s=t.runtype)==null?void 0:s.host)!=null?i:this.config.apiUrl,voiceId:(c=t.runtype)==null?void 0:c.voiceId,createPlaybackEngine:(l=t.runtype)==null?void 0:l.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((p=t.browser)==null?void 0:p.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(r=(t=this.callbacks).onError)==null||r.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}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,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r={...this.config,...t};if(!bb(this.config,r)){this.config=r,this.client.updateConfig(r);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=r,this.client=new Qn(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:l=!1,voiceProcessing:p,rawContent:f}=t,m={id:s!=null?s:r==="user"?Ra():r==="assistant"?Yn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:l,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...f!==void 0&&{rawContent:f}};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 r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:l,sequence:p,streaming:f=!1,voiceProcessing:u,rawContent:m}=o,b={id:c!=null?c:n==="user"?Ra():n==="assistant"?Yn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:f,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};r.push(b)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,l={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var l,p,f,u,m;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let n=Ra(),a=Yn(),s={id:n,role:"user",content:o||ui,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(x){let b=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!b){let L=Yg(x,this.config.errorMessage);if(L){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:L,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(x instanceof Error?(f=(p=this.callbacks).onError)==null||f.call(p,x):(m=(u=this.callbacks).onError)==null||m.call(u,new Error(String(x))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort();let t=Yn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.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 f=Yg(l,this.config.errorMessage);if(f){let u={id:t,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,l):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(l))))}}async connectStream(t,r){var n,a,s;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(n=this.abortController)==null||n.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,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(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var p,f,u,m,x;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(b=>b.id===n),i={id:n,role:"assistant",content:"",createdAt:(p=s==null?void 0:s.createdAt)!=null?p:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,l=c&&typeof c=="object"?c.onDecision:void 0;try{let b;if(l?b=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):b=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),b){let L=null;if(b instanceof Response){if(!b.ok){let E=await b.json().catch(()=>null);throw new Error((u=E==null?void 0:E.error)!=null?u:`Approval request failed: ${b.status}`)}L=b.body}else b instanceof ReadableStream&&(L=b);L?await this.connectStream(L,{allowReentry:!0}):(r==="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(b){let L=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,L||(x=(m=this.callbacks).onError)==null||x.call(m,b instanceof Error?b:new Error(String(b)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var p,f,u,m,x,b,L,E,A,T,y,S;let o=this.messages.find(v=>v.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let n=(f=t.agentMetadata)==null?void 0:f.executionId,a=(u=t.toolCall)==null?void 0:u.name;if(!n||!a){(x=(m=this.callbacks).onError)==null||x.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let v=(b=t.toolCall)==null?void 0:b.args,M=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(M.length===1){let I=typeof((L=M[0])==null?void 0:L.question)=="string"?M[0].question:"";I&&(s={[I]:r})}}this.markAskUserQuestionResolved(t,s),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(A=t.toolCall)==null?void 0:A.args,l=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(l.length===0){let v=typeof r=="string"?r:Object.entries(r).map(([M,I])=>`${M}: ${Array.isArray(I)?I.join(", "):I}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=s!=null?s:{};l.forEach((M,I)=>{let H=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!H)return;let R=v[H],D=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${I}`,role:"assistant",content:H,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${I}`,role:"user",content:D||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(n,{[a]:r});if(!v.ok){let M=await v.json().catch(()=>null);throw new Error((T=M==null?void 0:M.error)!=null?T:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(S=(y=this.callbacks).onError)==null||S.call(y,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==wo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,l,p,f;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async u=>{var S,v,M,I,H,R,D;let m=(S=u.toolCall)==null?void 0:S.name,x=(v=u.toolCall)==null?void 0:v.id;if(!m||!x)return null;let b=`${t}:${x}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(b),o.push(b);let L=this.markWebMcpToolRunning(u),E=(I=(M=u.agentMetadata)==null?void 0:M.webMcpToolCallId)!=null?I:m;if(m===wo)return{dedupeKey:b,resumeKey:E,output:Wl(),toolMessage:u,startedAt:L,completedAt:Date.now()};let A=new AbortController;this.webMcpResolveControllers.add(A),n.push(A);let T=this.client.executeWebMcpToolCall(m,(H=u.toolCall)==null?void 0:H.args,A.signal),y;if(!T)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await T}catch(O){let Q=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Q||(D=(R=this.callbacks).onError)==null||D.call(R,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(u,ys(Q?"Aborted by cancel()":Zg(O)),L),this.webMcpInflightKeys.delete(b),null}return A.signal.aborted?(this.markWebMcpToolComplete(u,ys("Aborted by cancel()"),L),this.webMcpInflightKeys.delete(b),null):{dedupeKey:b,resumeKey:E,output:y,toolMessage:u,startedAt:L,completedAt:Date.now()}})),i=[];try{if(i=s.filter(x=>x!==null),i.length===0)return;let u={};for(let x of i)u[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,u,{signal:a.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((c=x==null?void 0:x.error)!=null?c:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((l=x.toolMessage.toolCall)==null?void 0:l.name)===wo?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(p=this.callbacks).onError)==null||f.call(p,u instanceof Error?u:new Error(String(u)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,ys("Aborted by cancel()"),x.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of n)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,b,L,E,A,T,y,S,v,M,I,H;let r=(x=t.agentMetadata)==null?void 0:x.executionId,o=(b=t.toolCall)==null?void 0:b.name,n=(L=t.toolCall)==null?void 0:L.id;if(!r){(A=(E=this.callbacks).onError)==null||A.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let R=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(r,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch(D){(y=(T=this.callbacks).onError)==null||y.call(T,D instanceof Error?D:new Error(String(D)))}finally{this.webMcpInflightKeys.delete(R)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let l=o===wo,p=(S=t.toolCall)==null?void 0:S.args,f=l?null:this.client.executeWebMcpToolCall(o,p,c),u="execute",m=s;try{let R;if(l?R=Wl():f?R=await f:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),c.aborted){this.markWebMcpToolComplete(t,ys("Aborted by cancel()"),s);return}let D=(M=(v=t.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?M:o;u="resume",await this.resumeWithToolOutput(r,D,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,R,s,m,l?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(R){let D=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(u==="execute"||D||c.aborted)&&this.markWebMcpToolComplete(t,ys(D||c.aborted?"Aborted by cancel()":Zg(R)),s),D||(H=(I=this.callbacks).onError)==null||H.call(I,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,o,n){var s,i;let a=await this.client.resumeFlow(t,{[r]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let c=await a.json().catch(()=>null);throw new Error((s=c==null?void 0:c.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),a.body?await this.connectStream(a.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 n;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}let o={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(n=t.props)!=null?n:{}};return this.artifacts.set(r,o),this.selectedArtifactId=r,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,o;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:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!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 o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let n=_l(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ia(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=_l(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var p,f,u,m,x,b,L,E,A,T,y,S,v,M,I;if(a!==o)return n;let s={...n,...r};if(((p=n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=n.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(u=s.agentMetadata)!=null?u:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let H=n.approval,R=r.approval;s.approval={...H,...R,executionId:R.executionId||H.executionId,toolName:R.toolName||H.toolName,description:R.description||H.description,toolType:(m=R.toolType)!=null?m:H.toolType,reason:(x=R.reason)!=null?x:H.reason,parameters:(b=R.parameters)!=null?b:H.parameters}}let i=(L=r.toolCall)==null?void 0:L.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,l=(A=r.toolCall)==null?void 0:A.id;if(i&&eh(i)&&c&&l&&((T=r.agentMetadata)==null?void 0:T.awaitingLocalTool)===!0){let H=`${c}:${l}`,R=this.webMcpInflightKeys.has(H),D=this.webMcpResolvedKeys.has(H),O=(y=n.toolCall)==null?void 0:y.name,Q=((S=n.agentMetadata)==null?void 0:S.executionId)===c&&((v=n.toolCall)==null?void 0:v.id)===l&&O!==void 0&&eh(O)&&((M=n.toolCall)==null?void 0:M.status)==="complete";(R||D||Q)&&(s.agentMetadata={...(I=s.agentMetadata)!=null?I:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),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((r,o)=>{var c,l;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(l=o.sequence)!=null?l:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var Vl=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var zl=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var $l=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var jl=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var Gl=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Kl=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Xl=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var Jl=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var Ql=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var Yl=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var Zl=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var ed=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var td=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var rd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var od=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var nd=[["path",{d:"M20 6 9 17l-5-5"}]];var ad=[["path",{d:"m6 9 6 6 6-6"}]];var sd=[["path",{d:"m15 18-6-6 6-6"}]];var id=[["path",{d:"m9 18 6-6-6-6"}]];var ld=[["path",{d:"m18 15-6-6-6 6"}]];var hi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var xi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var dd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var cd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var pd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var ud=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var fd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var md=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var gd=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var yi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var bi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var hd=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var xd=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var yd=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var bd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var vd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Cd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var wd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var Sd=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Ad=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var Md=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Td=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var Ed=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var vi=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var kd=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Ld=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var Pd=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Rd=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Id=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Hd=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Ci=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Wd=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Bd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var Dd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Fd=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var Nd=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var wi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Od=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var _d=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Ud=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var qd=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Vd=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var zd=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var $d=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var jd=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var Gd=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Kd=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Xd=[["path",{d:"M5 12h14"}]];var Jd=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var Qd=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var Yd=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var Zd=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var ec=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var tc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var rc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var oc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var nc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var ac=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var sc=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var ic=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var lc=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var dc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var cc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var pc=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var uc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var fc=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var mc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var gc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Si=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var hc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var xc=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var yc=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var bc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Ai=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var vc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Cc=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var wc=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var Sc=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Ac=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var Mc=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Tc=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Ec=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var kc=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Lc=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Mi=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var Pc=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Rc=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Ic=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Hc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Wc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var Bc=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var Dc=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Fc=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var vb={activity:Vl,"arrow-down":zl,"arrow-up":Kl,"arrow-up-right":Gl,bot:Zl,"chevron-down":ad,"chevron-up":ld,"chevron-right":id,"chevron-left":sd,check:nd,clipboard:cd,"clipboard-copy":dd,copy:ud,file:wd,"file-code":bd,"file-spreadsheet":vd,"file-text":Cd,"image-plus":Wd,loader:Od,"loader-circle":wi,mic:Gd,paperclip:Zd,"refresh-cw":ic,search:cc,send:pc,"shield-alert":mc,"shield-check":gc,"shield-x":Si,square:vc,"thumbs-down":Mc,"thumbs-up":Tc,upload:Rc,"volume-2":Hc,x:Dc,user:Ic,mail:Ud,phone:oc,calendar:rd,clock:pd,building:ed,"map-pin":qd,lock:_d,key:Fd,"credit-card":fd,"at-sign":Xl,hash:Pd,globe:Ld,link:Nd,"circle-check":hi,"circle-x":xi,"triangle-alert":Mi,info:Dd,ban:Jl,shield:hc,"arrow-left":$l,"arrow-right":jl,"external-link":xd,ellipsis:bi,"ellipsis-vertical":yi,menu:zd,house:Ci,plus:ac,minus:Xd,pencil:tc,trash:Lc,"trash-2":kc,save:dc,download:gd,share:fc,funnel:vi,settings:uc,"rotate-cw":lc,maximize:Vd,minimize:Kd,"shopping-cart":yc,"shopping-bag":xc,package:Yd,truck:Pc,tag:Ac,gift:kd,receipt:sc,wallet:Bc,store:wc,"dollar-sign":md,percent:rc,play:nc,pause:ec,"volume-x":Wc,camera:od,image:Bd,film:Ad,headphones:Rd,"message-circle":$d,"message-square":jd,bell:Ql,heart:Id,star:Cc,eye:yd,"eye-off":hd,bookmark:Yl,"calendar-days":td,history:Hd,timer:Ec,folder:Ed,"folder-open":Td,files:Sd,sparkles:Ai,zap:Fc,sun:Sc,moon:Qd,flag:Md,monitor:Jd,smartphone:bc},fe=(e,t=24,r="currentColor",o=2)=>{let n=vb[e];return n?Cb(n,t,r,o):(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 Cb(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&c.setAttribute(l,String(p))}),n.appendChild(c)}),n}var Ti={allowedTypes:en,maxFileSize:10*1024*1024,maxFiles:4};function wb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Sb(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 ta=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ti.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ti.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n: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 r,o,n,a,s,i,c;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,l,"count");continue}let p=Gg(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let f=(n=p.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,f);continue}try{let f=await jg(l),u=fi(l)?URL.createObjectURL(l):null,m={id:wb(),file:l,previewUrl:u,contentPart:f};this.attachments.push(m),this.renderPreview(m)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=fi(t.file),o=C("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",r&&t.previewUrl){let s=C("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=C("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=Sb(t.file.type),c=fe(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let l=C("span");l.textContent=Kg(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",s.appendChild(l),o.appendChild(s)}let n=C("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=fe("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){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:r})}};var th=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bs(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];th(a)&&th(n)?r[o]=bs(a,n):r[o]=n}return r}var Zr="min(440px, calc(100vw - 24px))",Ei="440px",Ab={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:Zr,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)"},Bt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Ab,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 rh(e,t){if(!(!e&&!t))return e?t?bs(e,t):e:t}function ki(e){var t,r,o,n,a,s,i,c,l,p,f,u,m,x,b,L,E,A,T,y,S;return e?{...Bt,...e,theme:rh(Bt.theme,e.theme),darkTheme:rh(Bt.darkTheme,e.darkTheme),launcher:{...Bt.launcher,...e.launcher,dock:{...(t=Bt.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=Bt.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{...Bt.copy,...e.copy},sendButton:{...Bt.sendButton,...e.sendButton},statusIndicator:{...Bt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Bt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ae,se,pe,ze,_e,K,J,Se,Y,ie;let v=(ae=Bt.features)==null?void 0:ae.artifacts,M=(se=e.features)==null?void 0:se.artifacts,I=(pe=Bt.features)==null?void 0:pe.scrollToBottom,H=(ze=e.features)==null?void 0:ze.scrollToBottom,R=(_e=Bt.features)==null?void 0:_e.scrollBehavior,D=(K=e.features)==null?void 0:K.scrollBehavior,O=(J=Bt.features)==null?void 0:J.streamAnimation,Q=(Se=e.features)==null?void 0:Se.streamAnimation,me=(Y=Bt.features)==null?void 0:Y.askUserQuestion,ce=(ie=e.features)==null?void 0:ie.askUserQuestion,ee=v===void 0&&M===void 0?void 0:{...v,...M,layout:{...v==null?void 0:v.layout,...M==null?void 0:M.layout}},Ce=I===void 0&&H===void 0?void 0:{...I,...H},Ie=R===void 0&&D===void 0?void 0:{...R,...D},le=O===void 0&&Q===void 0?void 0:{...O,...Q},ve=me===void 0&&ce===void 0?void 0:{...me,...ce,styles:{...me==null?void 0:me.styles,...ce==null?void 0:ce.styles}};return{...Bt.features,...e.features,...Ce!==void 0?{scrollToBottom:Ce}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...ee!==void 0?{artifacts:ee}:{},...le!==void 0?{streamAnimation:le}:{},...ve!==void 0?{askUserQuestion:ve}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:Bt.suggestionChips,suggestionChipsConfig:{...Bt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Bt.layout,...e.layout,header:{...(s=Bt.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=Bt.layout)==null?void 0:c.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(f=(p=Bt.layout)==null?void 0:p.messages)==null?void 0:f.avatar,...(m=(u=e.layout)==null?void 0:u.messages)==null?void 0:m.avatar},timestamp:{...(b=(x=Bt.layout)==null?void 0:x.messages)==null?void 0:b.timestamp,...(E=(L=e.layout)==null?void 0:L.messages)==null?void 0:E.timestamp}},slots:{...(A=Bt.layout)==null?void 0:A.slots,...(T=e.layout)==null?void 0:T.slots}},markdown:{...Bt.markdown,...e.markdown,options:{...(y=Bt.markdown)==null?void 0:y.options,...(S=e.markdown)==null?void 0:S.options}},messageActions:{...Bt.messageActions,...e.messageActions}}:Bt}var Nc={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"}},Oc={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"}},_c={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:Zr,maxWidth:Ei,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"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:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",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 Wa(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Wa(e,o):o}function Li(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let c=Wa(e,s);c!==void 0&&(t[i]={path:i,value:c,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Uc(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:r}}function oh(e,t){let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?r[o]=oh(a,n):r[o]=n}return r}function Mb(e,t){return t?oh(e,t):e}function Ba(e,t={}){var n,a,s,i,c,l,p,f,u,m,x,b,L;let r={palette:Nc,semantic:Oc,components:_c},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(u=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...r.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(b=e==null?void 0:e.semantic)==null?void 0:b.spacing},typography:{...r.semantic.typography,...(L=e==null?void 0:e.semantic)==null?void 0:L.typography}},components:Mb(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=Uc(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Pi(e){var b,L,E,A,T,y,S,v,M,I,H,R,D,O,Q,me,ce,ee,Ce,Ie,le,ve,ae,se,pe,ze,_e,K,J,Se,Y,ie,Re,rt,bt,qt,Gt,at,Ne,G,je,$e,ye,we,Qe,Xe,Ae,Oe,fr,Dt,Yt,Uo,F,j,de,He,Ue,We,Ee,st,Pt,gt,Rt,W,ne,Me,Mt,Ye,Vt,br,xt,yt,It,vt,mr,_t,Ur,Er,kr,Cr,Lr,fo,Ct,Ao,Mo,qo,mo,ct,Hn,To,Wn,Fr,ca,nn,Vo,an,sn,Bn,Dn,ln,ht,qr,Vr,Pr,wt,ro,oo,zr,dn,zo,cn,$r,Ht,Rr,no,pn,$o,un;let t=Li(e),r={};for(let[he,Nr]of Object.entries(t)){let Eo=he.replace(/\./g,"-");r[`--persona-${Eo}`]=Nr.value}r["--persona-primary"]=(b=r["--persona-semantic-colors-primary"])!=null?b:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(L=r["--persona-semantic-colors-secondary"])!=null?L:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(E=r["--persona-semantic-colors-accent"])!=null?E:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(A=r["--persona-semantic-colors-surface"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(T=r["--persona-semantic-colors-background"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(S=r["--persona-semantic-colors-text"])!=null?S:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(v=r["--persona-semantic-colors-text-muted"])!=null?v:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(M=r["--persona-semantic-colors-text-inverse"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(I=r["--persona-semantic-colors-border"])!=null?I:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(H=r["--persona-semantic-colors-divider"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(R=r["--persona-components-voice-recording-indicator"])!=null?R:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(D=r["--persona-components-voice-recording-background"])!=null?D:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(O=r["--persona-components-voice-processing-icon"])!=null?O:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Q=r["--persona-components-voice-speaking-icon"])!=null?Q:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-surface"],r["--persona-approval-border"]=(ce=r["--persona-components-approval-requested-border"])!=null?ce:r["--persona-border"],r["--persona-approval-text"]=(ee=r["--persona-components-approval-requested-text"])!=null?ee:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Ce=r["--persona-components-approval-requested-shadow"])!=null?Ce:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",r["--persona-approval-approve-bg"]=(Ie=r["--persona-components-approval-approve-background"])!=null?Ie:r["--persona-button-primary-bg"],r["--persona-approval-deny-bg"]=(le=r["--persona-components-approval-deny-background"])!=null?le:r["--persona-container"],r["--persona-attachment-image-bg"]=(ve=r["--persona-components-attachment-image-background"])!=null?ve:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(ae=r["--persona-components-attachment-image-border"])!=null?ae:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(se=r["--persona-semantic-typography-fontFamily"])!=null?se:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(pe=r["--persona-semantic-typography-fontSize"])!=null?pe:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(ze=r["--persona-semantic-typography-fontWeight"])!=null?ze:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(_e=r["--persona-semantic-typography-lineHeight"])!=null?_e:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(K=r["--persona-palette-radius-sm"])!=null?K:"0.125rem",r["--persona-radius-md"]=(J=r["--persona-palette-radius-md"])!=null?J:"0.375rem",r["--persona-radius-lg"]=(Se=r["--persona-palette-radius-lg"])!=null?Se:"0.5rem",r["--persona-radius-xl"]=(Y=r["--persona-palette-radius-xl"])!=null?Y:"0.75rem",r["--persona-radius-full"]=(ie=r["--persona-palette-radius-full"])!=null?ie:"9999px",r["--persona-launcher-radius"]=(rt=(Re=r["--persona-components-launcher-borderRadius"])!=null?Re:r["--persona-palette-radius-full"])!=null?rt:"9999px",r["--persona-launcher-bg"]=(bt=r["--persona-components-launcher-background"])!=null?bt:r["--persona-primary"],r["--persona-launcher-fg"]=(qt=r["--persona-components-launcher-foreground"])!=null?qt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(Gt=r["--persona-components-launcher-border"])!=null?Gt:r["--persona-border"],r["--persona-button-primary-bg"]=(at=r["--persona-components-button-primary-background"])!=null?at:r["--persona-primary"],r["--persona-button-primary-fg"]=(Ne=r["--persona-components-button-primary-foreground"])!=null?Ne:r["--persona-text-inverse"],r["--persona-button-radius"]=(je=(G=r["--persona-components-button-primary-borderRadius"])!=null?G:r["--persona-palette-radius-full"])!=null?je:"9999px",r["--persona-panel-radius"]=(ye=($e=r["--persona-components-panel-borderRadius"])!=null?$e:r["--persona-radius-xl"])!=null?ye:"0.75rem",r["--persona-panel-border"]=(we=r["--persona-components-panel-border"])!=null?we:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Xe=(Qe=r["--persona-components-panel-shadow"])!=null?Qe:r["--persona-palette-shadows-xl"])!=null?Xe:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(Ae=r["--persona-components-launcher-shadow"])!=null?Ae:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(fr=(Oe=r["--persona-components-input-borderRadius"])!=null?Oe:r["--persona-radius-lg"])!=null?fr:"0.5rem",r["--persona-message-user-radius"]=(Yt=(Dt=r["--persona-components-message-user-borderRadius"])!=null?Dt:r["--persona-radius-lg"])!=null?Yt:"0.5rem",r["--persona-message-assistant-radius"]=(F=(Uo=r["--persona-components-message-assistant-borderRadius"])!=null?Uo:r["--persona-radius-lg"])!=null?F:"0.5rem",r["--persona-header-bg"]=(j=r["--persona-components-header-background"])!=null?j:r["--persona-surface"],r["--persona-header-border"]=(de=r["--persona-components-header-border"])!=null?de:r["--persona-divider"],r["--persona-header-icon-bg"]=(He=r["--persona-components-header-iconBackground"])!=null?He:r["--persona-primary"],r["--persona-header-icon-fg"]=(Ue=r["--persona-components-header-iconForeground"])!=null?Ue:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(We=r["--persona-components-header-titleForeground"])!=null?We:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Ee=r["--persona-components-header-subtitleForeground"])!=null?Ee:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(st=r["--persona-components-header-actionIconForeground"])!=null?st:r["--persona-muted"];let o=(Pt=e.components)==null?void 0:Pt.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(gt=e.components)==null?void 0:gt.introCard;r["--persona-intro-card-bg"]=(Rt=r["--persona-components-introCard-background"])!=null?Rt:r["--persona-surface"],r["--persona-intro-card-radius"]=(W=r["--persona-components-introCard-borderRadius"])!=null?W:"1rem",r["--persona-intro-card-padding"]=(ne=r["--persona-components-introCard-padding"])!=null?ne:"1.5rem",r["--persona-intro-card-shadow"]=(Mt=(Me=n==null?void 0:n.shadow)!=null?Me:r["--persona-components-introCard-shadow"])!=null?Mt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Ye=r["--persona-components-input-background"])!=null?Ye:r["--persona-surface"],r["--persona-input-placeholder"]=(Vt=r["--persona-components-input-placeholder"])!=null?Vt:r["--persona-text-muted"],r["--persona-message-user-bg"]=(br=r["--persona-components-message-user-background"])!=null?br:r["--persona-accent"],r["--persona-message-user-text"]=(xt=r["--persona-components-message-user-text"])!=null?xt:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(yt=r["--persona-components-message-user-shadow"])!=null?yt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(It=r["--persona-components-message-assistant-background"])!=null?It:r["--persona-surface"],r["--persona-message-assistant-text"]=(vt=r["--persona-components-message-assistant-text"])!=null?vt:r["--persona-text"],r["--persona-message-assistant-border"]=(mr=r["--persona-components-message-assistant-border"])!=null?mr:r["--persona-border"],r["--persona-message-assistant-shadow"]=(_t=r["--persona-components-message-assistant-shadow"])!=null?_t:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(Er=(Ur=r["--persona-components-scrollToBottom-background"])!=null?Ur:r["--persona-button-primary-bg"])!=null?Er:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(Cr=(kr=r["--persona-components-scrollToBottom-foreground"])!=null?kr:r["--persona-button-primary-fg"])!=null?Cr:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(Lr=r["--persona-components-scrollToBottom-border"])!=null?Lr:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(fo=r["--persona-components-scrollToBottom-size"])!=null?fo:"40px",r["--persona-scroll-to-bottom-radius"]=(Mo=(Ao=(Ct=r["--persona-components-scrollToBottom-borderRadius"])!=null?Ct:r["--persona-button-radius"])!=null?Ao:r["--persona-radius-full"])!=null?Mo:"9999px",r["--persona-scroll-to-bottom-shadow"]=(mo=(qo=r["--persona-components-scrollToBottom-shadow"])!=null?qo:r["--persona-palette-shadows-sm"])!=null?mo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(ct=r["--persona-components-scrollToBottom-padding"])!=null?ct:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(Hn=r["--persona-components-scrollToBottom-gap"])!=null?Hn:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(Wn=(To=r["--persona-components-scrollToBottom-fontSize"])!=null?To:r["--persona-palette-typography-fontSize-sm"])!=null?Wn:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(Fr=r["--persona-components-scrollToBottom-iconSize"])!=null?Fr:"14px",r["--persona-tool-bubble-shadow"]=(ca=r["--persona-components-toolBubble-shadow"])!=null?ca:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(nn=r["--persona-components-reasoningBubble-shadow"])!=null?nn:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Vo=r["--persona-components-composer-shadow"])!=null?Vo:"none",r["--persona-md-inline-code-bg"]=(an=r["--persona-components-markdown-inlineCode-background"])!=null?an:r["--persona-container"],r["--persona-md-inline-code-color"]=(sn=r["--persona-components-markdown-inlineCode-foreground"])!=null?sn:r["--persona-text"],r["--persona-md-link-color"]=(Dn=(Bn=r["--persona-components-markdown-link-foreground"])!=null?Bn:r["--persona-accent"])!=null?Dn:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let l=r["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(r["--persona-md-prose-font-family"]=l),r["--persona-md-code-block-bg"]=(ln=r["--persona-components-markdown-codeBlock-background"])!=null?ln:r["--persona-container"],r["--persona-md-code-block-border-color"]=(ht=r["--persona-components-markdown-codeBlock-borderColor"])!=null?ht:r["--persona-border"],r["--persona-md-code-block-text-color"]=(qr=r["--persona-components-markdown-codeBlock-textColor"])!=null?qr:"inherit",r["--persona-md-table-header-bg"]=(Vr=r["--persona-components-markdown-table-headerBackground"])!=null?Vr:r["--persona-container"],r["--persona-md-table-border-color"]=(Pr=r["--persona-components-markdown-table-borderColor"])!=null?Pr:r["--persona-border"],r["--persona-md-hr-color"]=(wt=r["--persona-components-markdown-hr-color"])!=null?wt:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(ro=r["--persona-components-markdown-blockquote-borderColor"])!=null?ro:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(oo=r["--persona-components-markdown-blockquote-background"])!=null?oo:"transparent",r["--persona-md-blockquote-text-color"]=(zr=r["--persona-components-markdown-blockquote-textColor"])!=null?zr:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(dn=r["--persona-components-collapsibleWidget-container"])!=null?dn:r["--persona-surface"],r["--cw-surface"]=(zo=r["--persona-components-collapsibleWidget-surface"])!=null?zo:r["--persona-surface"],r["--cw-border"]=(cn=r["--persona-components-collapsibleWidget-border"])!=null?cn:r["--persona-border"],r["--persona-message-border"]=($r=r["--persona-components-message-border"])!=null?$r:r["--persona-border"];let p=e.components,f=p==null?void 0:p.iconButton;f&&(f.background&&(r["--persona-icon-btn-bg"]=f.background),f.border&&(r["--persona-icon-btn-border"]=f.border),f.color&&(r["--persona-icon-btn-color"]=f.color),f.padding&&(r["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(r["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(r["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(r["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(r["--persona-icon-btn-active-border"]=f.activeBorder));let u=p==null?void 0:p.labelButton;u&&(u.background&&(r["--persona-label-btn-bg"]=u.background),u.border&&(r["--persona-label-btn-border"]=u.border),u.color&&(r["--persona-label-btn-color"]=u.color),u.padding&&(r["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(r["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(r["--persona-label-btn-gap"]=u.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(r["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(r["--persona-toggle-group-radius"]=m.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let he=x.toolbar;he.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=he.iconHoverColor),he.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=he.iconHoverBackground),he.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=he.iconPadding),he.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=he.iconBorderRadius),he.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=he.iconBorder),he.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=he.toggleGroupGap),he.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=he.toggleBorderRadius),he.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=he.copyBackground),he.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=he.copyBorder),he.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=he.copyColor),he.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=he.copyBorderRadius),he.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=he.copyPadding),he.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=he.copyMenuBackground,r["--persona-dropdown-bg"]=(Ht=r["--persona-dropdown-bg"])!=null?Ht:he.copyMenuBackground),he.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=he.copyMenuBorder,r["--persona-dropdown-border"]=(Rr=r["--persona-dropdown-border"])!=null?Rr:he.copyMenuBorder),he.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=he.copyMenuShadow,r["--persona-dropdown-shadow"]=(no=r["--persona-dropdown-shadow"])!=null?no:he.copyMenuShadow),he.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=he.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(pn=r["--persona-dropdown-radius"])!=null?pn:he.copyMenuBorderRadius),he.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=he.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=($o=r["--persona-dropdown-item-hover-bg"])!=null?$o:he.copyMenuItemHoverBackground),he.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=he.iconBackground),he.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=he.toolbarBorder)}if(x!=null&&x.tab){let he=x.tab;he.background&&(r["--persona-artifact-tab-bg"]=he.background),he.activeBackground&&(r["--persona-artifact-tab-active-bg"]=he.activeBackground),he.activeBorder&&(r["--persona-artifact-tab-active-border"]=he.activeBorder),he.borderRadius&&(r["--persona-artifact-tab-radius"]=he.borderRadius),he.textColor&&(r["--persona-artifact-tab-color"]=he.textColor),he.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=he.hoverBackground),he.listBackground&&(r["--persona-artifact-tab-list-bg"]=he.listBackground),he.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=he.listBorderColor),he.listPadding&&(r["--persona-artifact-tab-list-padding"]=he.listPadding)}if(x!=null&&x.pane){let he=x.pane;if(he.toolbarBackground){let Nr=(un=Wa(e,he.toolbarBackground))!=null?un:he.toolbarBackground;r["--persona-artifact-toolbar-bg"]=Nr}}return r}var nh={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 Tb={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"}}},ah=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},vs=()=>{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"},Eb=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":vs()},qc=e=>Eb(e),kb=e=>Ba(e),Lb=e=>{var r;let t=Ba(void 0,{validate:!1});return Ba({...e,palette:{...t.palette,colors:{...Tb.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Da=e=>{let t=qc(e),r=ah(e==null?void 0:e.theme),o=ah(e==null?void 0:e.darkTheme);return t==="dark"?Lb(bs(r!=null?r:{},o!=null?o:{})):kb(r)},Pb=e=>Pi(e),kn=(e,t)=>{let r=Da(t),o=Pb(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},Ri=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(vs())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(vs());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(r=>r())}};var sh=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:u=>u.getAttribute("im-preserve")==="true",shouldReAppend:u=>u.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(u,m,x={}){u=p(u);let b=f(m),L=l(u,b,x),E=n(L,()=>i(L,u,b,A=>A.morphStyle==="innerHTML"?(a(A,u,b),Array.from(u.childNodes)):o(A,u,b)));return L.pantry.remove(),E}function o(u,m,x){let b=f(m);return a(u,b,x,m,m.nextSibling),Array.from(b.childNodes)}function n(u,m){var T;if(!u.config.restoreFocus)return m();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return m();let{id:b,selectionStart:L,selectionEnd:E}=x,A=m();return b&&b!==((T=document.activeElement)==null?void 0:T.getAttribute("id"))&&(x=u.target.querySelector(`[id="${b}"]`),x==null||x.focus()),x&&!x.selectionEnd&&E&&x.setSelectionRange(L,E),A}let a=(function(){function u(y,S,v,M=null,I=null){S instanceof HTMLTemplateElement&&v instanceof HTMLTemplateElement&&(S=S.content,v=v.content),M||(M=S.firstChild);for(let H of v.childNodes){if(M&&M!=I){let D=x(y,H,M,I);if(D){D!==M&&L(y,M,D),s(D,H,y),M=D.nextSibling;continue}}if(H instanceof Element){let D=H.getAttribute("id");if(y.persistentIds.has(D)){let O=E(S,D,M,y);s(O,H,y),M=O.nextSibling;continue}}let R=m(S,H,M,y);R&&(M=R.nextSibling)}for(;M&&M!=I;){let H=M;M=M.nextSibling,b(y,H)}}function m(y,S,v,M){if(M.callbacks.beforeNodeAdded(S)===!1)return null;if(M.idMap.has(S)){let I=document.createElement(S.tagName);return y.insertBefore(I,v),s(I,S,M),M.callbacks.afterNodeAdded(I),I}else{let I=document.importNode(S,!0);return y.insertBefore(I,v),M.callbacks.afterNodeAdded(I),I}}let x=(function(){function y(M,I,H,R){let D=null,O=I.nextSibling,Q=0,me=H;for(;me&&me!=R;){if(v(me,I)){if(S(M,me,I))return me;D===null&&(M.idMap.has(me)||(D=me))}if(D===null&&O&&v(me,O)&&(Q++,O=O.nextSibling,Q>=2&&(D=void 0)),M.activeElementAndParents.includes(me))break;me=me.nextSibling}return D||null}function S(M,I,H){let R=M.idMap.get(I),D=M.idMap.get(H);if(!D||!R)return!1;for(let O of R)if(D.has(O))return!0;return!1}function v(M,I){var D,O,Q;let H=M,R=I;return H.nodeType===R.nodeType&&H.tagName===R.tagName&&(!((D=H.getAttribute)!=null&&D.call(H,"id"))||((O=H.getAttribute)==null?void 0:O.call(H,"id"))===((Q=R.getAttribute)==null?void 0:Q.call(R,"id")))}return y})();function b(y,S){var v;if(y.idMap.has(S))T(y.pantry,S,null);else{if(y.callbacks.beforeNodeRemoved(S)===!1)return;(v=S.parentNode)==null||v.removeChild(S),y.callbacks.afterNodeRemoved(S)}}function L(y,S,v){let M=S;for(;M&&M!==v;){let I=M;M=M.nextSibling,b(y,I)}return M}function E(y,S,v,M){var H,R;let I=((R=(H=M.target).getAttribute)==null?void 0:R.call(H,"id"))===S&&M.target||M.target.querySelector(`[id="${S}"]`)||M.pantry.querySelector(`[id="${S}"]`);return A(I,M),T(y,I,v),I}function A(y,S){let v=y.getAttribute("id");for(;y=y.parentNode;){let M=S.idMap.get(y);M&&(M.delete(v),M.size||S.idMap.delete(y))}}function T(y,S,v){if(y.moveBefore)try{y.moveBefore(S,v)}catch{y.insertBefore(S,v)}else y.insertBefore(S,v)}return u})(),s=(function(){function u(A,T,y){return y.ignoreActive&&A===document.activeElement?null:(y.callbacks.beforeNodeMorphed(A,T)===!1||(A instanceof HTMLHeadElement&&y.head.ignore||(A instanceof HTMLHeadElement&&y.head.style!=="morph"?c(A,T,y):(m(A,T,y),E(A,y)||a(y,A,T))),y.callbacks.afterNodeMorphed(A,T)),A)}function m(A,T,y){let S=T.nodeType;if(S===1){let v=A,M=T,I=v.attributes,H=M.attributes;for(let R of H)L(R.name,v,"update",y)||v.getAttribute(R.name)!==R.value&&v.setAttribute(R.name,R.value);for(let R=I.length-1;0<=R;R--){let D=I[R];if(D&&!M.hasAttribute(D.name)){if(L(D.name,v,"remove",y))continue;v.removeAttribute(D.name)}}E(v,y)||x(v,M,y)}(S===8||S===3)&&A.nodeValue!==T.nodeValue&&(A.nodeValue=T.nodeValue)}function x(A,T,y){if(A instanceof HTMLInputElement&&T instanceof HTMLInputElement&&T.type!=="file"){let S=T.value,v=A.value;b(A,T,"checked",y),b(A,T,"disabled",y),T.hasAttribute("value")?v!==S&&(L("value",A,"update",y)||(A.setAttribute("value",S),A.value=S)):L("value",A,"remove",y)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&T instanceof HTMLOptionElement)b(A,T,"selected",y);else if(A instanceof HTMLTextAreaElement&&T instanceof HTMLTextAreaElement){let S=T.value,v=A.value;if(L("value",A,"update",y))return;S!==v&&(A.value=S),A.firstChild&&A.firstChild.nodeValue!==S&&(A.firstChild.nodeValue=S)}}function b(A,T,y,S){let v=T[y],M=A[y];if(v!==M){let I=L(y,A,"update",S);I||(A[y]=T[y]),v?I||A.setAttribute(y,""):L(y,A,"remove",S)||A.removeAttribute(y)}}function L(A,T,y,S){return A==="value"&&S.ignoreActiveValue&&T===document.activeElement?!0:S.callbacks.beforeAttributeUpdated(A,T,y)===!1}function E(A,T){return!!T.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return u})();function i(u,m,x,b){if(u.head.block){let L=m.querySelector("head"),E=x.querySelector("head");if(L&&E){let A=c(L,E,u);return Promise.all(A).then(()=>{let T=Object.assign(u,{head:{block:!1,ignore:!0}});return b(T)})}}return b(u)}function c(u,m,x){let b=[],L=[],E=[],A=[],T=new Map;for(let S of m.children)T.set(S.outerHTML,S);for(let S of u.children){let v=T.has(S.outerHTML),M=x.head.shouldReAppend(S),I=x.head.shouldPreserve(S);v||I?M?L.push(S):(T.delete(S.outerHTML),E.push(S)):x.head.style==="append"?M&&(L.push(S),A.push(S)):x.head.shouldRemove(S)!==!1&&L.push(S)}A.push(...T.values());let y=[];for(let S of A){let v=document.createRange().createContextualFragment(S.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(v)!==!1){if("href"in v&&v.href||"src"in v&&v.src){let M,I=new Promise(function(H){M=H});v.addEventListener("load",function(){M()}),y.push(I)}u.appendChild(v),x.callbacks.afterNodeAdded(v),b.push(v)}}for(let S of L)x.callbacks.beforeNodeRemoved(S)!==!1&&(u.removeChild(S),x.callbacks.afterNodeRemoved(S));return x.head.afterHeadMorphed(u,{added:b,kept:E,removed:L}),y}let l=(function(){function u(y,S,v){let{persistentIds:M,idMap:I}=A(y,S),H=m(v),R=H.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(R))throw`Do not understand how to morph style ${R}`;return{target:y,newContent:S,config:H,morphStyle:R,ignoreActive:H.ignoreActive,ignoreActiveValue:H.ignoreActiveValue,restoreFocus:H.restoreFocus,idMap:I,persistentIds:M,pantry:x(),activeElementAndParents:b(y),callbacks:H.callbacks,head:H.head}}function m(y){let S=Object.assign({},t);return Object.assign(S,y),S.callbacks=Object.assign({},t.callbacks,y.callbacks),S.head=Object.assign({},t.head,y.head),S}function x(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function b(y){let S=[],v=document.activeElement;if((v==null?void 0:v.tagName)!=="BODY"&&y.contains(v))for(;v&&(S.push(v),v!==y);)v=v.parentElement;return S}function L(y){var v;let S=Array.from(y.querySelectorAll("[id]"));return(v=y.getAttribute)!=null&&v.call(y,"id")&&S.push(y),S}function E(y,S,v,M){for(let I of M){let H=I.getAttribute("id");if(S.has(H)){let R=I;for(;R;){let D=y.get(R);if(D==null&&(D=new Set,y.set(R,D)),D.add(H),R===v)break;R=R.parentElement}}}}function A(y,S){let v=L(y),M=L(S),I=T(v,M),H=new Map;E(H,I,y,v);let R=S.__idiomorphRoot||S;return E(H,I,R,M),{persistentIds:I,idMap:H}}function T(y,S){let v=new Set,M=new Map;for(let{id:H,tagName:R}of y)M.has(H)?v.add(H):M.set(H,R);let I=new Set;for(let{id:H,tagName:R}of S)I.has(H)?v.add(H):M.get(H)===R&&I.add(H);for(let H of v)I.delete(H);return I}return u})(),{normalizeElement:p,normalizeParent:f}=(function(){let u=new WeakSet;function m(E){return E instanceof Document?E.documentElement:E}function x(E){if(E==null)return document.createElement("div");if(typeof E=="string")return x(L(E));if(u.has(E))return E;if(E instanceof Node){if(E.parentNode)return new b(E);{let A=document.createElement("div");return A.append(E),A}}else{let A=document.createElement("div");for(let T of[...E])A.append(T);return A}}class b{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],T=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;T&&T!=this.nextSibling;)A.push(T),T=T.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((T,y)=>{if(y instanceof Element){y.matches(A)&&T.push(y);let S=y.querySelectorAll(A);for(let v=0;v<S.length;v++)T.push(S[v])}return T},[])}insertBefore(A,T){return this.realParentNode.insertBefore(A,T)}moveBefore(A,T){return this.realParentNode.moveBefore(A,T)}get __idiomorphRoot(){return this.originalNode}}function L(E){let A=new DOMParser,T=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(T.match(/<\/html>/)||T.match(/<\/head>/)||T.match(/<\/body>/)){let y=A.parseFromString(E,"text/html");if(T.match(/<\/html>/))return u.add(y),y;{let S=y.firstChild;return S&&u.add(S),S}}else{let S=A.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return u.add(S),S}}return{normalizeElement:m,normalizeParent:x}})();return{morph:r,defaults:t}})();var Ii=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;sh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",l=(i=a.textContent)!=null?i:"";if(c!==l)return}return!1}}}}})};var ih=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Hi={index:-1,draft:""};function lh(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...Hi}}}function dh(e,t){var r,o,n,a,s,i,c,l,p,f,u,m,x,b,L,E,A,T,y,S,v,M,I,H,R,D,O,Q,me,ce,ee,Ce,Ie,le,ve,ae,se,pe;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(u=(f=e.approval)==null?void 0:f.status)!=null?u:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(L=(b=e.toolCall)==null?void 0:b.name)!=null?L:"",(T=(A=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:A.length)!=null?T:0,(M=(v=(S=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:S[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?M:"",typeof((I=e.toolCall)==null?void 0:I.args)=="string"?e.toolCall.args.length:(H=e.toolCall)!=null&&H.args?JSON.stringify(e.toolCall.args).length:0,(O=(D=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:D.length)!=null?O:0,(ee=(ce=(me=(Q=e.reasoning)==null?void 0:Q.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:ce.length)!=null?ee:0,(ve=(le=(Ie=(Ce=e.reasoning)==null?void 0:Ce.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:le.slice(-32))!=null?ve:"",(se=(ae=e.contentParts)==null?void 0:ae.length)!=null?se:0,(pe=e.stopReason)!=null?pe:"",t].join("\0")}function ch(){return new Map}function ph(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function uh(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function fh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function Wi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function tn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ra(e,t){return tn(e)-e.scrollTop<=t}function Bi(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,p=r-o;return s||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:r}:!t&&n&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function Di(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}function mh(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function gh(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),r=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:r}}function hh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Mr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Tr=1e5,Ln=Tr+1;var Cs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Rb=["pre","code","a","script","style"],Fi=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:Cs.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Cs.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Cs.speed,duration:(n=e==null?void 0:e.duration)!=null?n:Cs.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:Cs.buffer}},yh=[{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"}],ws=new Map;for(let e of yh)ws.set(e.name,e);var oa=e=>{ws.set(e.name,e)},$c=e=>{yh.some(t=>t.name===e)||ws.delete(e)},jc=()=>Array.from(ws.keys()),Ss=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=ws.get(e))!=null?o:null},Ni=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
20
+ `);return a<0?"":e.slice(0,a)}return e},Ib=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},Hb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},Vc=/\s/,Wb=(e,t)=>{let r=e.parentNode;for(;r;){if(r.nodeType===1){let o=r;if(t.has(o.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},Bb=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(Vc.test(a[i])){let l=i;for(;l<a.length&&Vc.test(a[l]);)l+=1;s.appendChild(o.createTextNode(a.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<a.length&&!Vc.test(a[p]);)l.appendChild(Ib(o,a[p],t,r.value)),r.value+=1,p+=1;s.appendChild(l),i=p}n.replaceChild(s,e)},Db=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?s.appendChild(o.createTextNode(l)):(s.appendChild(Hb(o,l,t,r.value)),r.value+=1));n.replaceChild(s,e)},As=(e,t,r,o)=>{var f,u;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((f=o==null?void 0:o.skipTags)!=null?f:Rb).map(m=>m.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)Wb(c,a)||i.push(c),c=s.nextNode();let l={value:(u=o==null?void 0:o.startIndex)!=null?u:0},p=t==="char"?Bb:Db;for(let m of i)p(m,r,l);return n.innerHTML},Oi=(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},Ms=(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 r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},xh=new WeakMap,Fb=(e,t)=>{var a;if(!e.styles)return;let r=xh.get(t);if(r||(r=new Set,xh.set(t,r)),r.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:(a=t.ownerDocument)!=null?a:document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)},zc=new WeakMap,Nb=(e,t)=>{if(!e.onAttach)return;let r=zc.get(t);if(r||(r=new Map,zc.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},bh=e=>{let t=zc.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},Gc=(e,t)=>{Fb(e,t),Nb(e,t)};function Kc(e,t=Tr){let r=e.style.position,o=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=o,e.style.isolation=n}}var Ts=0,Pn=null;function Xc(e=document){var r;if(Ts++,Ts===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Pn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Ts=Math.max(0,Ts-1),Ts===0&&Pn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Pn.originalOverflow,n.style.position=Pn.originalPosition,n.style.top=Pn.originalTop,n.style.width=Pn.originalWidth,a.scrollTo(0,Pn.scrollY),Pn=null}}}var Es={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},sr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Rn=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},eo=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Es.side,width:(n=t==null?void 0:t.width)!=null?n:Es.width,animate:(a=t==null?void 0:t.animate)!=null?a:Es.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:Es.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Es.maxHeight}};var So={"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 Ob="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",_i=(e,t={})=>{var L,E,A,T,y,S;let{showClose:r=!0,wrapperClassName:o=Ob,buttonSize:n,iconSize:a="28px"}=t,s=(L=e==null?void 0:e.launcher)!=null?L:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=C("div",o),l=(A=s.closeButtonTooltipText)!=null?A:"Close chat",p=(T=s.closeButtonShowTooltip)!=null?T:!0,f=(y=s.closeButtonIconName)!=null?y:"x",u=(S=s.closeButtonIconText)!=null?S:"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=At("button",{className:ss("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||Dr.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),b=fe(f,a,"currentColor",1);if(b?(b.style.display="block",x.appendChild(b)):x.textContent=u,c.appendChild(x),p&&l){let v=null,M=()=>{if(v)return;let H=x.ownerDocument,R=H.body;if(!R)return;v=Oo(H,"div","persona-clear-chat-tooltip"),v.textContent=l;let D=Oo(H,"div");D.className="persona-clear-chat-tooltip-arrow",v.appendChild(D);let O=x.getBoundingClientRect();v.style.position="fixed",v.style.zIndex=String(Ln),v.style.left=`${O.left+O.width/2}px`,v.style.top=`${O.top-8}px`,v.style.transform="translate(-50%, -100%)",R.appendChild(v)},I=()=>{v&&v.parentNode&&(v.parentNode.removeChild(v),v=null)};c.addEventListener("mouseenter",M),c.addEventListener("mouseleave",I),x.addEventListener("focus",M),x.addEventListener("blur",I),c._cleanupTooltip=()=>{I(),c.removeEventListener("mouseenter",M),c.removeEventListener("mouseleave",I),x.removeEventListener("focus",M),x.removeEventListener("blur",I)}}return{button:x,wrapper:c}},_b="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ui=(e,t={})=>{var v,M,I,H,R,D,O,Q,me,ce,ee,Ce,Ie;let{wrapperClassName:r=_b,buttonSize:o,iconSize:n="20px"}=t,s=(M=((v=e==null?void 0:e.launcher)!=null?v:{}).clearChat)!=null?M:{},i=(I=o!=null?o:s.size)!=null?I:"32px",c=(H=s.iconName)!=null?H:"refresh-cw",l=(R=s.iconColor)!=null?R:"",p=(D=s.backgroundColor)!=null?D:"",f=(O=s.borderWidth)!=null?O:"",u=(Q=s.borderColor)!=null?Q:"",m=(me=s.borderRadius)!=null?me:"",x=(ce=s.paddingX)!=null?ce:"",b=(ee=s.paddingY)!=null?ee:"",L=(Ce=s.tooltipText)!=null?Ce:"Clear chat",E=(Ie=s.showTooltip)!=null?Ie:!0,A=C("div",r),T=!!(f||u),y=At("button",{className:ss("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":L},style:{height:i,width:i,color:l||Dr.actionIconColor,backgroundColor:p||void 0,border:T?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:b||void 0,paddingBottom:b||void 0}}),S=fe(c,n,"currentColor",1);if(S&&(S.style.display="block",y.appendChild(S)),A.appendChild(y),E&&L){let le=null,ve=()=>{if(le)return;let se=y.ownerDocument,pe=se.body;if(!pe)return;le=Oo(se,"div","persona-clear-chat-tooltip"),le.textContent=L;let ze=Oo(se,"div");ze.className="persona-clear-chat-tooltip-arrow",le.appendChild(ze);let _e=y.getBoundingClientRect();le.style.position="fixed",le.style.zIndex=String(Ln),le.style.left=`${_e.left+_e.width/2}px`,le.style.top=`${_e.top-8}px`,le.style.transform="translate(-50%, -100%)",pe.appendChild(le)},ae=()=>{le&&le.parentNode&&(le.parentNode.removeChild(le),le=null)};A.addEventListener("mouseenter",ve),A.addEventListener("mouseleave",ae),y.addEventListener("focus",ve),y.addEventListener("blur",ae),A._cleanupTooltip=()=>{ae(),A.removeEventListener("mouseenter",ve),A.removeEventListener("mouseleave",ae),y.removeEventListener("focus",ve),y.removeEventListener("blur",ae)}}return{button:y,wrapper:A}};var Dr={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))"},rn=e=>{var S,v,M,I,H,R,D,O,Q,me,ce,ee,Ce,Ie,le,ve;let{config:t,showClose:r=!0}=e,o=At("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),n=(S=t==null?void 0:t.launcher)!=null?S:{},a=(v=n.headerIconSize)!=null?v:"48px",s=(M=n.closeButtonPlacement)!=null?M:"inline",i=(I=n.headerIconHidden)!=null?I:!1,c=n.headerIconName,l=At("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(c){let ae=parseFloat(a)||24,se=fe(c,ae*.6,"currentColor",1);se?l.replaceChildren(se):l.textContent=(R=(H=t==null?void 0:t.launcher)==null?void 0:H.agentIconText)!=null?R:"\u{1F4AC}"}else if((D=t==null?void 0:t.launcher)!=null&&D.iconUrl){let ae=C("img");ae.src=t.launcher.iconUrl,ae.alt="",ae.className="persona-rounded-xl persona-object-cover",ae.style.height=a,ae.style.width=a,l.replaceChildren(ae)}else l.textContent=(Q=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?Q:"\u{1F4AC}";let p=C("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=At("span",{className:"persona-text-base persona-font-semibold",text:(ce=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?ce:"Chat Assistant",style:{color:Dr.titleColor}}),u=At("span",{className:"persona-text-xs",text:(Ce=(ee=t==null?void 0:t.launcher)==null?void 0:ee.subtitle)!=null?Ce:"Here to help you get answers fast",style:{color:Dr.subtitleColor}});p.append(f,u),i?o.append(p):o.append(l,p);let m=(Ie=n.clearChat)!=null?Ie:{},x=(le=m.enabled)!=null?le:!0,b=(ve=m.placement)!=null?ve:"inline",L=null,E=null;if(x){let se=Ui(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});L=se.button,E=se.wrapper,b==="top-right"&&(E.style.right="48px"),b==="inline"&&o.appendChild(E)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&b==="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:T,wrapper:y}=_i(t,{showClose:r,wrapperClassName:A});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:l,headerTitle:f,headerSubtitle:u,closeButton:T,closeButtonWrapper:y,clearChatButton:L,clearChatButtonWrapper:E}},na=(e,t,r)=>{var s,i,c,l;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(l=(c=o.clearChat)==null?void 0:c.placement)!=null?l:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function In(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=C("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Ln)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of t){if(m.dividerBefore){let L=document.createElement("hr");s.appendChild(L)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let L=fe(m.icon,16,"currentColor",1.5);L&&x.appendChild(L)}let b=document.createElement("span");b.textContent=m.label,x.appendChild(b),x.addEventListener("click",L=>{L.stopPropagation(),p(),r(m.id)}),s.appendChild(x)}let i=null;function c(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function l(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!s.contains(x.target)&&!o.contains(x.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){s.classList.add("persona-hidden"),i==null||i(),i=null}function f(){s.classList.contains("persona-hidden")?l():p()}function u(){p(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:p,toggle:f,destroy:u}}function ur(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=C("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let l=fe(t,o!=null?o:16,"currentColor",n!=null?n:2);if(l&&c.appendChild(l),s&&c.addEventListener("click",s),i)for(let[p,f]of Object.entries(i))c.setAttribute(p,f);return c}function ks(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+n,s&&(l+=" "+s);let p=C("button",l);if(p.type="button",p.setAttribute("aria-label",r),t){let u=fe(t,a!=null?a:14,"currentColor",2);u&&p.appendChild(u)}let f=C("span");if(f.textContent=r,p.appendChild(f),i&&p.addEventListener("click",i),c)for(let[u,m]of Object.entries(c))p.setAttribute(u,m);return p}function vh(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=C("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===s?"true":"false")}for(let p of t){let f;p.icon?f=ur({icon:p.icon,label:p.label,onClick:()=>{s=p.id,c(),o(p.id)}}):(f=C("button","persona-icon-btn"),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{s=p.id,c(),o(p.id)})),f.setAttribute("aria-pressed",p.id===s?"true":"false"),i.push({id:p.id,btn:f}),a.appendChild(f)}function l(p){s=p,c()}return{element:a,setSelected:l}}function qi(e){var m,x;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,l=C("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=C("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let f=fe(r,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",l.appendChild(f)),c&&(l.style.borderRadius=(m=c.borderRadius)!=null?m:"10px",l.style.padding=(x=c.padding)!=null?x:"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 b,L;l.style.backgroundColor=(b=c.background)!=null?b:"",l.style.borderColor=(L=c.border)!=null?L:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let u=In({items:o,onSelect:b=>{l.setAttribute("aria-expanded","false"),n(b)},anchor:l,position:a,portal:s});return s||l.appendChild(u.element),l.addEventListener("click",b=>{b.stopPropagation();let L=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",L?"false":"true"),u.toggle()}),l.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),l.click())}),{element:l,setLabel:b=>{p.textContent=b,l.setAttribute("aria-label",b)},open:()=>{l.setAttribute("aria-expanded","true"),u.show()},close:()=>{l.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let b=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",b?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),l.remove()}}}var Jc=e=>{var o;let t=rn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(r){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>r()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function Ub(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=C("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",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let c=fe(s.icon,14,"currentColor",2);c&&i.appendChild(c)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let c=C("div","persona-relative");c.appendChild(i);let l=In({items:s.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:c,position:"bottom-left"});c.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var Qc=e=>{var A,T,y,S,v,M,I,H,R;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(A=t==null?void 0:t.launcher)!=null?A:{},i=C("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 c=n==null?void 0:n.titleMenu,l,p;if(c)l=qi({label:(T=s.title)!=null?T:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,l.style.color=Dr.titleColor,p=(y=l.querySelector(".persona-combo-btn-label"))!=null?y:l;else{if(l=C("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=C("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Dr.titleColor,p.textContent=(S=s.title)!=null?S:"Chat Assistant",l.appendChild(p),Ub(l,n==null?void 0:n.trailingActions,(v=n==null?void 0:n.onAction)!=null?v:a),n!=null&&n.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let O=n.onTitleClick;l.addEventListener("click",Q=>{Q.target.closest("button")||O()}),l.addEventListener("keydown",Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),O())})}let D=n==null?void 0:n.titleRowHover;D&&(l.style.borderRadius=(M=D.borderRadius)!=null?M:"10px",l.style.padding=(I=D.padding)!=null?I:"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 O,Q;l.style.backgroundColor=(O=D.background)!=null?O:"",l.style.borderColor=(Q=D.border)!=null?Q:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let f=(H=s.closeButtonSize)!=null?H:"32px",u=C("div",""),m=C("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=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none",m.style.color=s.closeButtonColor||Dr.actionIconColor;let x=(R=s.closeButtonIconName)!=null?R:"x",b=fe(x,"28px","currentColor",1);b?m.appendChild(b):m.textContent="\xD7",o&&m.addEventListener("click",o),u.appendChild(m),i.appendChild(u);let L=C("div");L.style.display="none";let E=C("span");return E.style.display="none",{header:i,iconHolder:L,headerTitle:p,headerSubtitle:E,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Vi={default:Jc,minimal:Qc},Yc=e=>{var t;return(t=Vi[e])!=null?t:Vi.default},Fa=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let l=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=C("div");p.style.display="none";let f=C("span"),u=C("span"),m=C("button");m.style.display="none";let x=C("div");return x.style.display="none",{header:l,iconHolder:p,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=Yc(o)({config:e,showClose:(c=(i=t==null?void 0:t.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?c:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var zi=e=>{var s,i;let t=C("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.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 r=3,o=20;t.style.maxHeight=`${r*o}px`,t.style.overflowY="auto";let n=()=>{let c=parseFloat(t.style.maxHeight);return Number.isFinite(c)&&c>0?c:r*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let c=Math.min(t.scrollHeight,n());t.style.height=`${c}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:a}},$i=e=>{var S,v,M,I,H,R,D,O,Q,me,ce,ee;let t=(S=e==null?void 0:e.sendButton)!=null?S:{},r=(v=t.useIcon)!=null?v:!1,o=(M=t.iconText)!=null?M:"\u2191",n=t.iconName,a=(I=t.stopIconName)!=null?I:"square",s=(H=t.tooltipText)!=null?H:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",c=(O=(D=e==null?void 0:e.copy)==null?void 0:D.sendButtonLabel)!=null?O:"Send",l=(me=(Q=e==null?void 0:e.copy)==null?void 0:Q.stopButtonLabel)!=null?me:"Stop",p=(ce=t.showTooltip)!=null?ce:!1,f=(ee=t.size)!=null?ee:"40px",u=t.backgroundColor,m=t.textColor,x=C("div","persona-send-button-wrapper"),b=At("button",{className:ss("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!u&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?f:void 0,height:r?f:void 0,minWidth:r?f:void 0,minHeight:r?f:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:r&&u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),L=null,E=null;if(r){let Ce=parseFloat(f)||24,Ie=(m==null?void 0:m.trim())||"currentColor";n?(L=fe(n,Ce,Ie,2),L?b.appendChild(L):b.textContent=o):b.textContent=o,E=fe(a,Ce,Ie,2)}else b.textContent=c;let A=null;p&&s&&(A=C("div","persona-send-button-tooltip"),A.textContent=s,x.appendChild(A)),b.setAttribute("aria-label",s),x.appendChild(b);let T="send";return{button:b,wrapper:x,setMode:Ce=>{if(Ce===T)return;T=Ce;let Ie=Ce==="stop"?i:s;if(b.setAttribute("aria-label",Ie),A&&(A.textContent=Ie),r){if(L&&E){let le=Ce==="stop"?E:L;b.replaceChildren(le)}}else b.textContent=Ce==="stop"?l:c}}},ji=e=>{var A,T,y,S,v,M,I,H,R,D,O,Q;let t=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((T=t.provider)==null?void 0:T.type)==="runtype";if(!(o||n))return null;let s=(S=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?S:"40px",i=(v=t.iconName)!=null?v:"mic",c=(M=t.iconSize)!=null?M:s,l=parseFloat(c)||24,p=(H=t.backgroundColor)!=null?H:(I=e==null?void 0:e.sendButton)==null?void 0:I.backgroundColor,f=(D=t.iconColor)!=null?D:(R=e==null?void 0:e.sendButton)==null?void 0:R.textColor,u=C("div","persona-send-button-wrapper"),m=At("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),b=fe(i,l,f||"currentColor",1.5);b?m.appendChild(b):m.textContent="\u{1F3A4}",u.appendChild(m);let L=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((Q=t.showTooltip)!=null?Q:!1)&&L){let me=C("div","persona-send-button-tooltip");me.textContent=L,u.appendChild(me)}return{button:m,wrapper:u}},Gi=e=>{var x,b,L,E,A,T,y,S;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(L=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?L:"40px",o=C("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=C("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:en).join(","),n.multiple=((A=t.maxFiles)!=null?A:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(T=t.buttonIconName)!=null?T:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),l=C("div","persona-send-button-wrapper"),p=At("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let f=fe(a,c,"currentColor",1.5);f?p.appendChild(f):p.textContent="\u{1F4CE}",p.addEventListener("click",v=>{v.preventDefault(),n.click()}),l.appendChild(p);let u=(S=t.buttonTooltipText)!=null?S:"Attach file",m=C("div","persona-send-button-tooltip");return m.textContent=u,l.appendChild(m),{button:p,wrapper:l,input:n,previewsContainer:o}},Ki=e=>{var s,i,c;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=C("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let l=C("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=a,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=a;return o},Xi=()=>At("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Na=e=>{var x,b,L,E,A,T;let{config:t}=e,r=At("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Xi(),n=At("form",{className:"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",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=zi(t);s();let i=$i(t),c=ji(t),l=Gi(t),p=Ki(t);l&&(l.previewsContainer.style.gap="8px",n.append(l.previewsContainer,l.input)),n.append(a);let f=At("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=C("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=C("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&u.append(l.wrapper),c&&m.append(c.wrapper),m.append(i.wrapper),f.append(u,m),n.append(f),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(l==null?void 0:l.button)&&y.target!==(l==null?void 0:l.wrapper)&&a.focus()}),r.append(o,n,p),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:p,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var Ch=()=>{let e=At("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=C("span","persona-pill-peek__icon"),r=fe("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=C("span","persona-pill-peek__text"),n=C("span","persona-pill-peek__caret"),a=fe("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},wh=e=>{var x,b,L,E,A,T;let{config:t}=e,r=At("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Xi();o.style.display="none";let n=Ki(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=zi(t);a.style.maxHeight="100px",s();let i=$i(t),c=ji(t),l=Gi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=At("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=C("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&f.append(l.wrapper);let u=C("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&u.append(c.wrapper),u.append(i.wrapper),p.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(l==null?void 0:l.button)&&y.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&p.append(l.input),p.append(f,a,u),l&&r.append(l.previewsContainer),r.append(p,o,n);let m=p;return{footer:r,suggestions:o,composerForm:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:n,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var Sh=e=>{var p,f,u,m,x,b,L,E,A,T,y,S,v,M,I,H,R;let t=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?f:!0,r=sr(e);if(Rn(e)){let D=(m=(u=e==null?void 0:e.launcher)==null?void 0:u.composerBar)!=null?m:{},O=C("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(x=D.expandedSize)!=null?x:"anchored",O.style.zIndex=String((L=(b=e==null?void 0:e.launcher)==null?void 0:b.zIndex)!=null?L:Tr);let Q=C("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Q.style.width="100%",O.appendChild(Q);let me=C("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=D.expandedSize)!=null?E:"anchored",me.style.zIndex=String((T=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?T:Tr),{wrapper:O,panel:Q,pillRoot:me}}if(r){let D=C("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=C("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return D.appendChild(O),{wrapper:D,panel:O}}if(!t){let D=C("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=C("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Q=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?S:"100%";return D.style.width=Q,O.style.width="100%",D.appendChild(O),{wrapper:D,panel:O}}let n=(v=e==null?void 0:e.launcher)!=null?v:{},a=n.position&&So[n.position]?So[n.position]:So["bottom-right"],s=C("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((I=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?I:Tr);let i=C("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(R=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?R:e==null?void 0:e.launcherWidth,l=c!=null?c:Zr;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},qb=(e,t)=>{var y,S,v,M,I,H,R,D,O;let r=C("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=_i(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(v=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:S.enabled)!=null?v:!0,s=null,i=null;if(a){let Q=Ui(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=Q.button,i=Q.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=At("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=At("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});l.style.setProperty("scrollbar-gutter","stable");let p=At("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(I=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?I:"Hello \u{1F44B}"}),f=At("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),u=At("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,f),m=C("div","persona-flex persona-flex-col persona-gap-3"),x=(D=e==null?void 0:e.layout)==null?void 0:D.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let L=At("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=wh({config:e}),{root:A,textNode:T}=Ch();return r.append(c,n,l,L),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:m,composerOverlay:L,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:p,introSubtitle:f,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:C("span"),headerTitle:C("span"),headerSubtitle:C("span"),header:c,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:A,peekTextNode:T}},Ah=(e,t=!0)=>{var L,E,A,T,y,S,v,M,I;if(Rn(e))return qb(e,t);let r=At("div",{className:"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",attrs:{"data-persona-theme-zone":"container"}}),o=(L=e==null?void 0:e.layout)==null?void 0:L.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?Fa(e,o,{showClose:t}):rn({config:e,showClose:t}),s=At("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let i=At("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(T=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?T:"Hello \u{1F44B}"}),c=At("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(S=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?S:"Ask anything about your account or products."}),l=At("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:sr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),p=C("div","persona-flex persona-flex-col persona-gap-3"),f=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(l.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(l,p);let m=Na({config:e}),x=((I=e==null?void 0:e.layout)==null?void 0:I.showFooter)!==!1;n?na(r,a,e):(a.header.style.display="none",na(r,a,e)),r.append(s);let b=At("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return x||(m.footer.style.display="none"),r.append(m.footer),r.append(b),{container:r,body:s,messagesWrapper:p,composerOverlay:b,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:i,introSubtitle:c,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.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 Zc=(e,t)=>{let r=C("button");r.type="button",r.innerHTML=`
19
21
  <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>
20
22
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
21
23
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -23,14 +25,14 @@ _Details: ${r.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
23
25
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
24
26
  </span>
25
27
  <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>
26
- `,r.addEventListener("click",t);let o=a=>{var L,y,w,b,T,I,P,k,N,U,Y,he,$e;let s=(L=a.launcher)!=null?L:{},i=nr(a),p=r.querySelector("[data-role='launcher-title']");if(p){let Me=(y=s.title)!=null?y:"Chat Assistant";p.textContent=Me,p.setAttribute("title",Me)}let d=r.querySelector("[data-role='launcher-subtitle']");if(d){let Me=(w=s.subtitle)!=null?w:"Here to help you get answers fast";d.textContent=Me,d.setAttribute("title",Me)}let u=r.querySelector(".persona-flex-col");u&&(s.textHidden||i?u.style.display="none":u.style.display="");let g=r.querySelector("[data-role='launcher-icon']");if(g)if(s.agentIconHidden)g.style.display="none";else{let Me=(b=s.agentIconSize)!=null?b:"40px";if(g.style.height=Me,g.style.width=Me,g.innerHTML="",s.agentIconName){let Ie=parseFloat(Me)||24,qe=be(s.agentIconName,Ie*.6,"var(--persona-text-inverse, #ffffff)",2);qe?(g.appendChild(qe),g.style.display=""):(g.textContent=(T=s.agentIconText)!=null?T:"\u{1F4AC}",g.style.display="")}else s.iconUrl?g.style.display="none":(g.textContent=(I=s.agentIconText)!=null?I:"\u{1F4AC}",g.style.display="")}let c=r.querySelector("[data-role='launcher-image']");if(c){let Me=(P=s.agentIconSize)!=null?P:"40px";c.style.height=Me,c.style.width=Me,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(c.src=s.iconUrl,c.style.display="block"):c.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Me=(k=s.callToActionIconSize)!=null?k:"32px";m.style.height=Me,m.style.width=Me,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Ie=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,Ie=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let qe=parseFloat(Me)||24,Ee=Math.max(qe-Ie,8),Be=be(s.callToActionIconName,Ee,"currentColor",2);Be?m.appendChild(Be):m.textContent=(N=s.callToActionIconText)!=null?N:"\u2197"}else m.textContent=(U=s.callToActionIconText)!=null?U:"\u2197"}let x=s.position&&vo[s.position]?vo[s.position]:vo["bottom-right"],C="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",R="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";r.className=i?R:`${C} ${x}`,i||(r.style.zIndex=String((Y=s.zIndex)!=null?Y:Sr));let M="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(he=s.border)!=null?he:M,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=($e=s.collapsedMaxWidth)!=null?$e:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},n=()=>{r.removeEventListener("click",t),r.remove()};return e&&o(e),{element:r,update:o,destroy:n}};var yh=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=hh(e),a=xh(e,t),s={wrapper:r,panel:o,pillRoot:n},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},p={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:p,composer:d,replaceHeader:c=>(p.element.replaceWith(c.header),p.element=c.header,p.iconHolder=c.iconHolder,p.headerTitle=c.headerTitle,p.headerSubtitle=c.headerSubtitle,p.closeButton=c.closeButton,p.closeButtonWrapper=c.closeButtonWrapper,p.clearChatButton=c.clearChatButton,p.clearChatButtonWrapper=c.clearChatButtonWrapper,c),replaceComposer:c=>{d.footer.replaceWith(c),d.footer=c}}},Yp=({config:e,plugins:t,onToggle:r})=>{let o=t.find(a=>a.renderLauncher);if(o!=null&&o.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>Qp(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=Qp(e,r);return{instance:n,element:n.element}};var Eb=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}},kb=(e,t)=>{if(!e)return null;let r=Eb(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},Lb=(e,t)=>{let r=S("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},Pb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Zp=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(":"))},ec=320,vh=320,Rb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ib=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Wb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Hb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Bb=(e,t,r)=>{if(e.length===0)return null;try{let o=S("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,p)=>{var g;let d=S("img");d.alt=((g=i.alt)==null?void 0:g.trim())||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${ec}px`,d.style.maxHeight=`${vh}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;n+=1,d.addEventListener("error",()=>{u||(u=!0,n=Math.max(0,n-1),d.remove(),n===0&&s())}),d.addEventListener("load",()=>{u=!0}),Pb(i.image)?(d.src=i.image,o.appendChild(d)):(u=!0,n=Math.max(0,n-1),d.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},Db=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!Zp(o.audio))return;let n=S("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${ec}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Fb=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!Zp(o.video))return;let n=S("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${ec}px`,n.style.maxHeight=`${vh}px`,n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Nb=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!Zp(o.data))return;let n=S("a");n.href=o.data,n.download=o.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=o.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},ra=()=>{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 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="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(o),e.appendChild(n),e},tc=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:ra};if(t){let n=t(o);if(n!==null)return n}return ra()},Ob=(e,t)=>{let r=S("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"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let n=S("img");n.src=o,n.alt=t==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(n)}else r.textContent=o,r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},bh=(e,t,r="div")=>{let o=S(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?o.textContent=t.format(n):o.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},_b=(e,t="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.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 r},rc=(e,t,r)=>{var x,C,R,M,A,L,y;let o=(x=t.showCopy)!=null?x:!0,n=(C=t.showUpvote)!=null?C:!0,a=(R=t.showDownvote)!=null?R:!0,s=(M=t.showReadAloud)!=null?M:!1;if(!o&&!n&&!a&&!s){let w=S("div");return w.style.display="none",w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id),w}let i=(A=t.visibility)!=null?A:"hover",p=(L=t.align)!=null?L:"right",d=(y=t.layout)!=null?y:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],c=S("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${g} ${i==="hover"?"persona-message-actions-hover":""}`);c.id=`actions-${e.id}`,c.setAttribute("data-actions-for",e.id);let m=(w,b,T)=>{let I=cr({icon:w,label:b,size:14,className:"persona-message-action-btn"});return I.setAttribute("data-action",T),I};return o&&c.appendChild(m("copy","Copy message","copy")),s&&c.appendChild(m("volume-2","Read aloud","read-aloud")),n&&c.appendChild(m("thumbs-up","Upvote","upvote")),a&&c.appendChild(m("thumbs-down","Downvote","downvote")),c},Ha=(e,t,r,o,n,a)=>{var ae,Q,pe,ye,ne,K,oe,Ge,Z,se,We,Ct,Lt,mt,Oe,fe,Ye;let s=r!=null?r:{},i=(ae=s.layout)!=null?ae:"bubble",p=s.avatar,d=s.timestamp,u=(Q=p==null?void 0:p.show)!=null?Q:!1,g=(pe=d==null?void 0:d.show)!=null?pe:!1,c=(ye=p==null?void 0:p.position)!=null?ye:"left",m=(ne=d==null?void 0:d.position)!=null?ne:"below",x=_b(e.role,i),C=S("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let R=Rb(e),M=(oe=(K=e.content)==null?void 0:K.trim())!=null?oe:"",L=R.length>0&&M===di,y=Hi((Z=(Ge=a==null?void 0:a.widgetConfig)==null?void 0:Ge.features)==null?void 0:Z.streamAnimation),w=(Ct=(We=(se=a==null?void 0:a.widgetConfig)==null?void 0:se.features)==null?void 0:We.streamAnimation)==null?void 0:Ct.plugins,b=e.role==="assistant"&&y.type!=="none"?ys(y.type,w):null,T=e.role==="assistant"&&((Lt=b==null?void 0:b.isAnimating)==null?void 0:Lt.call(b,e))===!0,I=e.role==="assistant"&&b!==null&&(!!e.streaming||T);I&&(b!=null&&b.bubbleClass)&&C.classList.add(b.bubbleClass);let P=document.createElement("div");P.classList.add("persona-message-content"),I&&b&&(b.containerClass&&P.classList.add(b.containerClass),P.style.setProperty("--persona-stream-step",`${y.speed}ms`),P.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let k=I?Bi((mt=e.content)!=null?mt:"",y.buffer,b,e,!!e.streaming):(Oe=e.content)!=null?Oe:"",N=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),U=N;I&&(b==null?void 0:b.wrap)==="char"?U=bs(N,"char",e.id,{skipTags:b.skipTags}):I&&(b==null?void 0:b.wrap)==="word"&&(U=bs(N,"word",e.id,{skipTags:b.skipTags}));let Y=null;if(L?(Y=document.createElement("div"),Y.innerHTML=U,Y.style.display="none",P.appendChild(Y)):P.innerHTML=U,I&&(b!=null&&b.useCaret)&&!L&&M){let X=Di(),ie=P.querySelectorAll(".persona-stream-char, .persona-stream-word"),ve=ie[ie.length-1];if(ve!=null&&ve.parentNode)ve.parentNode.insertBefore(X,ve.nextSibling);else{let Ve=P.lastElementChild;Ve?Ve.appendChild(X):P.appendChild(X)}}if(g&&m==="inline"&&e.createdAt){let X=bh(e,d,"span");X.classList.add("persona-timestamp-inline");let ie=P.lastElementChild;ie?ie.appendChild(X):P.appendChild(X)}if(R.length>0){let X=Bb(R,!L&&!!M,()=>{L&&Y&&(Y.style.display="")});X?C.appendChild(X):L&&Y&&(Y.style.display="")}let he=Ib(e);if(he.length>0){let X=Db(he);X&&C.appendChild(X)}let $e=Wb(e);if($e.length>0){let X=Fb($e);X&&C.appendChild(X)}let Me=Hb(e);if(Me.length>0){let X=Nb(Me);X&&C.appendChild(X)}if(C.appendChild(P),g&&m==="below"&&e.createdAt){let X=bh(e,d);X.classList.add("persona-mt-1"),C.appendChild(X)}let Ie=e.role==="assistant"?kb(e.stopReason,(Ye=(fe=a==null?void 0:a.widgetConfig)==null?void 0:fe.copy)==null?void 0:Ye.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(k&&k.trim()),ie=y.placeholder==="skeleton",ve=ie&&y.buffer==="line"&&X;if(X)ve&&C.appendChild(vs());else if(ie)C.appendChild(vs());else{let Ve=tc("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Ve&&C.appendChild(Ve)}}if(Ie&&e.stopReason&&!e.streaming&&(M||(P.style.display="none"),C.appendChild(Lb(e.stopReason,Ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let X=rc(e,o,n);C.appendChild(X)}if(!u||e.role==="system")return C;let Ee=S("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Be=Ob(p,e.role);return c==="right"||c==="left"&&e.role==="user"?Ee.append(C,Be):Ee.append(Be,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ee},Ch=(e,t,r,o,n,a)=>{let s=r!=null?r:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ha(e,t,r,o,n,a)};var Ba=new Set,Ub=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),qb=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
27
- `):""},wh=(e,t)=>{let r=Ba.has(e),o=t.querySelector('button[data-expand-header="true"]'),n=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!n)return;o.setAttribute("aria-expanded",r?"true":"false");let s=o.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=be(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}n.style.display=r?"":"none",a&&(a.style.display=r?"none":a.textContent||a.childNodes.length?"":"none")},oc=(e,t)=>{var $e,Me,Ie,qe,Ee,Be,ae,Q,pe,ye,ne;let r=e.reasoning,o=S("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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!r)return o;let n=(Me=($e=t==null?void 0:t.features)==null?void 0:$e.reasoningDisplay)!=null?Me:{},a=n.expandable!==!1,s=a&&Ba.has(e.id),i=r.status!=="complete",p=qb(e,(Ie=n.previewMaxLines)!=null?Ie:3),d=S("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");d.type="button",a&&(d.setAttribute("aria-expanded",s?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let u=S("div","persona-flex persona-flex-col persona-text-left"),g=S("span","persona-text-xs persona-text-persona-primary"),c="Thinking...",m=(qe=t==null?void 0:t.reasoning)!=null?qe:{},x=String((Ee=r.startedAt)!=null?Ee:Date.now()),C=()=>{let K=S("span","");return K.setAttribute("data-tool-elapsed",x),K.textContent=ri(r),K},R=(Be=m.renderCollapsedSummary)==null?void 0:Be.call(m,{message:e,reasoning:r,defaultSummary:c,previewText:p,isActive:i,config:t!=null?t:{},elapsed:ri(r),createElapsedElement:C});typeof R=="string"&&R.trim()?(g.textContent=R,u.appendChild(g)):R instanceof HTMLElement?u.appendChild(R):(g.textContent=c,u.appendChild(g));let M=S("span","persona-text-xs persona-text-persona-primary");M.textContent=Mg(r),u.appendChild(M);let A=(ae=n.loadingAnimation)!=null?ae:"none",L=m.activeTextTemplate,y=m.completeTextTemplate,w=i?L:y,b=R instanceof HTMLElement,T=(K,oe,Ge)=>{let Z=Ge;for(let se of oe){let We=S("span","persona-tool-char");We.style.setProperty("--char-index",String(Z)),We.textContent=se===" "?"\xA0":se,K.appendChild(We),Z++}return Z},I=(K,oe)=>{g.textContent="";let Ge=oi(K,""),Z=0;for(let se of Ge){let We=se.styles.length>0?(()=>{let Ct=S("span",se.styles.map(Lt=>`persona-tool-text-${Lt}`).join(" "));return g.appendChild(Ct),Ct})():g;if(se.isDuration&&i)We.appendChild(C());else{let Ct=se.isDuration?ri(r):se.text;oe?Z=T(We,Ct,Z):We.appendChild(document.createTextNode(Ct))}}};if(!b&&w)if(M.style.display="none",g.style.display="",i&&A!=="none"){let K=(Q=m.loadingAnimationDuration)!=null?Q:2e3;g.setAttribute("data-preserve-animation","true"),A==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),I(w,!1)):(g.classList.add(`persona-tool-loading-${A}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),I(w,!0))}else I(w,!1);else if(!b&&i&&A!=="none"){g.style.display="";let K=(pe=m.loadingAnimationDuration)!=null?pe:2e3;if(g.setAttribute("data-preserve-animation","true"),A==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{g.classList.add(`persona-tool-loading-${A}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let oe=g.textContent||c;g.textContent="",T(g,oe,0)}r.status==="complete"&&(g.style.display="none")}else b||(r.status==="complete"?g.style.display="none":g.style.display="");let P=null;if(a){P=S("div","persona-flex persona-items-center");let oe=be(s?"chevron-up":"chevron-down",16,"currentColor",2);oe?P.appendChild(oe):P.textContent=s?"Hide":"Show";let Ge=S("div","persona-flex persona-items-center persona-ml-auto");Ge.append(P),d.append(u,Ge)}else d.append(u);let k=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!s&&i&&n.activePreview&&p){let K=(ne=(ye=t==null?void 0:t.reasoning)==null?void 0:ye.renderCollapsedPreview)==null?void 0:ne.call(ye,{message:e,reasoning:r,defaultPreview:p,isActive:i,config:t!=null?t:{}});Ub(k,K)||(k.textContent=p),k.style.display=""}if(!s&&i&&n.activeMinHeight&&(o.style.minHeight=n.activeMinHeight),!a)return o.append(d,k),o;let N=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=s?"":"none";let U=r.chunks.join(""),Y=S("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Y.textContent=U||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(Y),(()=>{if(d.setAttribute("aria-expanded",s?"true":"false"),P){P.innerHTML="";let oe=be(s?"chevron-up":"chevron-down",16,"currentColor",2);oe?P.appendChild(oe):P.textContent=s?"Hide":"Show"}N.style.display=s?"":"none",k.style.display=s?"none":k.textContent||k.childNodes.length?"":"none"})(),o.append(d,k,N),o};var Da=new Set,Vb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zb=(e,t)=>{var a;let r=e.toolCall;if(!r)return"";let o=((a=r.chunks)!=null?a:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
28
- `);let n=Ma(r.args).trim();return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
29
- `):""},nc=(e,t)=>{var r,o,n;e.style.backgroundColor=(r=t.codeBlockBackgroundColor)!=null?r:"var(--persona-container, #f3f4f6)",e.style.borderColor=(o=t.codeBlockBorderColor)!=null?o:"var(--persona-border, #e5e7eb)",e.style.color=(n=t.codeBlockTextColor)!=null?n:"var(--persona-text, #171717)"},$b=(e,t)=>{var u,g,c,m,x;let r=e.toolCall,o=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,n=(g=o==null?void 0:o.collapsedMode)!=null?g:"tool-call",a=zb(e,(c=o==null?void 0:o.previewMaxLines)!=null?c:3),s=r?Tg(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i=r.status!=="complete",p=(m=t==null?void 0:t.toolCall)!=null?m:{},d=s;return n==="tool-name"?d=((x=r.name)==null?void 0:x.trim())||s:n==="tool-preview"&&a&&(d=a),i&&p.activeTextTemplate?d=Dl(r,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=Dl(r,p.completeTextTemplate,d)),{summary:d,previewText:a,isActive:i}},Sh=(e,t,r)=>{var u;let o=Da.has(e),n=(u=r==null?void 0:r.toolCall)!=null?u:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let p=a.querySelector(".persona-ml-auto"),d=p==null?void 0:p.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=n.toggleTextColor||n.headerTextColor||"var(--persona-primary, #171717)",c=be(o?"chevron-up":"chevron-down",16,g,2);c?d.appendChild(c):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},ac=(e,t)=>{var U,Y,he,$e,Me,Ie,qe,Ee,Be;let r=e.toolCall,o=(U=t==null?void 0:t.toolCall)!=null?U:{},n=S("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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),o.backgroundColor&&(n.style.backgroundColor=o.backgroundColor),o.borderColor&&(n.style.borderColor=o.borderColor),o.borderWidth&&(n.style.borderWidth=o.borderWidth),o.borderRadius&&(n.style.borderRadius=o.borderRadius),n.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return n;let a=(he=(Y=t==null?void 0:t.features)==null?void 0:Y.toolCallDisplay)!=null?he:{},s=a.expandable!==!1,i=s&&Da.has(e.id),{summary:p,previewText:d,isActive:u}=$b(e,t),g=S("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");g.type="button",s&&(g.setAttribute("aria-expanded",i?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let c=S("div","persona-flex persona-flex-col persona-text-left"),m=S("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let x=String(($e=r.startedAt)!=null?$e:Date.now()),C=()=>{let ae=S("span","");return ae.setAttribute("data-tool-elapsed",x),ae.textContent=ls(r),ae},R=(Ie=o.renderCollapsedSummary)==null?void 0:Ie.call(o,{message:e,toolCall:r,defaultSummary:p,previewText:d,collapsedMode:(Me=a.collapsedMode)!=null?Me:"tool-call",isActive:u,config:t!=null?t:{},elapsed:ls(r),createElapsedElement:C});typeof R=="string"&&R.trim()?(m.textContent=R,c.appendChild(m)):R instanceof HTMLElement?c.appendChild(R):(m.textContent=p,c.appendChild(m));let M=(qe=a.loadingAnimation)!=null?qe:"none",A=o.activeTextTemplate,L=o.completeTextTemplate,y=u?A:L,w=R instanceof HTMLElement,b=(ae,Q,pe)=>{let ye=pe;for(let ne of Q){let K=S("span","persona-tool-char");K.style.setProperty("--char-index",String(ye)),K.textContent=ne===" "?"\xA0":ne,ae.appendChild(K),ye++}return ye},T=(ae,Q)=>{var K;m.textContent="";let pe=((K=r.name)==null?void 0:K.trim())||"tool",ye=oi(ae,pe),ne=0;for(let oe of ye){let Ge=oe.styles.length>0?(()=>{let Z=S("span",oe.styles.map(se=>`persona-tool-text-${se}`).join(" "));return m.appendChild(Z),Z})():m;if(oe.isDuration&&u)Ge.appendChild(C());else{let Z=oe.isDuration?ls(r):oe.text;Q?ne=b(Ge,Z,ne):Ge.appendChild(document.createTextNode(Z))}}};if(!w)if(u&&M!=="none"){let ae=(Ee=o.loadingAnimationDuration)!=null?Ee:2e3;if(m.setAttribute("data-preserve-animation","true"),M==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),y&&T(y,!1);else if(m.classList.add(`persona-tool-loading-${M}`),m.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),M==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),y)T(y,!0);else{let Q=m.textContent||p;m.textContent="",b(m,Q,0)}}else y&&T(y,!1);let I=null;if(s){I=S("div","persona-flex persona-items-center");let ae=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",Q=be(i?"chevron-up":"chevron-down",16,ae,2);Q?I.appendChild(Q):I.textContent=i?"Hide":"Show";let pe=S("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");pe.append(I),g.append(c,pe)}else g.append(c);let P=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(P.setAttribute("data-persona-collapsed-preview","tool"),P.style.display="none",P.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&d){let ae=(Be=o.renderCollapsedPreview)==null?void 0:Be.call(o,{message:e,toolCall:r,defaultPreview:d,isActive:u,config:t!=null?t:{}});Vb(P,ae)||(P.textContent=d),P.style.display=""}if(!i&&u&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(g,P),n;let k=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",o.contentBackgroundColor&&(k.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(k.style.color=o.contentTextColor),o.contentPaddingX&&(k.style.paddingLeft=o.contentPaddingX,k.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(k.style.paddingTop=o.contentPaddingY,k.style.paddingBottom=o.contentPaddingY),r.name){let ae=S("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?ae.style.color=o.contentTextColor:o.headerTextColor&&(ae.style.color=o.headerTextColor),ae.textContent=r.name,k.appendChild(ae)}if(r.args!==void 0){let ae=S("div","persona-space-y-1"),Q=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Q.style.color=o.labelTextColor),Q.textContent="Arguments";let pe=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",nc(pe,o),pe.textContent=Ma(r.args),ae.append(Q,pe),k.appendChild(ae)}if(r.chunks&&r.chunks.length){let ae=S("div","persona-space-y-1"),Q=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Q.style.color=o.labelTextColor),Q.textContent="Activity";let pe=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",nc(pe,o),pe.textContent=r.chunks.join(""),ae.append(Q,pe),k.appendChild(ae)}if(r.status==="complete"&&r.result!==void 0){let ae=S("div","persona-space-y-1"),Q=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Q.style.color=o.labelTextColor),Q.textContent="Result";let pe=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",nc(pe,o),pe.textContent=Ma(r.result),ae.append(Q,pe),k.appendChild(ae)}if(r.status==="complete"&&typeof r.duration=="number"){let ae=S("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(ae.style.color=o.contentTextColor),ae.textContent=`Duration: ${r.duration}ms`,k.appendChild(ae)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),I){I.innerHTML="";let ae=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",Q=be(i?"chevron-up":"chevron-down",16,ae,2);Q?I.appendChild(Q):I.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",P.style.display=i?"none":P.textContent||P.childNodes.length?"":"none"})(),n.append(g,P,k),n};var Gi=new Map,jb=e=>{let r=(e.startsWith(Ko)?e.slice(Ko.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(r.length===0)return e;let o=r.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Ah=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Mh=(e,t)=>{var o,n,a;let r=(n=(o=Ah(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=Gi.get(e))!=null?a:r==="expanded"},Th=(e,t,r)=>{var s,i;let o=Ah(r);e.setAttribute("aria-expanded",t?"true":"false");let n=e.querySelector("[data-approval-details-label]");n&&(n.textContent=t?(s=o==null?void 0:o.hideDetailsLabel)!=null?s:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let p=be(t?"chevron-up":"chevron-down",14,"currentColor",2);p&&a.appendChild(p)}},Eh=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=Mh(e,r);Th(o,a,r),n.style.display=a?"":"none"};var Ki=(e,t)=>{var T,I,P,k,N,U,Y,he,$e,Me,Ie,qe,Ee,Be,ae;let r=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,n=(r==null?void 0:r.status)==="pending",a=S("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(T=o==null?void 0:o.backgroundColor)!=null?T:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(I=o==null?void 0:o.borderColor)!=null?I:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return a;let s=S("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=S("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",d=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(P=o==null?void 0:o.titleColor)!=null?P:"currentColor",u=be(p,20,d,2);u&&i.appendChild(u);let g=S("div","persona-flex-1 persona-min-w-0"),c=S("div","persona-flex persona-items-center persona-gap-2"),m=S("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(k=o==null?void 0:o.title)!=null?k:"Approval Required",c.appendChild(m),!n){let Q=S("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",r.status),r.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"):r.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"):r.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"),c.appendChild(Q)}g.appendChild(c);let C=r.toolType==="webmcp"||r.toolName.startsWith(Ko)?Al(r.toolName):void 0,R=(N=o==null?void 0:o.formatDescription)==null?void 0:N.call(o,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...C?{displayTitle:C}:{},...r.reason?{reason:r.reason}:{}}),M=!r.toolName,A=R||(M?r.description:`The assistant wants to use \u201C${C!=null?C:jb(r.toolName)}\u201D.`),L=S("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(L.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(L.style.color=o.descriptionColor),L.textContent=A,g.appendChild(L),r.reason){let Q=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");Q.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?Q.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(Q.style.color=o.descriptionColor);let pe=S("span","persona-font-medium");pe.textContent=`${(U=o==null?void 0:o.reasonLabel)!=null?U:"Agent's stated reason:"} `,Q.appendChild(pe),Q.appendChild(document.createTextNode(r.reason)),g.appendChild(Q)}let y=(Y=o==null?void 0:o.detailsDisplay)!=null?Y:"collapsed",w=!!r.description&&!M,b=w||!!r.parameters;if(y!=="hidden"&&b){let Q=Mh(e.id,t),pe=S("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");pe.type="button",pe.setAttribute("data-expand-header","true"),pe.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(pe.style.color=o.descriptionColor);let ye=S("span");ye.setAttribute("data-approval-details-label","true");let ne=S("span","persona-inline-flex persona-items-center");ne.setAttribute("data-approval-details-chevron","true"),pe.append(ye,ne),Th(pe,Q,t),g.appendChild(pe);let K=S("div");if(K.setAttribute("data-approval-details","true"),K.style.display=Q?"":"none",w){let oe=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(oe.style.color=o.descriptionColor),oe.textContent=r.description,K.appendChild(oe)}if(r.parameters){let oe=S("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");o!=null&&o.parameterBackgroundColor&&(oe.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(oe.style.color=o.parameterTextColor),oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",oe.textContent=Ma(r.parameters),K.appendChild(oe)}g.appendChild(K)}if(n){let Q=S("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let pe=S("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");pe.type="button",pe.style.backgroundColor=(he=o==null?void 0:o.approveButtonColor)!=null?he:"var(--persona-approval-approve-bg, #22c55e)",pe.style.color=($e=o==null?void 0:o.approveButtonTextColor)!=null?$e:"#ffffff",pe.setAttribute("data-approval-action","approve");let ye=be("shield-check",14,(Me=o==null?void 0:o.approveButtonTextColor)!=null?Me:"#ffffff",2);ye&&(ye.style.marginRight="4px",pe.appendChild(ye));let ne=document.createTextNode((Ie=o==null?void 0:o.approveLabel)!=null?Ie:"Approve");pe.appendChild(ne);let K=S("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(qe=o==null?void 0:o.denyButtonColor)!=null?qe:"transparent",K.style.color=(Ee=o==null?void 0:o.denyButtonTextColor)!=null?Ee:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let oe=be("shield-x",14,(Be=o==null?void 0:o.denyButtonTextColor)!=null?Be:"var(--persona-feedback-error, #dc2626)",2);oe&&(oe.style.marginRight="4px",K.appendChild(oe));let Ge=document.createTextNode((ae=o==null?void 0:o.denyLabel)!=null?ae:"Deny");K.appendChild(Ge),Q.append(pe,K),g.appendChild(Q)}return s.append(i,g),a.appendChild(s),a};var kh=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,p,d)=>{e.innerHTML="",t.length=0;let u=(d==null?void 0:d.agentPushed)===!0;if(u||(r=null),!n||!n.length||!u&&(i!=null?i:a?a.getMessages():[]).some(R=>R.role==="user"))return;let g=document.createDocumentFragment(),c=a?a.isStreaming():!1,m=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(n.forEach(x=>{let C=S("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");C.type="button",C.textContent=x,C.disabled=c,p!=null&&p.fontFamily&&(C.style.fontFamily=m(p.fontFamily)),p!=null&&p.fontWeight&&(C.style.fontWeight=p.fontWeight),p!=null&&p.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p!=null&&p.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",u&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),a.sendMessage(x))}),g.appendChild(C),t.push(C)}),e.appendChild(g),u){let x=JSON.stringify(n);x!==r&&(r=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var As=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;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),(r=this.store)==null||r.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 r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of r)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.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 Ms=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let n=o.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}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 o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(o){r(o)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}};var Gb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Kb=new Set(["step_start","execution_start"]),Xb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Jb=new Set(["step_complete","agent_turn_complete"]),Qb=new Set(["flow_complete","agent_complete"]),Lh=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Rh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eo=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,oa=(e,t)=>{let r=e[t];return Rh(r)?r:void 0};function sc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Xi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Yb(e,t){return typeof t.type=="string"?t.type:e}function Zb(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 ev(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 Ph(e){var o,n,a,s,i;let t=oa(e,"result"),r=[oa(e,"tokens"),oa(e,"totalTokens"),t?oa(t,"tokens"):void 0,oa(e,"usage"),t?oa(t,"usage"):void 0];for(let p of r){if(!p)continue;let d=(n=(o=eo(p.output))!=null?o:eo(p.outputTokens))!=null?n:eo(p.completionTokens);if(d!==void 0)return d}return(i=(a=eo(e.outputTokens))!=null?a:eo(e.completionTokens))!=null?i:t?(s=eo(t.outputTokens))!=null?s:eo(t.completionTokens):void 0}function tv(e){var r,o,n,a,s;let t=oa(e,"result");return(s=(n=(o=(r=eo(e.executionTime))!=null?r:eo(e.executionTimeMs))!=null?o:eo(e.execution_time))!=null?n:eo(e.duration))!=null?s:t?(a=eo(t.executionTime))!=null?a:eo(t.executionTimeMs):void 0}function rv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ts=class{constructor(t=rv){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 r=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:Xi(this.metric.outputTokens,r)}}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,r){var a;if(!Rh(r)){Lh.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Yb(t,r),n=this.now();if(Gb.has(o)){this.startRun(n);return}if(Kb.has(o)){this.run||this.startRun(n);return}if(Xb.has(o)){if(!ev(o,r))return;let s=Zb(r);if(!s)return;this.run||this.startRun(n);let i=this.run;(a=i.firstDeltaAt)!=null||(i.firstDeltaAt=n),i.visibleCharCount+=s.length;let p=i.exactOutputTokens+sc(i.visibleCharCount),d=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Xi(p,d),outputTokens:p,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Jb.has(o)){if(!this.run)return;let s=this.run,i=Ph(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let p=s.exactOutputTokens>0,d=s.exactOutputTokens+sc(s.visibleCharCount),u=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:Xi(d,u),outputTokens:d,durationMs:u,source:p?"usage":"estimate"};return}if(Qb.has(o)){if(!this.run)return;let s=this.run,i=Ph(r),p=i!=null?i:s.exactOutputTokens+sc(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:Xi(p,u),outputTokens:p,durationMs:u,source:d},this.run=null;return}if(Lh.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,r,o){let n=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(n!==void 0&&n>=250)return n;let a=tv(r);return a!=null?a:o-t.startedAt}};function Fa(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var ov={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)"}},nv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},av=["flowName","stepName","reasoningText","text","name","tool","toolName"],sv=100;function iv(e,t){let r={...ov,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return nv}function lv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function dv(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${o}:${n}.${a}`}function pv(e,t){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let o of t){let n=o.split("."),a=r;for(let s of n)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function cv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),r()})}function uv(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 fv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function mv(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 gv(e,t,r){let o,n;try{n=JSON.parse(e.payload),o=JSON.stringify(n,null,2)}catch{n=e.payload,o=e.payload}let a=t.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&r){let i=a.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:n});if(i)return i}return s();function s(){let i=S("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=S("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,i.appendChild(p),i}}function ic(e,t,r,o,n,a,s,i){var c;let p=n.has(e.id),d=S("div","persona-border-b persona-border-persona-divider persona-text-xs");Fa(d,(c=o.classNames)==null?void 0:c.eventRow);let u=s.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>g(),isExpanded:p,onToggleExpand:()=>a(e.id)});if(m)return d.appendChild(m),d}return d.appendChild(g()),d;function g(){var U,Y;let m=S("div",""),x=S("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");x.setAttribute("data-event-id",e.id);let C=S("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),R=be(p?"chevron-down":"chevron-right","14px","currentColor",2);R&&C.appendChild(R);let M=S("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(U=o.timestampFormat)!=null?U:"relative";M.textContent=A==="relative"?lv(e.timestamp,r):dv(e.timestamp);let L=null;o.showSequenceNumbers!==!1&&(L=S("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(t+1));let y=iv(e.type,o.badgeColors),w=S("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=y.bg,w.style.color=y.text,w.style.borderColor=y.text+"50",w.textContent=e.type;let b=(Y=o.descriptionFields)!=null?Y:av,T=pv(e.payload,b),I=null;T&&(I=S("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),I.textContent=T);let P=S("div","persona-flex-1 persona-min-w-0"),k=S("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"),N=be("clipboard","12px","currentColor",1.5);return N&&k.appendChild(N),k.addEventListener("click",async he=>{he.stopPropagation(),await cv(uv(e)),k.innerHTML="";let $e=be("check","12px","currentColor",1.5);$e&&k.appendChild($e),setTimeout(()=>{k.innerHTML="";let Me=be("clipboard","12px","currentColor",1.5);Me&&k.appendChild(Me)},1500)}),x.appendChild(C),x.appendChild(M),L&&x.appendChild(L),x.appendChild(w),I&&x.appendChild(I),x.appendChild(P),x.appendChild(k),m.appendChild(x),p&&m.appendChild(gv(e,s,i)),m}}function Ih(e){var x,C,R,M,A;let{buffer:t,getFullHistory:r,onClose:o,config:n,plugins:a=[],getThroughput:s}=e,i=(x=n==null?void 0:n.features)==null?void 0:x.scrollToBottom,p=(i==null?void 0:i.enabled)!==!1,d=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",u=(R=i==null?void 0:i.label)!=null?R:"",g=(A=(M=n==null?void 0:n.features)==null?void 0:M.eventStream)!=null?A:{},c=a.find(L=>L.renderEventStreamView);if(c!=null&&c.renderEventStreamView&&n){let L=c.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return m();function m(){let L=g.classNames,y=S("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Fa(y,L==null?void 0:L.panel);let w=[],b="",T="",I=null,P=[],k={},N=0,U=Ri(),Y=0,he=0,$e=!1,Me=null,Ie=!1,qe=0,Ee=new Set,Be=new Map,ae="",Q="",pe=null,ye,ne,K,oe,Ge,Z=null,se=null,We=null;function Ct(){let j=S("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),le=S("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");Fa(le,L==null?void 0:L.headerBar);let Ae=S("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ae.textContent="Events",ye=S("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"),ye.textContent="0",s){se=S("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),se.style.cursor="help";let to=S("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");to.textContent="Throughput",Z=S("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",We=S("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"),We.style.display="none",We.style.pointerEvents="none";let Ar=se,tr=We,Wr=()=>{if(!tr.textContent)return;let yt=Ar.getBoundingClientRect(),Or=j.getBoundingClientRect();tr.style.left=`${yt.left-Or.left}px`,tr.style.top=`${yt.bottom-Or.top+4}px`,tr.style.display="block"},wo=()=>{tr.style.display="none"};se.addEventListener("mouseenter",Wr),se.addEventListener("mouseleave",wo),se.appendChild(to),se.appendChild(Z)}let xt=S("div","persona-flex-1");ne=S("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Zt=S("option","");Zt.value="",Zt.textContent="All events",ne.appendChild(Zt),K=S("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),K.type="button",K.title="Copy All";let fr=be("clipboard-copy","12px","currentColor",1.5);fr&&K.appendChild(fr);let Ht=S("span","persona-text-xs");Ht.textContent="Copy All",K.appendChild(Ht),le.appendChild(Ae),le.appendChild(ye),se&&le.appendChild(se),le.appendChild(xt),le.appendChild(ne),le.appendChild(K);let et=S("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Fa(et,L==null?void 0:L.searchBar);let Wt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),st=S("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Wt&&st.appendChild(Wt),oe=S("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"),Fa(oe,L==null?void 0:L.searchInput),oe.type="text",oe.placeholder="Search event payloads...",Ge=S("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"),Ge.type="button",Ge.style.display="none";let Gt=be("x","12px","currentColor",2);return Gt&&Ge.appendChild(Gt),et.appendChild(st),et.appendChild(oe),et.appendChild(Ge),j.appendChild(le),j.appendChild(et),We&&j.appendChild(We),j}let Lt,mt=a.find(j=>j.renderEventStreamToolbar);if(mt!=null&&mt.renderEventStreamToolbar&&n){let j=mt.renderEventStreamToolbar({config:n,defaultRenderer:()=>Ct(),eventCount:t.getSize(),filteredCount:0,onFilterChange:le=>{b=le,Rt(),yr()},onSearchChange:le=>{T=le,Rt(),yr()}});Lt=j!=null?j:Ct()}else Lt=Ct();let Oe=S("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");Oe.style.display="none";function fe(){if(!s||!Z||!se)return;let j=s();Z.textContent=fv(j);let le=mv(j);We&&(We.textContent=le,le||(We.style.display="none")),le?se.setAttribute("aria-label",le):se.removeAttribute("aria-label")}let Ye=S("div","persona-flex-1 persona-min-h-0 persona-relative"),X=S("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let ie=S("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");Fa(ie,L==null?void 0:L.scrollIndicator),ie.style.display="none",ie.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let ve=be(d,"14px","currentColor",2);ve&&ie.appendChild(ve);let Ve=S("span","");Ve.textContent=u,ie.appendChild(Ve);let Pt=S("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Pt.style.display="none",Ye.appendChild(X),Ye.appendChild(Pt),Ye.appendChild(ie),y.setAttribute("tabindex","0"),y.appendChild(Lt),y.appendChild(Oe),y.appendChild(Ye);function we(){let j=t.getAll(),le={};for(let Ht of j)le[Ht.type]=(le[Ht.type]||0)+1;let Ae=Object.keys(le).sort(),xt=Ae.length!==P.length||!Ae.every((Ht,et)=>Ht===P[et]),Zt=!xt&&Ae.some(Ht=>le[Ht]!==k[Ht]),er=j.length!==Object.values(k).reduce((Ht,et)=>Ht+et,0);if(!xt&&!Zt&&!er||(P=Ae,k=le,!ne))return;let fr=ne.value;if(ne.options[0].textContent="All events",xt){for(;ne.options.length>1;)ne.remove(1);for(let Ht of Ae){let et=S("option","");et.value=Ht,et.textContent=`${Ht} (${le[Ht]||0})`,ne.appendChild(et)}fr&&Ae.includes(fr)?ne.value=fr:fr&&(ne.value="",b="")}else for(let Ht=1;Ht<ne.options.length;Ht++){let et=ne.options[Ht];et.textContent=`${et.value} (${le[et.value]||0})`}}function ce(){let j=t.getAll();if(b&&(j=j.filter(le=>le.type===b)),T){let le=T.toLowerCase();j=j.filter(Ae=>Ae.type.toLowerCase().includes(le)||Ae.payload.toLowerCase().includes(le))}return j}function xr(){return b!==""||T!==""}function Rt(){N=0,Y=0,U.resume(),ie.style.display="none"}function ar(j){Ee.has(j)?Ee.delete(j):Ee.add(j),pe=j;let le=X.scrollTop,Ae=U.isFollowing();Ie=!0,U.pause(),yr(),X.scrollTop=le,Ae&&U.resume(),Ie=!1}function Co(){return Zn(X,50)}function yr(){he=Date.now(),$e=!1,fe(),we();let j=t.getEvictedCount();j>0?(Oe.textContent=`${j.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",w=ce();let le=w.length,Ae=t.getSize()>0;ye&&(ye.textContent=String(t.getSize())),le===0&&Ae&&xr()?(Pt.textContent=T?`No events matching '${T}'`:"No events matching filter",Pt.style.display="",X.style.display="none"):(Pt.style.display="none",X.style.display=""),K&&(K.title=xr()?`Copy Filtered (${le})`:"Copy All"),p&&!U.isFollowing()&&le>N&&(Y+=le-N,Ve.textContent=u?`${u}${Y>0?` (${Y})`:""}`:"",ie.style.display=""),N=le;let xt=t.getAll(),Zt=xt.length>0?xt[0].timestamp:0,er=new Set(w.map(et=>et.id));for(let et of Ee)er.has(et)||Ee.delete(et);let fr=b!==ae||T!==Q,Ht=Be.size===0&&w.length>0;if(fr||Ht||w.length===0){X.innerHTML="",Be.clear();let et=document.createDocumentFragment();for(let Wt=0;Wt<w.length;Wt++){let st=ic(w[Wt],Wt,Zt,g,Ee,ar,a,n);Be.set(w[Wt].id,st),et.appendChild(st)}X.appendChild(et),ae=b,Q=T,pe=null}else{if(pe!==null){let Wt=Be.get(pe);if(Wt&&Wt.parentNode===X){let st=w.findIndex(Gt=>Gt.id===pe);if(st>=0){let Gt=ic(w[st],st,Zt,g,Ee,ar,a,n);X.insertBefore(Gt,Wt),Wt.remove(),Be.set(pe,Gt)}}pe=null}let et=new Set(w.map(Wt=>Wt.id));for(let[Wt,st]of Be)et.has(Wt)||(st.remove(),Be.delete(Wt));for(let Wt=0;Wt<w.length;Wt++){let st=w[Wt];if(!Be.has(st.id)){let Gt=ic(st,Wt,Zt,g,Ee,ar,a,n);Be.set(st.id,Gt),X.appendChild(Gt)}}}U.isFollowing()&&(X.scrollTop=X.scrollHeight)}function ze(){if(Date.now()-he>=sv){Me!==null&&(cancelAnimationFrame(Me),Me=null),yr();return}$e||($e=!0,Me=requestAnimationFrame(()=>{Me=null,yr()}))}let H=(j,le)=>{if(!K)return;K.innerHTML="";let Ae=be(j,"12px","currentColor",1.5);Ae&&K.appendChild(Ae);let xt=S("span","persona-text-xs");xt.textContent="Copy All",K.appendChild(xt),setTimeout(()=>{K.innerHTML="";let Zt=be("clipboard-copy","12px","currentColor",1.5);Zt&&K.appendChild(Zt);let er=S("span","persona-text-xs");er.textContent="Copy All",K.appendChild(er),K.disabled=!1},le)},de=async()=>{if(K){K.disabled=!0;try{let j;xr()?j=w:r?(j=await r(),j.length===0&&(j=t.getAll())):j=t.getAll();let le=j.map(Ae=>{try{return JSON.parse(Ae.payload)}catch{return Ae.payload}});await navigator.clipboard.writeText(JSON.stringify(le,null,2)),H("check",1500)}catch{H("x",1500)}}},Te=()=>{ne&&(b=ne.value,Rt(),yr())},Se=()=>{!oe||!Ge||(Ge.style.display=oe.value?"":"none",I&&clearTimeout(I),I=setTimeout(()=>{T=oe.value,Rt(),yr()},150))},Le=()=>{!oe||!Ge||(oe.value="",T="",Ge.style.display="none",I&&clearTimeout(I),Rt(),yr())},Ze=()=>{if(Ie)return;let j=X.scrollTop,{action:le,nextLastScrollTop:Ae}=Ii({following:U.isFollowing(),currentScrollTop:j,lastScrollTop:qe,nearBottom:Co(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});qe=Ae,le==="resume"?(U.resume(),Y=0,ie.style.display="none"):le==="pause"&&(U.pause(),p&&(Ve.textContent=u,ie.style.display=""))},Ke=j=>{let le=Wi({following:U.isFollowing(),deltaY:j.deltaY,nearBottom:Co(),resumeWhenNearBottom:!0});le==="pause"?(U.pause(),p&&(Ve.textContent=u,ie.style.display="")):le==="resume"&&(U.resume(),Y=0,ie.style.display="none")},dt=()=>{p&&(X.scrollTop=X.scrollHeight,U.resume(),Y=0,ie.style.display="none")},It=j=>{let le=j.target;if(!le||le.closest("button"))return;let Ae=le.closest("[data-event-id]");if(!Ae)return;let xt=Ae.getAttribute("data-event-id");xt&&ar(xt)},z=j=>{if((j.metaKey||j.ctrlKey)&&j.key==="f"){j.preventDefault(),oe==null||oe.focus(),oe==null||oe.select();return}j.key==="Escape"&&(oe&&document.activeElement===oe?(Le(),oe.blur(),y.focus()):o&&o())};K&&K.addEventListener("click",de),ne&&ne.addEventListener("change",Te),oe&&oe.addEventListener("input",Se),Ge&&Ge.addEventListener("click",Le),X.addEventListener("scroll",Ze),X.addEventListener("wheel",Ke,{passive:!0}),X.addEventListener("click",It),ie.addEventListener("click",dt),y.addEventListener("keydown",z);function ot(){I&&clearTimeout(I),Me!==null&&(cancelAnimationFrame(Me),Me=null),$e=!1,Be.clear(),K&&K.removeEventListener("click",de),ne&&ne.removeEventListener("change",Te),oe&&oe.removeEventListener("input",Se),Ge&&Ge.removeEventListener("click",Le),X.removeEventListener("scroll",Ze),X.removeEventListener("wheel",Ke),X.removeEventListener("click",It),ie.removeEventListener("click",dt),y.removeEventListener("keydown",z)}return{element:y,update:ze,destroy:ot}}}function Wh(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",n=e.status==="streaming"?"streaming":"complete",s=(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 ${r} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let p=document.createElement("div");p.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-muted, #9ca3af)",p.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=r;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let c=document.createElement("span");c.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",c.style.backgroundColor="var(--persona-primary, #171717)",c.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(c);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,g.appendChild(m)}else g.textContent=s;if(d.append(u,g),i.append(p,d),n==="complete"){let c=document.createElement("button");c.type="button",c.textContent="Download",c.title=`Download ${r}`,c.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-text, #1f2937)",c.style.backgroundColor="transparent",c.style.cursor="pointer",c.setAttribute("data-download-artifact",o),i.append(c)}return i}var Hh=(e,t)=>{var o,n,a;let r=(a=(n=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(r){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",p=e.status==="streaming"?"streaming":"complete",d=typeof e.artifactType=="string"?e.artifactType:"markdown",u=r({artifact:{artifactId:i,title:s,artifactType:d,status:p},config:t.config,defaultRenderer:()=>Wh(e,t)});if(u)return u}return Wh(e,t)};var lc=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}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(([r,o])=>{this.register(r,o)})}},tn=new lc;tn.register("PersonaArtifactCard",Hh);function hv(e){var n;let t=S("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=S("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let o=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((n=e.props)!=null?n:{},null,2),t.appendChild(r),t.appendChild(o),t}function Bh(e,t){var ne,K,oe,Ge;let r=(K=(ne=e.features)==null?void 0:ne.artifacts)==null?void 0:K.layout,n=((oe=r==null?void 0:r.toolbarPreset)!=null?oe:"default")==="document",a=(Ge=r==null?void 0:r.panePadding)==null?void 0:Ge.trim(),s=e.markdown?$n(e.markdown):null,i=va(e.sanitize),p=Z=>{let se=s?s(Z):Ho(Z);return i?i(se):se},d=typeof document!="undefined"?S("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{d==null||d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};d&&d.addEventListener("click",()=>{var Z;u(),(Z=t.onDismiss)==null||Z.call(t)});let g=S("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");g.setAttribute("data-persona-theme-zone","artifact-pane"),n&&g.classList.add("persona-artifact-pane-document");let c=S("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");c.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&c.classList.add("persona-artifact-toolbar-document");let m=S("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=S("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var Z;u(),(Z=t.onDismiss)==null||Z.call(t)});let C="rendered",R=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=n?cr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):cr({icon:"eye",label:"Rendered view"}),A=n?cr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):cr({icon:"code-2",label:"Source"}),L=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),y=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,w=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,b=r==null?void 0:r.documentToolbarCopyMenuItems,T=!!(w&&b&&b.length>0),I=null,P,k=null,N=null;if(n&&(y||w)&&!T){if(P=y?Ss({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):cr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let Z=be("chevron-down",14,"currentColor",2);Z&&P.appendChild(Z)}}else n&&T?(I=S("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),P=y?Ss({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):cr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=cr({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"}}),I.append(P,k)):n?P=cr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):P=cr({icon:"copy",label:"Copy"});let U=n?cr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):cr({icon:"refresh-cw",label:"Refresh"}),Y=n?cr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):cr({icon:"x",label:"Close"}),he=()=>{var Lt,mt,Oe;let Z=(Lt=Be.find(fe=>fe.id===ae))!=null?Lt:Be[Be.length-1],se=(mt=Z==null?void 0:Z.id)!=null?mt:null,We=(Z==null?void 0:Z.artifactType)==="markdown"&&(Oe=Z.markdown)!=null?Oe:"",Ct=Z?JSON.stringify({component:Z.component,props:Z.props},null,2):"";return{markdown:We,jsonPayload:Ct,id:se}},$e=async()=>{var Lt;let{markdown:Z,jsonPayload:se}=he(),We=(Lt=Be.find(mt=>mt.id===ae))!=null?Lt:Be[Be.length-1],Ct=(We==null?void 0:We.artifactType)==="markdown"?Z:We?se:"";try{await navigator.clipboard.writeText(Ct)}catch{}};if(P.addEventListener("click",async()=>{let Z=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(Z&&T){let{markdown:se,jsonPayload:We,id:Ct}=he();try{await Z({actionId:"primary",artifactId:Ct,markdown:se,jsonPayload:We})}catch{}return}await $e()}),k&&(b!=null&&b.length)){let Z=()=>{var We;return(We=g.closest("[data-persona-root]"))!=null?We:document.body},se=()=>{N=kn({items:b.map(We=>({id:We.id,label:We.label})),onSelect:async We=>{let{markdown:Ct,jsonPayload:Lt,id:mt}=he(),Oe=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{Oe?await Oe({actionId:We,artifactId:mt,markdown:Ct,jsonPayload:Lt}):We==="markdown"||We==="md"?await navigator.clipboard.writeText(Ct):We==="json"||We==="source"?await navigator.clipboard.writeText(Lt):await navigator.clipboard.writeText(Ct||Lt)}catch{}},anchor:I!=null?I:k,position:"bottom-right",portal:Z()})};g.isConnected?se():requestAnimationFrame(se),k.addEventListener("click",We=>{We.stopPropagation(),N==null||N.toggle()})}U.addEventListener("click",async()=>{var Z;try{await((Z=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:Z.call(r))}catch{}pe()}),Y.addEventListener("click",()=>{var Z;u(),(Z=t.onDismiss)==null||Z.call(t)});let Me=()=>{n&&(M.setAttribute("aria-pressed",C==="rendered"?"true":"false"),A.setAttribute("aria-pressed",C==="source"?"true":"false"))};M.addEventListener("click",()=>{C="rendered",Me(),pe()}),A.addEventListener("click",()=>{C="source",Me(),pe()});let Ie=S("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");n?(c.replaceChildren(),R.append(M,A),I?L.append(I,U,Y):L.append(P,U,Y),c.append(R,Ie,L),Me()):(c.appendChild(m),c.appendChild(x)),a&&(c.style.paddingLeft=a,c.style.paddingRight=a);let qe=S("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"),Ee=S("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(qe.style.paddingLeft=a,qe.style.paddingRight=a,Ee.style.padding=a),g.appendChild(c),g.appendChild(qe),g.appendChild(Ee);let Be=[],ae=null,Q=!1,pe=()=>{var Ct,Lt,mt,Oe;let Z=n&&Be.length<=1;qe.classList.toggle("persona-hidden",Z),qe.replaceChildren();for(let fe of Be){let Ye=S("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");Ye.type="button",Ye.textContent=fe.title||fe.id.slice(0,8),fe.id===ae&&Ye.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ye.addEventListener("click",()=>t.onSelect(fe.id)),qe.appendChild(Ye)}Ee.replaceChildren();let se=ae&&Be.find(fe=>fe.id===ae)||Be[Be.length-1];if(!se)return;if(n){let fe=se.artifactType==="markdown"?"MD":(Ct=se.component)!=null?Ct:"Component",X=(se.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ie.textContent=`${X} \xB7 ${fe}`}else m.textContent="Artifacts";if(se.artifactType==="markdown"){if(n&&C==="source"){let Ye=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ye.textContent=(Lt=se.markdown)!=null?Lt:"",Ee.appendChild(Ye);return}let fe=S("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");fe.innerHTML=p((mt=se.markdown)!=null?mt:""),Ee.appendChild(fe);return}let We=se.component?tn.get(se.component):void 0;if(We){let Ye={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=We((Oe=se.props)!=null?Oe:{},Ye);if(X){Ee.appendChild(X);return}}catch{}}Ee.appendChild(hv(se))},ye=()=>{var se;let Z=Be.length>0;if(g.classList.toggle("persona-hidden",!Z),d){let We=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,Lt=((se=We==null?void 0:We.classList.contains("persona-artifact-narrow-host"))!=null?se:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Z&&Lt&&Q?(d.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:d,update(Z){var se,We,Ct;Be=Z.artifacts,ae=(Ct=(We=Z.selectedId)!=null?We:(se=Z.artifacts[Z.artifacts.length-1])==null?void 0:se.id)!=null?Ct:null,Be.length>0&&(Q=!0),pe(),ye()},setMobileOpen(Z){Q=Z,!Z&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):ye()}}}function co(e){var t,r;return((r=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:r.enabled)===!0}function Dh(e,t){var a,s,i,p;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!co(t))return;let r=(s=(a=t.features)==null?void 0:a.artifacts)==null?void 0:s.layout,o=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),n=(p=r==null?void 0:r.paneBorderLeft)==null?void 0:p.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}function xv(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 Ji(e,t){var p,d,u,g,c,m,x,C,R,M;if(!co(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"),xv(e),Dh(e,t);return}let r=(d=(p=t.features)==null?void 0:p.artifacts)==null?void 0:d.layout;e.style.setProperty("--persona-artifact-split-gap",(u=r==null?void 0:r.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(g=r==null?void 0:r.paneWidth)!=null?g:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(c=r==null?void 0:r.paneMaxWidth)!=null?c:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=r==null?void 0:r.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let n=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();n?e.style.setProperty("--persona-artifact-pane-padding",n):e.style.removeProperty("--persona-artifact-pane-padding");let a=(C=r==null?void 0:r.documentToolbarIconColor)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(R=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:R.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:M.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Dh(e,t)}var Fh=["panel","seamless"];function Qi(e,t){var i,p,d,u,g,c;for(let m of Fh)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"),!co(t))return;let r=(p=(i=t.features)==null?void 0:i.artifacts)==null?void 0:p.layout,o=(d=r==null?void 0:r.paneAppearance)!=null?d:"panel",n=Fh.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${n}`);let a=(u=r==null?void 0:r.paneBorderRadius)==null?void 0:u.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(g=r==null?void 0:r.paneShadow)==null?void 0:g.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((c=r.unifiedSplitOuterRadius)==null?void 0:c.trim())||a;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Nh(e,t){var r,o,n;return!t||!co(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function yv(e,t){if(!(e!=null&&e.trim()))return t;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):t}function bv(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 vv(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function Cv(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function Oh(e,t){var s;let o=(s=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",n=/^([\d.]+)px$/i.exec(o);if(n)return Number(n[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function _h(e,t,r,o,n,a){let s=yv(n,200),i=Cv(t,r,o,200);i=Math.max(s,i);let p=bv(a);return p!==null&&(i=Math.min(i,p)),vv(e,s,i)}var Uh={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"}},dc=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var x,C,R;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(C=Uh[s])!=null?C:Uh.init;a.classList.add("persona-form-card","persona-space-y-4");let p=S("div","persona-space-y-1"),d=S("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,p.appendChild(d),i.description){let M=S("p","persona-text-sm persona-text-persona-muted");M.textContent=i.description,p.appendChild(M)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(M=>{var b,T;let A=S("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${M.name}`;let L=S("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=M.label,A.appendChild(L);let y=(b=M.type)!=null?b:"text",w;y==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=y),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}-${s}-${M.name}`,w.name=M.name,w.placeholder=(T=M.placeholder)!=null?T:"",M.required&&(w.required=!0),A.appendChild(w),u.appendChild(A)});let g=S("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),c=S("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=S("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=(R=i.submitLabel)!=null?R:"Submit",g.appendChild(c),g.appendChild(m),u.appendChild(g),a.replaceChildren(p,u),u.addEventListener("submit",async M=>{var w,b;M.preventDefault();let A=(w=r.formEndpoint)!=null?w:"/form",L=new FormData(u),y={};L.forEach((T,I)=>{y[I]=T}),y.type=s,m.disabled=!0,c.textContent="Submitting\u2026";try{let T=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let I=await T.json();c.textContent=(b=I.message)!=null?b:"Thanks! We'll be in touch soon.",I.success&&I.nextPrompt&&await o.sendMessage(String(I.nextPrompt))}catch(T){c.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var pc=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var o;let r=this.plugins.get(t);r&&((o=r.onUnregister)==null||o.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var o,n;return((o=r.priority)!=null?o:0)-((n=t.priority)!=null?n:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let o=new Set(t.map(a=>a.id));return[...r.filter(a=>!o.has(a.id)),...t].sort((a,s)=>{var i,p;return((i=s.priority)!=null?i:0)-((p=a.priority)!=null?p:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Es=new pc;var qh=()=>{let e=new Map,t=(n,a)=>(e.has(n)||e.set(n,new Set),e.get(n).add(a),()=>r(n,a)),r=(n,a)=>{var s;(s=e.get(n))==null||s.delete(a)};return{on:t,off:r,emit:(n,a)=>{var s;(s=e.get(n))==null||s.forEach(i=>{try{i(a)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",p)}})}}};var wv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Sv=e=>{let t=e.trim(),r=t.indexOf("{");if(r===-1)return null;let o=0;for(let n=r;n<t.length;n+=1){let a=t[n];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(r,n+1)}return null},ks=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=wv(e),r=Sv(t);if(!r)return null;let o=JSON.parse(r);if(!o||typeof o!="object"||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},cc=e=>typeof e=="string"?e:e==null?"":String(e),na={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:cc(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=cc(r.element);if(o&&((n=t.document)!=null&&n.querySelector)){let a=t.document.querySelector(o);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:cc(r.text)}}},Vh=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ls=e=>{let t=new Set(Vh(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(Vh(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.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=s?e.parsers.reduce((d,u)=>d||(u==null?void 0:u({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),o();let p={action:i,message:a.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let u=()=>{e.emit("action:resubmit",p)},g=d(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let c=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:c,resubmit:g.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:r}};var Av=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}},Mv=e=>e.map(t=>({...t,streaming:!1})),Tv=e=>e.map(t=>({...t,status:"complete"})),Yi=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Av(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?Mv(r.messages):void 0,artifacts:r.artifacts?Tv(r.artifacts):void 0};o.setItem(e,JSON.stringify(n))}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",n)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Na=ya(Ks(),1);function Ev(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function kv(e,t){if(!Ev(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:t}}function Zi(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e;try{let n=(0,Na.parse)(r,Na.STR|Na.OBJ),a=kv(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function zh(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function el(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=tn.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:r,updateProps:i=>{n&&n(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function $h(){let e=Zi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function jh(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 tl(e){let t=jh(e);if(!t)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function rl(e){let t=jh(e);if(!t)return null;try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let o=r;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Lv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ol(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:d=Lv}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let g=null,c=document.createElement("div");c.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,m.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=n,m.appendChild(C),c.appendChild(m);let R=document.createElement("div");R.className="persona-feedback-rating persona-feedback-rating-csat",R.setAttribute("role","radiogroup"),R.setAttribute("aria-label","Satisfaction rating from 1 to 5");let M=[];for(let b=1;b<=5;b++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-star-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`${b} star${b>1?"s":""}: ${d[b-1]}`),T.title=d[b-1],T.dataset.rating=String(b),T.innerHTML=`
28
+ `,r.addEventListener("click",t);let o=a=>{var T,y,S,v,M,I,H,R,D,O,Q,me,ce;let s=(T=a.launcher)!=null?T:{},i=sr(a),c=r.querySelector("[data-role='launcher-title']");if(c){let ee=(y=s.title)!=null?y:"Chat Assistant";c.textContent=ee,c.setAttribute("title",ee)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let ee=(S=s.subtitle)!=null?S:"Here to help you get answers fast";l.textContent=ee,l.setAttribute("title",ee)}let p=r.querySelector(".persona-flex-col");p&&(s.textHidden||i?p.style.display="none":p.style.display="");let f=r.querySelector("[data-role='launcher-icon']");if(f)if(s.agentIconHidden)f.style.display="none";else{let ee=(v=s.agentIconSize)!=null?v:"40px";if(f.style.height=ee,f.style.width=ee,f.innerHTML="",s.agentIconName){let Ce=parseFloat(ee)||24,Ie=fe(s.agentIconName,Ce*.6,"var(--persona-text-inverse, #ffffff)",2);Ie?(f.appendChild(Ie),f.style.display=""):(f.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}",f.style.display="")}else s.iconUrl?f.style.display="none":(f.textContent=(I=s.agentIconText)!=null?I:"\u{1F4AC}",f.style.display="")}let u=r.querySelector("[data-role='launcher-image']");if(u){let ee=(H=s.agentIconSize)!=null?H:"40px";u.style.height=ee,u.style.width=ee,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(u.src=s.iconUrl,u.style.display="block"):u.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ee=(R=s.callToActionIconSize)!=null?R:"32px";m.style.height=ee,m.style.width=ee,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Ce=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,Ce=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let Ie=parseFloat(ee)||24,le=Math.max(Ie-Ce,8),ve=fe(s.callToActionIconName,le,"currentColor",2);ve?m.appendChild(ve):m.textContent=(D=s.callToActionIconText)!=null?D:"\u2197"}else m.textContent=(O=s.callToActionIconText)!=null?O:"\u2197"}let x=s.position&&So[s.position]?So[s.position]:So["bottom-right"],b="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",L="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";r.className=i?L:`${b} ${x}`,i||(r.style.zIndex=String((Q=s.zIndex)!=null?Q:Tr));let E="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(me=s.border)!=null?me:E,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(ce=s.collapsedMaxWidth)!=null?ce:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},n=()=>{r.removeEventListener("click",t),r.remove()};return e&&o(e),{element:r,update:o,destroy:n}};var Mh=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=Sh(e),a=Ah(e,t),s={wrapper:r,panel:o,pillRoot:n},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},l={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:c,composer:l,replaceHeader:u=>(c.element.replaceWith(u.header),c.element=u.header,c.iconHolder=u.iconHolder,c.headerTitle=u.headerTitle,c.headerSubtitle=u.headerSubtitle,c.closeButton=u.closeButton,c.closeButtonWrapper=u.closeButtonWrapper,c.clearChatButton=u.clearChatButton,c.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{l.footer.replaceWith(u),l.footer=u}}},ep=({config:e,plugins:t,onToggle:r})=>{let o=t.find(a=>a.renderLauncher);if(o!=null&&o.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>Zc(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=Zc(e,r);return{instance:n,element:n.element}};var Vb=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}},zb=(e,t)=>{if(!e)return null;let r=Vb(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},$b=(e,t)=>{let r=C("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},jb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},tp=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(":"))},rp=320,Eh=320,Gb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Kb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Xb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Jb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Qb=(e,t,r)=>{if(e.length===0)return null;try{let o=C("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,c)=>{var f;let l=C("img");l.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${c+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${rp}px`,l.style.maxHeight=`${Eh}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;n+=1,l.addEventListener("error",()=>{p||(p=!0,n=Math.max(0,n-1),l.remove(),n===0&&s())}),l.addEventListener("load",()=>{p=!0}),jb(i.image)?(l.src=i.image,o.appendChild(l)):(p=!0,n=Math.max(0,n-1),l.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},Yb=e=>{if(e.length===0)return null;try{let t=C("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!tp(o.audio))return;let n=C("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${rp}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Zb=e=>{if(e.length===0)return null;try{let t=C("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!tp(o.video))return;let n=C("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${rp}px`,n.style.maxHeight=`${Eh}px`,n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},ev=e=>{if(e.length===0)return null;try{let t=C("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!tp(o.data))return;let n=C("a");n.href=o.data,n.download=o.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=o.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},aa=()=>{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 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="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(o),e.appendChild(n),e},op=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:aa};if(t){let n=t(o);if(n!==null)return n}return aa()},tv=(e,t)=>{let r=C("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"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let n=C("img");n.src=o,n.alt=t==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(n)}else r.textContent=o,r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},Th=(e,t,r="div")=>{let o=C(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?o.textContent=t.format(n):o.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},rv=(e,t="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.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 r},np=(e,t,r)=>{var x,b,L,E,A,T,y;let o=(x=t.showCopy)!=null?x:!0,n=(b=t.showUpvote)!=null?b:!0,a=(L=t.showDownvote)!=null?L:!0,s=(E=t.showReadAloud)!=null?E:!1;if(!o&&!n&&!a&&!s){let S=C("div");return S.style.display="none",S.id=`actions-${e.id}`,S.setAttribute("data-actions-for",e.id),S}let i=(A=t.visibility)!=null?A:"hover",c=(T=t.align)!=null?T:"right",l=(y=t.layout)!=null?y:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[c],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[l],u=C("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let m=(S,v,M)=>{let I=ur({icon:S,label:v,size:14,className:"persona-message-action-btn"});return I.setAttribute("data-action",M),I};return o&&u.appendChild(m("copy","Copy message","copy")),s&&u.appendChild(m("volume-2","Read aloud","read-aloud")),n&&u.appendChild(m("thumbs-up","Upvote","upvote")),a&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},Oa=(e,t,r,o,n,a)=>{var ae,se,pe,ze,_e,K,J,Se,Y,ie,Re,rt,bt,qt,Gt,at,Ne;let s=r!=null?r:{},i=(ae=s.layout)!=null?ae:"bubble",c=s.avatar,l=s.timestamp,p=(se=c==null?void 0:c.show)!=null?se:!1,f=(pe=l==null?void 0:l.show)!=null?pe:!1,u=(ze=c==null?void 0:c.position)!=null?ze:"left",m=(_e=l==null?void 0:l.position)!=null?_e:"below",x=rv(e.role,i),b=C("div",x.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=Gb(e),E=(J=(K=e.content)==null?void 0:K.trim())!=null?J:"",T=L.length>0&&E===ui,y=Fi((Y=(Se=a==null?void 0:a.widgetConfig)==null?void 0:Se.features)==null?void 0:Y.streamAnimation),S=(rt=(Re=(ie=a==null?void 0:a.widgetConfig)==null?void 0:ie.features)==null?void 0:Re.streamAnimation)==null?void 0:rt.plugins,v=e.role==="assistant"&&y.type!=="none"?Ss(y.type,S):null,M=e.role==="assistant"&&((bt=v==null?void 0:v.isAnimating)==null?void 0:bt.call(v,e))===!0,I=e.role==="assistant"&&v!==null&&(!!e.streaming||M);I&&(v!=null&&v.bubbleClass)&&b.classList.add(v.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),e.streaming&&H.classList.add("persona-content-streaming"),I&&v&&(v.containerClass&&H.classList.add(v.containerClass),H.style.setProperty("--persona-stream-step",`${y.speed}ms`),H.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let R=I?Ni((qt=e.content)!=null?qt:"",y.buffer,v,e,!!e.streaming):(Gt=e.content)!=null?Gt:"",D=t({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=D;I&&(v==null?void 0:v.wrap)==="char"?O=As(D,"char",e.id,{skipTags:v.skipTags}):I&&(v==null?void 0:v.wrap)==="word"&&(O=As(D,"word",e.id,{skipTags:v.skipTags}));let Q=null;if(T?(Q=document.createElement("div"),Q.innerHTML=O,Q.style.display="none",H.appendChild(Q)):H.innerHTML=O,I&&(v!=null&&v.useCaret)&&!T&&E){let G=Oi(),je=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),$e=je[je.length-1];if($e!=null&&$e.parentNode)$e.parentNode.insertBefore(G,$e.nextSibling);else{let ye=H.lastElementChild;ye?ye.appendChild(G):H.appendChild(G)}}if(f&&m==="inline"&&e.createdAt){let G=Th(e,l,"span");G.classList.add("persona-timestamp-inline");let je=H.lastElementChild;je?je.appendChild(G):H.appendChild(G)}if(L.length>0){let G=Qb(L,!T&&!!E,()=>{T&&Q&&(Q.style.display="")});G?b.appendChild(G):T&&Q&&(Q.style.display="")}let me=Kb(e);if(me.length>0){let G=Yb(me);G&&b.appendChild(G)}let ce=Xb(e);if(ce.length>0){let G=Zb(ce);G&&b.appendChild(G)}let ee=Jb(e);if(ee.length>0){let G=ev(ee);G&&b.appendChild(G)}if(b.appendChild(H),f&&m==="below"&&e.createdAt){let G=Th(e,l);G.classList.add("persona-mt-1"),b.appendChild(G)}let Ce=e.role==="assistant"?zb(e.stopReason,(Ne=(at=a==null?void 0:a.widgetConfig)==null?void 0:at.copy)==null?void 0:Ne.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let G=!!(R&&R.trim()),je=y.placeholder==="skeleton",$e=je&&y.buffer==="line"&&G;if(G)$e&&b.appendChild(Ms());else if(je)b.appendChild(Ms());else{let ye=op("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);ye&&b.appendChild(ye)}}if(Ce&&e.stopReason&&!e.streaming&&(E||(H.style.display="none"),b.appendChild($b(e.stopReason,Ce))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let G=np(e,o,n);b.appendChild(G)}if(!p||e.role==="system")return b;let le=C("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=tv(c,e.role);return u==="right"||u==="left"&&e.role==="user"?le.append(b,ve):le.append(ve,b),b.classList.remove("persona-max-w-[85%]"),b.classList.add("persona-max-w-[calc(85%-2.5rem)]"),le},kh=(e,t,r,o,n,a)=>{let s=r!=null?r:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Oa(e,t,r,o,n,a)};var _a=new Set,ov=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),nv=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
29
+ `):""},Lh=(e,t)=>{let r=_a.has(e),o=t.querySelector('button[data-expand-header="true"]'),n=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!n)return;o.setAttribute("aria-expanded",r?"true":"false");let s=o.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=fe(r?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=r?"Hide":"Show"}n.style.display=r?"":"none",a&&(a.style.display=r?"none":a.textContent||a.childNodes.length?"":"none")},ap=(e,t)=>{var ce,ee,Ce,Ie,le,ve,ae,se,pe,ze,_e;let r=e.reasoning,o=C("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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!r)return o;let n=(ee=(ce=t==null?void 0:t.features)==null?void 0:ce.reasoningDisplay)!=null?ee:{},a=n.expandable!==!1,s=a&&_a.has(e.id),i=r.status!=="complete",c=nv(e,(Ce=n.previewMaxLines)!=null?Ce:3),l=C("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");l.type="button",a&&(l.setAttribute("aria-expanded",s?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=C("div","persona-flex persona-flex-col persona-text-left"),f=C("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",m=(Ie=t==null?void 0:t.reasoning)!=null?Ie:{},x=String((le=r.startedAt)!=null?le:Date.now()),b=()=>{let K=C("span","");return K.setAttribute("data-tool-elapsed",x),K.textContent=ai(r),K},L=(ve=m.renderCollapsedSummary)==null?void 0:ve.call(m,{message:e,reasoning:r,defaultSummary:u,previewText:c,isActive:i,config:t!=null?t:{},elapsed:ai(r),createElapsedElement:b});typeof L=="string"&&L.trim()?(f.textContent=L,p.appendChild(f)):L instanceof HTMLElement?p.appendChild(L):(f.textContent=u,p.appendChild(f));let E=C("span","persona-text-xs persona-text-persona-primary");E.textContent=Ig(r),p.appendChild(E);let A=(ae=n.loadingAnimation)!=null?ae:"none",T=m.activeTextTemplate,y=m.completeTextTemplate,S=i?T:y,v=L instanceof HTMLElement,M=(K,J,Se)=>{let Y=Se;for(let ie of J){let Re=C("span","persona-tool-char");Re.style.setProperty("--char-index",String(Y)),Re.textContent=ie===" "?"\xA0":ie,K.appendChild(Re),Y++}return Y},I=(K,J)=>{f.textContent="";let Se=si(K,""),Y=0;for(let ie of Se){let Re=ie.styles.length>0?(()=>{let rt=C("span",ie.styles.map(bt=>`persona-tool-text-${bt}`).join(" "));return f.appendChild(rt),rt})():f;if(ie.isDuration&&i)Re.appendChild(b());else{let rt=ie.isDuration?ai(r):ie.text;J?Y=M(Re,rt,Y):Re.appendChild(document.createTextNode(rt))}}};if(!v&&S)if(E.style.display="none",f.style.display="",i&&A!=="none"){let K=(se=m.loadingAnimationDuration)!=null?se:2e3;f.setAttribute("data-preserve-animation","true"),A==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),I(S,!1)):(f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),I(S,!0))}else I(S,!1);else if(!v&&i&&A!=="none"){f.style.display="";let K=(pe=m.loadingAnimationDuration)!=null?pe:2e3;if(f.setAttribute("data-preserve-animation","true"),A==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let J=f.textContent||u;f.textContent="",M(f,J,0)}r.status==="complete"&&(f.style.display="none")}else v||(r.status==="complete"?f.style.display="none":f.style.display="");let H=null;if(a){H=C("div","persona-flex persona-items-center");let J=fe(s?"chevron-up":"chevron-down",16,"currentColor",2);J?H.appendChild(J):H.textContent=s?"Hide":"Show";let Se=C("div","persona-flex persona-items-center persona-ml-auto");Se.append(H),l.append(p,Se)}else l.append(p);let R=C("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!s&&i&&n.activePreview&&c){let K=(_e=(ze=t==null?void 0:t.reasoning)==null?void 0:ze.renderCollapsedPreview)==null?void 0:_e.call(ze,{message:e,reasoning:r,defaultPreview:c,isActive:i,config:t!=null?t:{}});ov(R,K)||(R.textContent=c),R.style.display=""}if(!s&&i&&n.activeMinHeight&&(o.style.minHeight=n.activeMinHeight),!a)return o.append(l,R),o;let D=C("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");D.style.display=s?"":"none";let O=r.chunks.join(""),Q=C("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Q.textContent=O||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),D.appendChild(Q),(()=>{if(l.setAttribute("aria-expanded",s?"true":"false"),H){H.innerHTML="";let J=fe(s?"chevron-up":"chevron-down",16,"currentColor",2);J?H.appendChild(J):H.textContent=s?"Hide":"Show"}D.style.display=s?"":"none",R.style.display=s?"none":R.textContent||R.childNodes.length?"":"none"})(),o.append(l,R,D),o};var Ua=new Set,av=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),sv=(e,t)=>{var a;let r=e.toolCall;if(!r)return"";let o=((a=r.chunks)!=null?a:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
30
+ `);let n=Mn(r.args).trim();return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
31
+ `):""},sp=(e,t)=>{var r,o,n;e.style.backgroundColor=(r=t.codeBlockBackgroundColor)!=null?r:"var(--persona-container, #f3f4f6)",e.style.borderColor=(o=t.codeBlockBorderColor)!=null?o:"var(--persona-border, #e5e7eb)",e.style.color=(n=t.codeBlockTextColor)!=null?n:"var(--persona-text, #171717)"},iv=(e,t)=>{var p,f,u,m,x;let r=e.toolCall,o=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,n=(f=o==null?void 0:o.collapsedMode)!=null?f:"tool-call",a=sv(e,(u=o==null?void 0:o.previewMaxLines)!=null?u:3),s=r?Hg(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i=r.status!=="complete",c=(m=t==null?void 0:t.toolCall)!=null?m:{},l=s;return n==="tool-name"?l=((x=r.name)==null?void 0:x.trim())||s:n==="tool-preview"&&a&&(l=a),i&&c.activeTextTemplate?l=Nl(r,c.activeTextTemplate,l):!i&&c.completeTextTemplate&&(l=Nl(r,c.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},Ph=(e,t,r)=>{var p;let o=Ua.has(e),n=(p=r==null?void 0:r.toolCall)!=null?p:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto"),l=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let f=n.toggleTextColor||n.headerTextColor||"var(--persona-primary, #171717)",u=fe(o?"chevron-up":"chevron-down",16,f,2);u?l.appendChild(u):l.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},ip=(e,t)=>{var O,Q,me,ce,ee,Ce,Ie,le,ve;let r=e.toolCall,o=(O=t==null?void 0:t.toolCall)!=null?O:{},n=C("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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),o.backgroundColor&&(n.style.backgroundColor=o.backgroundColor),o.borderColor&&(n.style.borderColor=o.borderColor),o.borderWidth&&(n.style.borderWidth=o.borderWidth),o.borderRadius&&(n.style.borderRadius=o.borderRadius),n.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return n;let a=(me=(Q=t==null?void 0:t.features)==null?void 0:Q.toolCallDisplay)!=null?me:{},s=a.expandable!==!1,i=s&&Ua.has(e.id),{summary:c,previewText:l,isActive:p}=iv(e,t),f=C("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");f.type="button",s&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let u=C("div","persona-flex persona-flex-col persona-text-left"),m=C("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let x=String((ce=r.startedAt)!=null?ce:Date.now()),b=()=>{let ae=C("span","");return ae.setAttribute("data-tool-elapsed",x),ae.textContent=fs(r),ae},L=(Ce=o.renderCollapsedSummary)==null?void 0:Ce.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:l,collapsedMode:(ee=a.collapsedMode)!=null?ee:"tool-call",isActive:p,config:t!=null?t:{},elapsed:fs(r),createElapsedElement:b});typeof L=="string"&&L.trim()?(m.textContent=L,u.appendChild(m)):L instanceof HTMLElement?u.appendChild(L):(m.textContent=c,u.appendChild(m));let E=(Ie=a.loadingAnimation)!=null?Ie:"none",A=o.activeTextTemplate,T=o.completeTextTemplate,y=p?A:T,S=L instanceof HTMLElement,v=(ae,se,pe)=>{let ze=pe;for(let _e of se){let K=C("span","persona-tool-char");K.style.setProperty("--char-index",String(ze)),K.textContent=_e===" "?"\xA0":_e,ae.appendChild(K),ze++}return ze},M=(ae,se)=>{var K;m.textContent="";let pe=((K=r.name)==null?void 0:K.trim())||"tool",ze=si(ae,pe),_e=0;for(let J of ze){let Se=J.styles.length>0?(()=>{let Y=C("span",J.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(Y),Y})():m;if(J.isDuration&&p)Se.appendChild(b());else{let Y=J.isDuration?fs(r):J.text;se?_e=v(Se,Y,_e):Se.appendChild(document.createTextNode(Y))}}};if(!S)if(p&&E!=="none"){let ae=(le=o.loadingAnimationDuration)!=null?le:2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),y&&M(y,!1);else if(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),E==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),y)M(y,!0);else{let se=m.textContent||c;m.textContent="",v(m,se,0)}}else y&&M(y,!1);let I=null;if(s){I=C("div","persona-flex persona-items-center");let ae=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",se=fe(i?"chevron-up":"chevron-down",16,ae,2);se?I.appendChild(se):I.textContent=i?"Hide":"Show";let pe=C("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");pe.append(I),f.append(u,pe)}else f.append(u);let H=C("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","tool"),H.style.display="none",H.style.whiteSpace="pre-wrap",!i&&p&&a.activePreview&&l){let ae=(ve=o.renderCollapsedPreview)==null?void 0:ve.call(o,{message:e,toolCall:r,defaultPreview:l,isActive:p,config:t!=null?t:{}});av(H,ae)||(H.textContent=l),H.style.display=""}if(!i&&p&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(f,H),n;let R=C("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",o.contentBackgroundColor&&(R.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(R.style.color=o.contentTextColor),o.contentPaddingX&&(R.style.paddingLeft=o.contentPaddingX,R.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(R.style.paddingTop=o.contentPaddingY,R.style.paddingBottom=o.contentPaddingY),r.name){let ae=C("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?ae.style.color=o.contentTextColor:o.headerTextColor&&(ae.style.color=o.headerTextColor),ae.textContent=r.name,R.appendChild(ae)}if(r.args!==void 0){let ae=C("div","persona-space-y-1"),se=C("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(se.style.color=o.labelTextColor),se.textContent="Arguments";let pe=C("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",sp(pe,o),pe.textContent=Mn(r.args),ae.append(se,pe),R.appendChild(ae)}if(r.chunks&&r.chunks.length){let ae=C("div","persona-space-y-1"),se=C("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(se.style.color=o.labelTextColor),se.textContent="Activity";let pe=C("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",sp(pe,o),pe.textContent=r.chunks.join(""),ae.append(se,pe),R.appendChild(ae)}if(r.status==="complete"&&r.result!==void 0){let ae=C("div","persona-space-y-1"),se=C("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(se.style.color=o.labelTextColor),se.textContent="Result";let pe=C("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",sp(pe,o),pe.textContent=Mn(r.result),ae.append(se,pe),R.appendChild(ae)}if(r.status==="complete"&&typeof r.duration=="number"){let ae=C("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(ae.style.color=o.contentTextColor),ae.textContent=`Duration: ${r.duration}ms`,R.appendChild(ae)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),I){I.innerHTML="";let ae=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",se=fe(i?"chevron-up":"chevron-down",16,ae,2);se?I.appendChild(se):I.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",H.style.display=i?"none":H.textContent||H.childNodes.length?"":"none"})(),n.append(f,H,R),n};var sa=new Map,Ji=e=>{let r=(e.startsWith(Co)?e.slice(Co.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(r.length===0)return e;let o=r.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Rh=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Ih=(e,t)=>{var o,n,a;let r=(n=(o=Rh(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=sa.get(e))!=null?a:r==="expanded"},Hh=(e,t,r)=>{var s,i;let o=Rh(r);e.setAttribute("aria-expanded",t?"true":"false");let n=e.querySelector("[data-approval-details-label]");n&&(n.textContent=t?(s=o==null?void 0:o.hideDetailsLabel)!=null?s:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let c=fe(t?"chevron-up":"chevron-down",14,"currentColor",2);c&&a.appendChild(c)}},Wh=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=Ih(e,r);Hh(o,a,r),n.style.display=a?"":"none"};var Qi=(e,t)=>{var M,I,H,R,D,O,Q,me,ce,ee,Ce,Ie,le,ve,ae;let r=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,n=(r==null?void 0:r.status)==="pending",a=C("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(M=o==null?void 0:o.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(I=o==null?void 0:o.borderColor)!=null?I:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return a;let s=C("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=C("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let c=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",l=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(H=o==null?void 0:o.titleColor)!=null?H:"currentColor",p=fe(c,20,l,2);p&&i.appendChild(p);let f=C("div","persona-flex-1 persona-min-w-0"),u=C("div","persona-flex persona-items-center persona-gap-2"),m=C("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(R=o==null?void 0:o.title)!=null?R:"Approval Required",u.appendChild(m),!n){let se=C("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");se.setAttribute("data-approval-status",r.status),r.status==="approved"?(se.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",se.style.color="var(--persona-palette-colors-success-700, #15803d)",se.textContent="Approved"):r.status==="denied"?(se.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",se.style.color="var(--persona-palette-colors-error-700, #b91c1c)",se.textContent="Denied"):r.status==="timeout"&&(se.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",se.style.color="var(--persona-palette-colors-warning-700, #b45309)",se.textContent="Timeout"),u.appendChild(se)}f.appendChild(u);let b=r.toolType==="webmcp"||r.toolName.startsWith(Co)?as(r.toolName):void 0,L=(D=o==null?void 0:o.formatDescription)==null?void 0:D.call(o,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...b?{displayTitle:b}:{},...r.reason?{reason:r.reason}:{}}),E=!r.toolName,A=L||(E?r.description:`The assistant wants to use \u201C${b!=null?b:Ji(r.toolName)}\u201D.`),T=C("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=A,f.appendChild(T),r.reason){let se=C("p","persona-text-sm persona-mt-1 persona-text-persona-muted");se.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?se.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(se.style.color=o.descriptionColor);let pe=C("span","persona-font-medium");pe.textContent=`${(O=o==null?void 0:o.reasonLabel)!=null?O:"Agent's stated reason:"} `,se.appendChild(pe),se.appendChild(document.createTextNode(r.reason)),f.appendChild(se)}let y=(Q=o==null?void 0:o.detailsDisplay)!=null?Q:"collapsed",S=!!r.description&&!E,v=S||!!r.parameters;if(y!=="hidden"&&v){let se=Ih(e.id,t),pe=C("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");pe.type="button",pe.setAttribute("data-expand-header","true"),pe.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(pe.style.color=o.descriptionColor);let ze=C("span");ze.setAttribute("data-approval-details-label","true");let _e=C("span","persona-inline-flex persona-items-center");_e.setAttribute("data-approval-details-chevron","true"),pe.append(ze,_e),Hh(pe,se,t),f.appendChild(pe);let K=C("div");if(K.setAttribute("data-approval-details","true"),K.style.display=se?"":"none",S){let J=C("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(J.style.color=o.descriptionColor),J.textContent=r.description,K.appendChild(J)}if(r.parameters){let J=C("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");o!=null&&o.parameterBackgroundColor&&(J.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(J.style.color=o.parameterTextColor),J.style.fontSize="0.75rem",J.style.lineHeight="1rem",J.textContent=Mn(r.parameters),K.appendChild(J)}f.appendChild(K)}if(n){let se=C("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let pe=C("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");pe.type="button",pe.style.backgroundColor=(me=o==null?void 0:o.approveButtonColor)!=null?me:"var(--persona-approval-approve-bg, #22c55e)",pe.style.color=(ce=o==null?void 0:o.approveButtonTextColor)!=null?ce:"#ffffff",pe.setAttribute("data-approval-action","approve");let ze=fe("shield-check",14,(ee=o==null?void 0:o.approveButtonTextColor)!=null?ee:"#ffffff",2);ze&&(ze.style.marginRight="4px",pe.appendChild(ze));let _e=document.createTextNode((Ce=o==null?void 0:o.approveLabel)!=null?Ce:"Approve");pe.appendChild(_e);let K=C("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(Ie=o==null?void 0:o.denyButtonColor)!=null?Ie:"transparent",K.style.color=(le=o==null?void 0:o.denyButtonTextColor)!=null?le:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let J=fe("shield-x",14,(ve=o==null?void 0:o.denyButtonTextColor)!=null?ve:"var(--persona-feedback-error, #dc2626)",2);J&&(J.style.marginRight="4px",K.appendChild(J));let Se=document.createTextNode((ae=o==null?void 0:o.denyLabel)!=null?ae:"Deny");K.appendChild(Se),se.append(pe,K),f.appendChild(se)}return s.append(i,f),a.appendChild(s),a};function lv(e){var r,o;let t=(r=e.getRootNode)==null?void 0:r.call(e);return t instanceof ShadowRoot?t:((o=e.ownerDocument)!=null?o:document).body}function Bh(e){var b;let{anchor:t,content:r,placement:o="bottom-start",offset:n=6,matchAnchorWidth:a=!1,zIndex:s=2147483e3,onOpen:i,onDismiss:c}=e,l=(b=e.container)!=null?b:lv(t),p=!1,f=null,u=()=>{if(!p)return;let L=t.getBoundingClientRect();r.style.position="fixed",a&&(r.style.minWidth=`${L.width}px`);let E=o==="top-start"||o==="top-end"?L.top-n-r.getBoundingClientRect().height:L.bottom+n,A=o==="bottom-end"||o==="top-end"?L.right-r.getBoundingClientRect().width:L.left;r.style.top=`${E}px`,r.style.left=`${A}px`},m=()=>{p&&(p=!1,f&&(f(),f=null),r.remove())},x=()=>{var S,v,M;if(p)return;p=!0,s!=null&&(r.style.zIndex=String(s)),l.appendChild(r),u();let L=(v=((S=t.ownerDocument)!=null?S:document).defaultView)!=null?v:window,E=(M=t.ownerDocument)!=null?M:document,A=()=>{if(!t.isConnected){m(),c==null||c("anchor-removed");return}u()},T=I=>{let H=typeof I.composedPath=="function"?I.composedPath():[];H.includes(r)||H.includes(t)||(m(),c==null||c("outside"))},y=L.setTimeout(()=>{E.addEventListener("pointerdown",T,!0)},0);L.addEventListener("scroll",A,!0),L.addEventListener("resize",A),f=()=>{L.clearTimeout(y),E.removeEventListener("pointerdown",T,!0),L.removeEventListener("scroll",A,!0),L.removeEventListener("resize",A)},i==null||i()};return{get isOpen(){return p},open:x,close:m,toggle:()=>p?m():x(),reposition:u,destroy:m}}function Dh(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(r=>r instanceof HTMLElement&&(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable))}var dv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Fh=(e,t)=>{let r=e.keyHandlers.get(t);r&&(document.removeEventListener("keydown",r),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},ia=(e,t)=>{Fh(e,t);let r=e.pendingOrder.indexOf(t);r!==-1&&e.pendingOrder.splice(r,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},cv=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,pv=(e,t)=>{var o,n;let r=(o=t==null?void 0:t.detailsDisplay)!=null?o:"collapsed";return(n=sa.get(e))!=null?n:r==="expanded"},lp=e=>{let t=C("span","persona-approval-kbd");return t.textContent=e,t},uv=(e,t)=>{var l,p;let r=C("span","persona-approval-title");t!=null&&t.titleColor&&(r.style.color=t.titleColor);let n=e.toolType==="webmcp"||e.toolName.startsWith(Co)?as(e.toolName):void 0,a=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(l=e.description)!=null?l:"",parameters:e.parameters,...n?{displayTitle:n}:{},...e.reason?{reason:e.reason}:{}});if(a)return r.textContent=a,r;let s=n!=null?n:Ji(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;r.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=s,r.appendChild(c),i){r.append(" from ");let f=document.createElement("strong");f.textContent=i,r.appendChild(f)}return r},fv=e=>{let t=C("div","persona-approval-resolved"),r=fe("ban",15,"currentColor",2);r&&t.appendChild(r);let o=C("span","persona-approval-resolved-name");return o.textContent=e.toolName?Ji(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},mv=(e,t,r,o,n,a,s)=>{var I,H,R,D,O,Q,me;let i=C("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o!=null&&o.backgroundColor&&(i.style.background=o.backgroundColor),o!=null&&o.borderColor&&(i.style.borderColor=o.borderColor),(o==null?void 0:o.shadow)!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let c=(I=o==null?void 0:o.detailsDisplay)!=null?I:"collapsed",l=!!r.description&&c!=="hidden",p=r.parameters!=null&&c!=="hidden",f=l||p,u=f&&pv(t.id,o),m=(H=o==null?void 0:o.showDetailsLabel)!=null?H:"Show details",x=(R=o==null?void 0:o.hideDetailsLabel)!=null?R:"Hide details",b=C("button","persona-approval-head");b.type="button",f?(b.setAttribute("data-action","toggle-params"),b.setAttribute("aria-expanded",u?"true":"false"),b.setAttribute("aria-label",u?x:m)):b.setAttribute("data-static","true");let L=C("span","persona-approval-logo"),E=fe("shield-check",16,"currentColor",2);E&&L.appendChild(E),b.appendChild(L);let A=uv(r,o);if(f){let ce=C("span","persona-approval-toggle");ce.setAttribute("aria-hidden","true");let ee=fe("chevron-down",14,"currentColor",2);ee&&ce.appendChild(ee),A.append(" "),A.appendChild(ce)}b.appendChild(A),i.appendChild(b);let T=C("div","persona-approval-body");if(f){let ce=C("div","persona-approval-details");if(ce.setAttribute("data-role","params"),ce.hidden=!u,l){let ee=C("p","persona-approval-desc");o!=null&&o.descriptionColor&&(ee.style.color=o.descriptionColor),ee.textContent=r.description,ce.appendChild(ee)}if(p){let ee=C("pre","persona-approval-params");o!=null&&o.parameterBackgroundColor&&(ee.style.background=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ee.style.color=o.parameterTextColor),ee.textContent=Mn(r.parameters),ce.appendChild(ee)}T.appendChild(ce)}if(r.reason){let ce=C("p","persona-approval-reason");o!=null&&o.reasonColor?ce.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(ce.style.color=o.descriptionColor);let ee=C("span","persona-approval-reason-label");ee.textContent=`${(D=o==null?void 0:o.reasonLabel)!=null?D:"Agent's stated reason:"} `,ce.append(ee,document.createTextNode(r.reason)),T.appendChild(ce)}let y=C("div","persona-approval-actions"),S=null,v=ce=>{o!=null&&o.approveButtonColor&&(ce.style.background=o.approveButtonColor),o!=null&&o.approveButtonTextColor&&(ce.style.color=o.approveButtonTextColor)},M=C("button","persona-approval-deny");if(M.type="button",M.setAttribute("data-action","deny"),o!=null&&o.denyButtonColor&&(M.style.background=o.denyButtonColor),o!=null&&o.denyButtonTextColor&&(M.style.color=o.denyButtonTextColor),M.append((O=o==null?void 0:o.denyLabel)!=null?O:"Deny"),s){let ce=C("div","persona-approval-split"),ee=C("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),v(ee),ee.append((Q=o==null?void 0:o.approveLabel)!=null?Q:"Always allow",lp("\u23CE"));let Ce=C("button","persona-approval-caret");Ce.type="button",Ce.setAttribute("data-action","toggle-menu"),Ce.setAttribute("aria-label","More options"),v(Ce);let Ie=fe("chevron-down",15,"currentColor",2);Ie&&Ce.appendChild(Ie),ce.append(ee,Ce),y.append(ce,M),M.append(lp("Esc"));let le=C("div","persona-approval-menu"),ve=C("button","persona-approval-menu-item");ve.type="button",ve.append("Allow once",lp("\u2318\u23CE")),le.appendChild(ve),S=Bh({anchor:ce,content:le,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,S),ve.addEventListener("click",()=>{ia(e,t.id),n()})}else{let ce=C("button","persona-approval-primary persona-approval-primary--solo");ce.type="button",ce.setAttribute("data-action","allow"),v(ce),ce.append((me=o==null?void 0:o.approveLabel)!=null?me:"Allow"),y.append(ce,M)}return T.appendChild(y),i.appendChild(T),i.addEventListener("click",ce=>{let ee=ce.target instanceof Element?ce.target.closest("[data-action]"):null;if(!ee)return;let Ce=ee.getAttribute("data-action");if(Ce==="toggle-params"){let Ie=i.querySelector('[data-role="params"]');if(Ie){let le=Ie.hidden;Ie.hidden=!le,b.setAttribute("aria-expanded",le?"true":"false"),b.setAttribute("aria-label",le?x:m),sa.set(t.id,le)}return}if(Ce==="toggle-menu"){S==null||S.toggle();return}if(Ce==="always"){ia(e,t.id),n({remember:!0});return}if(Ce==="allow"){ia(e,t.id),n();return}if(Ce==="deny"){ia(e,t.id),a();return}}),i},Nh=()=>{let e=dv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:n,deny:a,config:s})=>{let i=o==null?void 0:o.approval;if(!i)return null;let c=cv(s);if(i.status!=="pending"){if(ia(e,o.id),i.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return fv(i)}Fh(e,o.id);let l=(c==null?void 0:c.enableAlwaysAllow)===!0,p=mv(e,o,i,c,n,a,l);if(l){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let f=u=>{Dh(u)||o.id===e.latestPendingApprovalId&&(u.key!=="Escape"&&u.key!=="Enter"||(u.preventDefault(),u.stopImmediatePropagation(),ia(e,o.id),u.key==="Escape"?a():u.metaKey||u.ctrlKey?n():n({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return p}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])ia(e,o);e.latestPendingApprovalId=null}}};var Oh=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(r=null),!n||!n.length||!p&&(i!=null?i:a?a.getMessages():[]).some(L=>L.role==="user"))return;let f=document.createDocumentFragment(),u=a?a.isStreaming():!1,m=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(n.forEach(x=>{let b=C("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");b.type="button",b.textContent=x,b.disabled=u,c!=null&&c.fontFamily&&(b.style.fontFamily=m(c.fontFamily)),c!=null&&c.fontWeight&&(b.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(b.style.paddingLeft=c.paddingX,b.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(b.style.paddingTop=c.paddingY,b.style.paddingBottom=c.paddingY),b.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),a.sendMessage(x))}),f.appendChild(b),t.push(b)}),e.appendChild(f),p){let x=JSON.stringify(n);x!==r&&(r=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var Ls=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;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),(r=this.store)==null||r.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 r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of r)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.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 Ps=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let n=o.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}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 o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(o){r(o)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}};var gv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),hv=new Set(["step_start","execution_start"]),xv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),yv=new Set(["step_complete","agent_turn_complete"]),bv=new Set(["flow_complete","agent_complete"]),_h=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),qh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),to=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,la=(e,t)=>{let r=e[t];return qh(r)?r:void 0};function dp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Yi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function vv(e,t){return typeof t.type=="string"?t.type:e}function Cv(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 wv(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 Uh(e){var o,n,a,s,i;let t=la(e,"result"),r=[la(e,"tokens"),la(e,"totalTokens"),t?la(t,"tokens"):void 0,la(e,"usage"),t?la(t,"usage"):void 0];for(let c of r){if(!c)continue;let l=(n=(o=to(c.output))!=null?o:to(c.outputTokens))!=null?n:to(c.completionTokens);if(l!==void 0)return l}return(i=(a=to(e.outputTokens))!=null?a:to(e.completionTokens))!=null?i:t?(s=to(t.outputTokens))!=null?s:to(t.completionTokens):void 0}function Sv(e){var r,o,n,a,s;let t=la(e,"result");return(s=(n=(o=(r=to(e.executionTime))!=null?r:to(e.executionTimeMs))!=null?o:to(e.execution_time))!=null?n:to(e.duration))!=null?s:t?(a=to(t.executionTime))!=null?a:to(t.executionTimeMs):void 0}function Av(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Rs=class{constructor(t=Av){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 r=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:Yi(this.metric.outputTokens,r)}}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,r){var a;if(!qh(r)){_h.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=vv(t,r),n=this.now();if(gv.has(o)){this.startRun(n);return}if(hv.has(o)){this.run||this.startRun(n);return}if(xv.has(o)){if(!wv(o,r))return;let s=Cv(r);if(!s)return;this.run||this.startRun(n);let i=this.run;(a=i.firstDeltaAt)!=null||(i.firstDeltaAt=n),i.visibleCharCount+=s.length;let c=i.exactOutputTokens+dp(i.visibleCharCount),l=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Yi(c,l),outputTokens:c,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(yv.has(o)){if(!this.run)return;let s=this.run,i=Uh(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,l=s.exactOutputTokens+dp(s.visibleCharCount),p=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:Yi(l,p),outputTokens:l,durationMs:p,source:c?"usage":"estimate"};return}if(bv.has(o)){if(!this.run)return;let s=this.run,i=Uh(r),c=i!=null?i:s.exactOutputTokens+dp(s.visibleCharCount),l=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:Yi(c,p),outputTokens:c,durationMs:p,source:l},this.run=null;return}if(_h.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,r,o){let n=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(n!==void 0&&n>=250)return n;let a=Sv(r);return a!=null?a:o-t.startedAt}};function qa(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var Mv={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)"}},Tv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ev=["flowName","stepName","reasoningText","text","name","tool","toolName"],kv=100;function Lv(e,t){let r={...Mv,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return Tv}function Pv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Rv(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${o}:${n}.${a}`}function Iv(e,t){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let o of t){let n=o.split("."),a=r;for(let s of n)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function Hv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),r()})}function Wv(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 Bv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Dv(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 Fv(e,t,r){let o,n;try{n=JSON.parse(e.payload),o=JSON.stringify(n,null,2)}catch{n=e.payload,o=e.payload}let a=t.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&r){let i=a.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:n});if(i)return i}return s();function s(){let i=C("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]"),c=C("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,i.appendChild(c),i}}function cp(e,t,r,o,n,a,s,i){var u;let c=n.has(e.id),l=C("div","persona-border-b persona-border-persona-divider persona-text-xs");qa(l,(u=o.classNames)==null?void 0:u.eventRow);let p=s.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>f(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(f()),l;function f(){var O,Q;let m=C("div",""),x=C("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");x.setAttribute("data-event-id",e.id);let b=C("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),L=fe(c?"chevron-down":"chevron-right","14px","currentColor",2);L&&b.appendChild(L);let E=C("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(O=o.timestampFormat)!=null?O:"relative";E.textContent=A==="relative"?Pv(e.timestamp,r):Rv(e.timestamp);let T=null;o.showSequenceNumbers!==!1&&(T=C("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(t+1));let y=Lv(e.type,o.badgeColors),S=C("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");S.style.backgroundColor=y.bg,S.style.color=y.text,S.style.borderColor=y.text+"50",S.textContent=e.type;let v=(Q=o.descriptionFields)!=null?Q:Ev,M=Iv(e.payload,v),I=null;M&&(I=C("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),I.textContent=M);let H=C("div","persona-flex-1 persona-min-w-0"),R=C("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"),D=fe("clipboard","12px","currentColor",1.5);return D&&R.appendChild(D),R.addEventListener("click",async me=>{me.stopPropagation(),await Hv(Wv(e)),R.innerHTML="";let ce=fe("check","12px","currentColor",1.5);ce&&R.appendChild(ce),setTimeout(()=>{R.innerHTML="";let ee=fe("clipboard","12px","currentColor",1.5);ee&&R.appendChild(ee)},1500)}),x.appendChild(b),x.appendChild(E),T&&x.appendChild(T),x.appendChild(S),I&&x.appendChild(I),x.appendChild(H),x.appendChild(R),m.appendChild(x),c&&m.appendChild(Fv(e,s,i)),m}}function Vh(e){var x,b,L,E,A;let{buffer:t,getFullHistory:r,onClose:o,config:n,plugins:a=[],getThroughput:s}=e,i=(x=n==null?void 0:n.features)==null?void 0:x.scrollToBottom,c=(i==null?void 0:i.enabled)!==!1,l=(b=i==null?void 0:i.iconName)!=null?b:"arrow-down",p=(L=i==null?void 0:i.label)!=null?L:"",f=(A=(E=n==null?void 0:n.features)==null?void 0:E.eventStream)!=null?A:{},u=a.find(T=>T.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&n){let T=u.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(T)return{element:T,update:()=>{},destroy:()=>{}}}return m();function m(){let T=f.classNames,y=C("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");qa(y,T==null?void 0:T.panel);let S=[],v="",M="",I=null,H=[],R={},D=0,O=Wi(),Q=0,me=0,ce=!1,ee=null,Ce=!1,Ie=0,le=new Set,ve=new Map,ae="",se="",pe=null,ze,_e,K,J,Se,Y=null,ie=null,Re=null;function rt(){let W=C("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ne=C("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");qa(ne,T==null?void 0:T.headerBar);let Me=C("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Me.textContent="Events",ze=C("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"),ze.textContent="0",s){ie=C("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ie.style.cursor="help";let _t=C("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");_t.textContent="Throughput",Y=C("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",Re=C("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"),Re.style.display="none",Re.style.pointerEvents="none";let Ur=ie,Er=Re,kr=()=>{if(!Er.textContent)return;let Lr=Ur.getBoundingClientRect(),fo=W.getBoundingClientRect();Er.style.left=`${Lr.left-fo.left}px`,Er.style.top=`${Lr.bottom-fo.top+4}px`,Er.style.display="block"},Cr=()=>{Er.style.display="none"};ie.addEventListener("mouseenter",kr),ie.addEventListener("mouseleave",Cr),ie.appendChild(_t),ie.appendChild(Y)}let Mt=C("div","persona-flex-1");_e=C("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ye=C("option","");Ye.value="",Ye.textContent="All events",_e.appendChild(Ye),K=C("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),K.type="button",K.title="Copy All";let br=fe("clipboard-copy","12px","currentColor",1.5);br&&K.appendChild(br);let xt=C("span","persona-text-xs");xt.textContent="Copy All",K.appendChild(xt),ne.appendChild(Me),ne.appendChild(ze),ie&&ne.appendChild(ie),ne.appendChild(Mt),ne.appendChild(_e),ne.appendChild(K);let yt=C("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");qa(yt,T==null?void 0:T.searchBar);let It=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),vt=C("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");It&&vt.appendChild(It),J=C("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"),qa(J,T==null?void 0:T.searchInput),J.type="text",J.placeholder="Search event payloads...",Se=C("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"),Se.type="button",Se.style.display="none";let mr=fe("x","12px","currentColor",2);return mr&&Se.appendChild(mr),yt.appendChild(vt),yt.appendChild(J),yt.appendChild(Se),W.appendChild(ne),W.appendChild(yt),Re&&W.appendChild(Re),W}let bt,qt=a.find(W=>W.renderEventStreamToolbar);if(qt!=null&&qt.renderEventStreamToolbar&&n){let W=qt.renderEventStreamToolbar({config:n,defaultRenderer:()=>rt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ne=>{v=ne,Oe(),Yt()},onSearchChange:ne=>{M=ne,Oe(),Yt()}});bt=W!=null?W:rt()}else bt=rt();let Gt=C("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");Gt.style.display="none";function at(){if(!s||!Y||!ie)return;let W=s();Y.textContent=Bv(W);let ne=Dv(W);Re&&(Re.textContent=ne,ne||(Re.style.display="none")),ne?ie.setAttribute("aria-label",ne):ie.removeAttribute("aria-label")}let Ne=C("div","persona-flex-1 persona-min-h-0 persona-relative"),G=C("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let je=C("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");qa(je,T==null?void 0:T.scrollIndicator),je.style.display="none",je.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let $e=fe(l,"14px","currentColor",2);$e&&je.appendChild($e);let ye=C("span","");ye.textContent=p,je.appendChild(ye);let we=C("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");we.style.display="none",Ne.appendChild(G),Ne.appendChild(we),Ne.appendChild(je),y.setAttribute("tabindex","0"),y.appendChild(bt),y.appendChild(Gt),y.appendChild(Ne);function Qe(){let W=t.getAll(),ne={};for(let xt of W)ne[xt.type]=(ne[xt.type]||0)+1;let Me=Object.keys(ne).sort(),Mt=Me.length!==H.length||!Me.every((xt,yt)=>xt===H[yt]),Ye=!Mt&&Me.some(xt=>ne[xt]!==R[xt]),Vt=W.length!==Object.values(R).reduce((xt,yt)=>xt+yt,0);if(!Mt&&!Ye&&!Vt||(H=Me,R=ne,!_e))return;let br=_e.value;if(_e.options[0].textContent="All events",Mt){for(;_e.options.length>1;)_e.remove(1);for(let xt of Me){let yt=C("option","");yt.value=xt,yt.textContent=`${xt} (${ne[xt]||0})`,_e.appendChild(yt)}br&&Me.includes(br)?_e.value=br:br&&(_e.value="",v="")}else for(let xt=1;xt<_e.options.length;xt++){let yt=_e.options[xt];yt.textContent=`${yt.value} (${ne[yt.value]||0})`}}function Xe(){let W=t.getAll();if(v&&(W=W.filter(ne=>ne.type===v)),M){let ne=M.toLowerCase();W=W.filter(Me=>Me.type.toLowerCase().includes(ne)||Me.payload.toLowerCase().includes(ne))}return W}function Ae(){return v!==""||M!==""}function Oe(){D=0,Q=0,O.resume(),je.style.display="none"}function fr(W){le.has(W)?le.delete(W):le.add(W),pe=W;let ne=G.scrollTop,Me=O.isFollowing();Ce=!0,O.pause(),Yt(),G.scrollTop=ne,Me&&O.resume(),Ce=!1}function Dt(){return ra(G,50)}function Yt(){me=Date.now(),ce=!1,at(),Qe();let W=t.getEvictedCount();W>0?(Gt.textContent=`${W.toLocaleString()} older events truncated`,Gt.style.display=""):Gt.style.display="none",S=Xe();let ne=S.length,Me=t.getSize()>0;ze&&(ze.textContent=String(t.getSize())),ne===0&&Me&&Ae()?(we.textContent=M?`No events matching '${M}'`:"No events matching filter",we.style.display="",G.style.display="none"):(we.style.display="none",G.style.display=""),K&&(K.title=Ae()?`Copy Filtered (${ne})`:"Copy All"),c&&!O.isFollowing()&&ne>D&&(Q+=ne-D,ye.textContent=p?`${p}${Q>0?` (${Q})`:""}`:"",je.style.display=""),D=ne;let Mt=t.getAll(),Ye=Mt.length>0?Mt[0].timestamp:0,Vt=new Set(S.map(yt=>yt.id));for(let yt of le)Vt.has(yt)||le.delete(yt);let br=v!==ae||M!==se,xt=ve.size===0&&S.length>0;if(br||xt||S.length===0){G.innerHTML="",ve.clear();let yt=document.createDocumentFragment();for(let It=0;It<S.length;It++){let vt=cp(S[It],It,Ye,f,le,fr,a,n);ve.set(S[It].id,vt),yt.appendChild(vt)}G.appendChild(yt),ae=v,se=M,pe=null}else{if(pe!==null){let It=ve.get(pe);if(It&&It.parentNode===G){let vt=S.findIndex(mr=>mr.id===pe);if(vt>=0){let mr=cp(S[vt],vt,Ye,f,le,fr,a,n);G.insertBefore(mr,It),It.remove(),ve.set(pe,mr)}}pe=null}let yt=new Set(S.map(It=>It.id));for(let[It,vt]of ve)yt.has(It)||(vt.remove(),ve.delete(It));for(let It=0;It<S.length;It++){let vt=S[It];if(!ve.has(vt.id)){let mr=cp(vt,It,Ye,f,le,fr,a,n);ve.set(vt.id,mr),G.appendChild(mr)}}}O.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Uo(){if(Date.now()-me>=kv){ee!==null&&(cancelAnimationFrame(ee),ee=null),Yt();return}ce||(ce=!0,ee=requestAnimationFrame(()=>{ee=null,Yt()}))}let F=(W,ne)=>{if(!K)return;K.innerHTML="";let Me=fe(W,"12px","currentColor",1.5);Me&&K.appendChild(Me);let Mt=C("span","persona-text-xs");Mt.textContent="Copy All",K.appendChild(Mt),setTimeout(()=>{K.innerHTML="";let Ye=fe("clipboard-copy","12px","currentColor",1.5);Ye&&K.appendChild(Ye);let Vt=C("span","persona-text-xs");Vt.textContent="Copy All",K.appendChild(Vt),K.disabled=!1},ne)},j=async()=>{if(K){K.disabled=!0;try{let W;Ae()?W=S:r?(W=await r(),W.length===0&&(W=t.getAll())):W=t.getAll();let ne=W.map(Me=>{try{return JSON.parse(Me.payload)}catch{return Me.payload}});await navigator.clipboard.writeText(JSON.stringify(ne,null,2)),F("check",1500)}catch{F("x",1500)}}},de=()=>{_e&&(v=_e.value,Oe(),Yt())},He=()=>{!J||!Se||(Se.style.display=J.value?"":"none",I&&clearTimeout(I),I=setTimeout(()=>{M=J.value,Oe(),Yt()},150))},Ue=()=>{!J||!Se||(J.value="",M="",Se.style.display="none",I&&clearTimeout(I),Oe(),Yt())},We=()=>{if(Ce)return;let W=G.scrollTop,{action:ne,nextLastScrollTop:Me}=Bi({following:O.isFollowing(),currentScrollTop:W,lastScrollTop:Ie,nearBottom:Dt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ie=Me,ne==="resume"?(O.resume(),Q=0,je.style.display="none"):ne==="pause"&&(O.pause(),c&&(ye.textContent=p,je.style.display=""))},Ee=W=>{let ne=Di({following:O.isFollowing(),deltaY:W.deltaY,nearBottom:Dt(),resumeWhenNearBottom:!0});ne==="pause"?(O.pause(),c&&(ye.textContent=p,je.style.display="")):ne==="resume"&&(O.resume(),Q=0,je.style.display="none")},st=()=>{c&&(G.scrollTop=G.scrollHeight,O.resume(),Q=0,je.style.display="none")},Pt=W=>{let ne=W.target;if(!ne||ne.closest("button"))return;let Me=ne.closest("[data-event-id]");if(!Me)return;let Mt=Me.getAttribute("data-event-id");Mt&&fr(Mt)},gt=W=>{if((W.metaKey||W.ctrlKey)&&W.key==="f"){W.preventDefault(),J==null||J.focus(),J==null||J.select();return}W.key==="Escape"&&(J&&document.activeElement===J?(Ue(),J.blur(),y.focus()):o&&o())};K&&K.addEventListener("click",j),_e&&_e.addEventListener("change",de),J&&J.addEventListener("input",He),Se&&Se.addEventListener("click",Ue),G.addEventListener("scroll",We),G.addEventListener("wheel",Ee,{passive:!0}),G.addEventListener("click",Pt),je.addEventListener("click",st),y.addEventListener("keydown",gt);function Rt(){I&&clearTimeout(I),ee!==null&&(cancelAnimationFrame(ee),ee=null),ce=!1,ve.clear(),K&&K.removeEventListener("click",j),_e&&_e.removeEventListener("change",de),J&&J.removeEventListener("input",He),Se&&Se.removeEventListener("click",Ue),G.removeEventListener("scroll",We),G.removeEventListener("wheel",Ee),G.removeEventListener("click",Pt),je.removeEventListener("click",st),y.removeEventListener("keydown",gt)}return{element:y,update:Uo,destroy:Rt}}}function zh(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",n=e.status==="streaming"?"streaming":"complete",s=(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 ${r} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.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=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(u);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,f.appendChild(m)}else f.textContent=s;if(l.append(p,f),i.append(c,l),n==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${r}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",o),i.append(u)}return i}var $h=(e,t)=>{var o,n,a;let r=(a=(n=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(r){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",c=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=r({artifact:{artifactId:i,title:s,artifactType:l,status:c},config:t.config,defaultRenderer:()=>zh(e,t)});if(p)return p}return zh(e,t)};var pp=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}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(([r,o])=>{this.register(r,o)})}},on=new pp;on.register("PersonaArtifactCard",$h);function Nv(e){var n;let t=C("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=C("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let o=C("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((n=e.props)!=null?n:{},null,2),t.appendChild(r),t.appendChild(o),t}function jh(e,t){var _e,K,J,Se;let r=(K=(_e=e.features)==null?void 0:_e.artifacts)==null?void 0:K.layout,n=((J=r==null?void 0:r.toolbarPreset)!=null?J:"default")==="document",a=(Se=r==null?void 0:r.panePadding)==null?void 0:Se.trim(),s=e.markdown?Kn(e.markdown):null,i=Ta(e.sanitize),c=Y=>{let ie=s?s(Y):No(Y);return i?i(ie):ie},l=typeof document!="undefined"?C("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"),f.classList.remove("persona-artifact-drawer-open"),D==null||D.hide()};l&&l.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let f=C("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");f.setAttribute("data-persona-theme-zone","artifact-pane"),n&&f.classList.add("persona-artifact-pane-document");let u=C("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");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&u.classList.add("persona-artifact-toolbar-document");let m=C("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=C("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let b="rendered",L=C("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=n?ur({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):ur({icon:"eye",label:"Rendered view"}),A=n?ur({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):ur({icon:"code-2",label:"Source"}),T=C("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),y=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,S=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,v=r==null?void 0:r.documentToolbarCopyMenuItems,M=!!(S&&v&&v.length>0),I=null,H,R=null,D=null;if(n&&(y||S)&&!M){if(H=y?ks({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):ur({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),S){let Y=fe("chevron-down",14,"currentColor",2);Y&&H.appendChild(Y)}}else n&&M?(I=C("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),H=y?ks({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):ur({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=ur({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"}}),I.append(H,R)):n?H=ur({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):H=ur({icon:"copy",label:"Copy"});let O=n?ur({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):ur({icon:"refresh-cw",label:"Refresh"}),Q=n?ur({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):ur({icon:"x",label:"Close"}),me=()=>{var bt,qt,Gt;let Y=(bt=ve.find(at=>at.id===ae))!=null?bt:ve[ve.length-1],ie=(qt=Y==null?void 0:Y.id)!=null?qt:null,Re=(Y==null?void 0:Y.artifactType)==="markdown"&&(Gt=Y.markdown)!=null?Gt:"",rt=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:Re,jsonPayload:rt,id:ie}},ce=async()=>{var bt;let{markdown:Y,jsonPayload:ie}=me(),Re=(bt=ve.find(qt=>qt.id===ae))!=null?bt:ve[ve.length-1],rt=(Re==null?void 0:Re.artifactType)==="markdown"?Y:Re?ie:"";try{await navigator.clipboard.writeText(rt)}catch{}};if(H.addEventListener("click",async()=>{let Y=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(Y&&M){let{markdown:ie,jsonPayload:Re,id:rt}=me();try{await Y({actionId:"primary",artifactId:rt,markdown:ie,jsonPayload:Re})}catch{}return}await ce()}),R&&(v!=null&&v.length)){let Y=()=>{var Re;return(Re=f.closest("[data-persona-root]"))!=null?Re:document.body},ie=()=>{D=In({items:v.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:rt,jsonPayload:bt,id:qt}=me(),Gt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{Gt?await Gt({actionId:Re,artifactId:qt,markdown:rt,jsonPayload:bt}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(rt):Re==="json"||Re==="source"?await navigator.clipboard.writeText(bt):await navigator.clipboard.writeText(rt||bt)}catch{}},anchor:I!=null?I:R,position:"bottom-right",portal:Y()})};f.isConnected?ie():requestAnimationFrame(ie),R.addEventListener("click",Re=>{Re.stopPropagation(),D==null||D.toggle()})}O.addEventListener("click",async()=>{var Y;try{await((Y=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:Y.call(r))}catch{}pe()}),Q.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let ee=()=>{n&&(E.setAttribute("aria-pressed",b==="rendered"?"true":"false"),A.setAttribute("aria-pressed",b==="source"?"true":"false"))};E.addEventListener("click",()=>{b="rendered",ee(),pe()}),A.addEventListener("click",()=>{b="source",ee(),pe()});let Ce=C("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");n?(u.replaceChildren(),L.append(E,A),I?T.append(I,O,Q):T.append(H,O,Q),u.append(L,Ce,T),ee()):(u.appendChild(m),u.appendChild(x)),a&&(u.style.paddingLeft=a,u.style.paddingRight=a);let Ie=C("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),le=C("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(Ie.style.paddingLeft=a,Ie.style.paddingRight=a,le.style.padding=a),f.appendChild(u),f.appendChild(Ie),f.appendChild(le);let ve=[],ae=null,se=!1,pe=()=>{var rt,bt,qt,Gt;let Y=n&&ve.length<=1;Ie.classList.toggle("persona-hidden",Y),Ie.replaceChildren();for(let at of ve){let Ne=C("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");Ne.type="button",Ne.textContent=at.title||at.id.slice(0,8),at.id===ae&&Ne.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ne.addEventListener("click",()=>t.onSelect(at.id)),Ie.appendChild(Ne)}le.replaceChildren();let ie=ae&&ve.find(at=>at.id===ae)||ve[ve.length-1];if(!ie)return;if(n){let at=ie.artifactType==="markdown"?"MD":(rt=ie.component)!=null?rt:"Component",G=(ie.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ce.textContent=`${G} \xB7 ${at}`}else m.textContent="Artifacts";if(ie.artifactType==="markdown"){if(n&&b==="source"){let Ne=C("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ne.textContent=(bt=ie.markdown)!=null?bt:"",le.appendChild(Ne);return}let at=C("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");at.innerHTML=c((qt=ie.markdown)!=null?qt:""),le.appendChild(at);return}let Re=ie.component?on.get(ie.component):void 0;if(Re){let Ne={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let G=Re((Gt=ie.props)!=null?Gt:{},Ne);if(G){le.appendChild(G);return}}catch{}}le.appendChild(Nv(ie))},ze=()=>{var ie;let Y=ve.length>0;if(f.classList.toggle("persona-hidden",!Y),l){let Re=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,bt=((ie=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?ie:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&bt&&se?(l.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:l,update(Y){var ie,Re,rt;ve=Y.artifacts,ae=(rt=(Re=Y.selectedId)!=null?Re:(ie=Y.artifacts[Y.artifacts.length-1])==null?void 0:ie.id)!=null?rt:null,ve.length>0&&(se=!0),pe(),ze()},setMobileOpen(Y){se=Y,!Y&&l?(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):ze()}}}function uo(e){var t,r;return((r=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:r.enabled)===!0}function Gh(e,t){var a,s,i,c;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"),!uo(t))return;let r=(s=(a=t.features)==null?void 0:a.artifacts)==null?void 0:s.layout,o=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),n=(c=r==null?void 0:r.paneBorderLeft)==null?void 0:c.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}function Ov(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 Zi(e,t){var c,l,p,f,u,m,x,b,L,E;if(!uo(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"),Ov(e),Gh(e,t);return}let r=(l=(c=t.features)==null?void 0:c.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(f=r==null?void 0:r.paneWidth)!=null?f:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(u=r==null?void 0:r.paneMaxWidth)!=null?u:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=r==null?void 0:r.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let n=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();n?e.style.setProperty("--persona-artifact-pane-padding",n):e.style.removeProperty("--persona-artifact-pane-padding");let a=(b=r==null?void 0:r.documentToolbarIconColor)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(L=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:L.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Gh(e,t)}var Kh=["panel","seamless"];function el(e,t){var i,c,l,p,f,u;for(let m of Kh)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"),!uo(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(l=r==null?void 0:r.paneAppearance)!=null?l:"panel",n=Kh.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${n}`);let a=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(f=r==null?void 0:r.paneShadow)==null?void 0:f.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((u=r.unifiedSplitOuterRadius)==null?void 0:u.trim())||a;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Xh(e,t){var r,o,n;return!t||!uo(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function _v(e,t){if(!(e!=null&&e.trim()))return t;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):t}function Uv(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 qv(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function Vv(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function Jh(e,t){var s;let o=(s=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",n=/^([\d.]+)px$/i.exec(o);if(n)return Number(n[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function Qh(e,t,r,o,n,a){let s=_v(n,200),i=Vv(t,r,o,200);i=Math.max(s,i);let c=Uv(a);return c!==null&&(i=Math.min(i,c)),qv(e,s,i)}var Yh={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"}},up=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var x,b,L;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(b=Yh[s])!=null?b:Yh.init;a.classList.add("persona-form-card","persona-space-y-4");let c=C("div","persona-space-y-1"),l=C("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,c.appendChild(l),i.description){let E=C("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,c.appendChild(E)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var v,M;let A=C("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${E.name}`;let T=C("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=E.label,A.appendChild(T);let y=(v=E.type)!=null?v:"text",S;y==="textarea"?(S=document.createElement("textarea"),S.rows=3):(S=document.createElement("input"),S.type=y),S.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",S.id=`${t.id}-${s}-${E.name}`,S.name=E.name,S.placeholder=(M=E.placeholder)!=null?M:"",E.required&&(S.required=!0),A.appendChild(S),p.appendChild(A)});let f=C("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=C("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=C("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=(L=i.submitLabel)!=null?L:"Submit",f.appendChild(u),f.appendChild(m),p.appendChild(f),a.replaceChildren(c,p),p.addEventListener("submit",async E=>{var S,v;E.preventDefault();let A=(S=r.formEndpoint)!=null?S:"/form",T=new FormData(p),y={};T.forEach((M,I)=>{y[I]=M}),y.type=s,m.disabled=!0,u.textContent="Submitting\u2026";try{let M=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let I=await M.json();u.textContent=(v=I.message)!=null?v:"Thanks! We'll be in touch soon.",I.success&&I.nextPrompt&&await o.sendMessage(String(I.nextPrompt))}catch(M){u.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var fp=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var o;let r=this.plugins.get(t);r&&((o=r.onUnregister)==null||o.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var o,n;return((o=r.priority)!=null?o:0)-((n=t.priority)!=null?n:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let o=new Set(t.map(a=>a.id));return[...r.filter(a=>!o.has(a.id)),...t].sort((a,s)=>{var i,c;return((i=s.priority)!=null?i:0)-((c=a.priority)!=null?c:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Is=new fp;var Zh=()=>{let e=new Map,t=(n,a)=>(e.has(n)||e.set(n,new Set),e.get(n).add(a),()=>r(n,a)),r=(n,a)=>{var s;(s=e.get(n))==null||s.delete(a)};return{on:t,off:r,emit:(n,a)=>{var s;(s=e.get(n))==null||s.forEach(i=>{try{i(a)}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var zv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},$v=e=>{let t=e.trim(),r=t.indexOf("{");if(r===-1)return null;let o=0;for(let n=r;n<t.length;n+=1){let a=t[n];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(r,n+1)}return null},Hs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=zv(e),r=$v(t);if(!r)return null;let o=JSON.parse(r);if(!o||typeof o!="object"||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},mp=e=>typeof e=="string"?e:e==null?"":String(e),da={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:mp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=mp(r.element);if(o&&((n=t.document)!=null&&n.querySelector)){let a=t.document.querySelector(o);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:mp(r.text)}}},ex=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ws=e=>{let t=new Set(ex(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(ex(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.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=s?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),o();let c={action:i,message:a.message};e.emit("action:detected",c);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",c)},f=l(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var jv=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}},Gv=e=>e.map(t=>({...t,streaming:!1})),Kv=e=>e.map(t=>({...t,status:"complete"})),tl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?jv(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?Gv(r.messages):void 0,artifacts:r.artifacts?Kv(r.artifacts):void 0};o.setItem(e,JSON.stringify(n))}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",n)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Va=Aa(Qs(),1);function Xv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Jv(e,t){if(!Xv(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:t}}function rl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e;try{let n=(0,Va.parse)(r,Va.STR|Va.OBJ),a=Jv(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function tx(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ol(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=on.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:r,updateProps:i=>{n&&n(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function rx(){let e=rl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ox(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 nl(e){let t=ox(e);if(!t)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function al(e){let t=ox(e);if(!t)return null;try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let o=r;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Qv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function sl(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,ratingLabels:l=Qv}=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 f=null,u=document.createElement("div");u.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,m.appendChild(x);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=n,m.appendChild(b),u.appendChild(m);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-csat",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let v=1;v<=5;v++){let M=document.createElement("button");M.type="button",M.className="persona-feedback-rating-btn persona-feedback-star-btn",M.setAttribute("role","radio"),M.setAttribute("aria-checked","false"),M.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),M.title=l[v-1],M.dataset.rating=String(v),M.innerHTML=`
30
32
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
31
33
  <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>
32
34
  </svg>
33
- `,T.addEventListener("click",()=>{g=b,M.forEach((I,P)=>{let k=P<b;I.classList.toggle("selected",k),I.setAttribute("aria-checked",P===b-1?"true":"false")})}),M.push(T),R.appendChild(T)}c.appendChild(R);let A=null;if(p){let b=document.createElement("div");b.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),b.appendChild(A),c.appendChild(b)}let L=document.createElement("div");L.className="persona-feedback-actions";let y=document.createElement("button");y.type="button",y.className="persona-feedback-btn persona-feedback-btn-skip",y.textContent=i,y.addEventListener("click",()=>{r==null||r(),u.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=s,w.addEventListener("click",async()=>{if(g===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let b=(A==null?void 0:A.value.trim())||void 0;await t(g,b),u.remove()}catch(b){w.disabled=!1,w.textContent=s,console.error("[CSAT Feedback] Failed to submit:",b)}}),L.appendChild(y),L.appendChild(w),c.appendChild(L),u.appendChild(c),u}function nl(e){let{onSubmit:t,onDismiss:r,title:o="How likely are you to recommend us?",subtitle:n="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:u="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let c=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,x.appendChild(C);let R=document.createElement("p");R.className="persona-feedback-subtitle",R.textContent=n,x.appendChild(R),m.appendChild(x);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-nps",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let L=document.createElement("span");L.className="persona-feedback-label-low",L.textContent=d;let y=document.createElement("span");y.className="persona-feedback-label-high",y.textContent=u,A.appendChild(L),A.appendChild(y);let w=document.createElement("div");w.className="persona-feedback-numbers";let b=[];for(let N=0;N<=10;N++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${N} out of 10`),U.textContent=String(N),U.dataset.rating=String(N),N<=6?U.classList.add("persona-feedback-detractor"):N<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{c=N,b.forEach((Y,he)=>{Y.classList.toggle("selected",he===N),Y.setAttribute("aria-checked",he===N?"true":"false")})}),b.push(U),w.appendChild(U)}M.appendChild(A),M.appendChild(w),m.appendChild(M);let T=null;if(p){let N=document.createElement("div");N.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=a,T.rows=3,T.setAttribute("aria-label","Additional comments"),N.appendChild(T),m.appendChild(N)}let I=document.createElement("div");I.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",()=>{r==null||r(),g.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=s,k.addEventListener("click",async()=>{if(c===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let N=(T==null?void 0:T.value.trim())||void 0;await t(c,N),g.remove()}catch(N){k.disabled=!1,k.textContent=s,console.error("[NPS Feedback] Failed to submit:",N)}}),I.appendChild(P),I.appendChild(k),m.appendChild(I),g.appendChild(m),g}var Oa="persona-chat-history",Pv=30*1e3,Rv={"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 Iv(e){var o,n,a;if(!e)return[];let t=[],r=Array.from((o=e.items)!=null?o:[]);for(let s of r){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let p=(n=Rv[i.type])!=null?n:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${p}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let s of Array.from((a=e.files)!=null?a:[]))s.type.startsWith("image/")&&t.push(s);return t}function al(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 Wv(e){var t,r,o,n,a,s,i,p,d;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:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(n=(o=e.persist)==null?void 0:o.openState)!=null?n:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(p=(i=e.persist)==null?void 0:i.focusInput)!=null?p:!0},clearOnChatClear:(d=e.clearOnChatClear)!=null?d:!0}:null}function Hv(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var uc=e=>!e||typeof e!="object"?{}:{...e},Gh=e=>e.map(t=>({...t,streaming:!1})),Kh=(e,t,r)=>{let o=e!=null&&e.markdown?$n(e.markdown):null,n=va(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&n&&(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."),a=>{var u,g,c;let s=(u=a.text)!=null?u:"",i=(g=a.message.rawContent)!=null?g:null;if(t){let m=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});m!==null&&(s=m.text,m.persist||(a.message.__skipPersist=!0),m.resubmit&&!a.streaming&&r&&r())}let p=zn()!==null,d;if(e!=null&&e.postprocessMessage){let m=e.postprocessMessage({...a,text:s,raw:(c=i!=null?i:a.text)!=null?c:""});d=n?n(m):m}else if(o){let m=o(s);d=n&&p?n(m):m}else d=Ho(s);return d}};function Xh(e){var i,p,d,u;let t=S("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 r=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(p=e==null?void 0:e.iconSize)!=null?p:"48px",n=(d=e==null?void 0:e.iconColor)!=null?d:"rgba(59, 130, 246, 0.6)",a=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,s=be(r,o,n,a);if(s&&t.appendChild(s),e!=null&&e.label){let g=S("span","persona-drop-overlay-label");g.textContent=e.label,t.appendChild(g)}return t}var sl=(e,t,r)=>{var ru,ou,nu,au,su,iu,lu,du,pu,cu,uu,fu,mu,gu,hu,xu,yu,bu,vu,Cu,wu,Su,Au,Mu,Tu,Eu,ku,Lu,Pu,Ru,Iu,Wu,Hu,Bu,Du,Fu,Nu,Ou,_u,Uu,qu,Vu,zu,$u,ju,Gu,Ku,Xu,Ju,Qu;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 o=Mi(t),n=Es.getForInstance(o.plugins);o.components&&tn.registerAll(o.components);let a=qh(),i=o.persistState===!1?null:(ru=o.storageAdapter)!=null?ru:Yi(),p={},d=null,u=!1,g=l=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(l);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:v}=f;return v&&(u=!0),h}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l.then(f=>{let h=f!=null?f:{messages:[],metadata:{}};return g(h)});else{let f=l!=null?l:{messages:[],metadata:{}},h=g(f);h.metadata&&(p=uc(h.metadata)),(ou=h.messages)!=null&&ou.length&&(o={...o,initialMessages:h.messages}),(nu=h.artifacts)!=null&&nu.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(au=h.selectedArtifactId)!=null?au:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=g({messages:[],metadata:{}});(su=l.messages)!=null&&su.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let c=()=>p,m=l=>{var h;p=(h=l({...p}))!=null?h:{},cn()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ks],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[na.message,na.messageAndClick],R=Ls({parsers:x,handlers:C,getSessionMetadata:c,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null});R.syncFromMetadata();let M=(lu=(iu=o.launcher)==null?void 0:iu.enabled)!=null?lu:!0,A=(pu=(du=o.launcher)==null?void 0:du.autoExpand)!=null?pu:!1,L=(cu=o.autoFocusInput)!=null?cu:!1,y=A,w=M,b=(fu=(uu=o.layout)==null?void 0:uu.header)==null?void 0:fu.layout,T=!1,I=()=>En(o),P=()=>M||I(),k=I()?!1:M?A:!0,N=!1,U=null,Y=()=>{N=!0,U&&clearTimeout(U),U=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},he=Kh(o,R,Y),$e=(gu=(mu=o.features)==null?void 0:mu.showReasoning)!=null?gu:!0,Me=(xu=(hu=o.features)==null?void 0:hu.showToolCalls)!=null?xu:!0,Ie=(bu=(yu=o.features)==null?void 0:yu.showEventStreamToggle)!=null?bu:!1,qe=(Cu=(vu=o.features)==null?void 0:vu.scrollToBottom)!=null?Cu:{},Ee=(Su=(wu=o.features)==null?void 0:wu.scrollBehavior)!=null?Su:{},ae=`${(Mu=typeof o.persistState=="object"?(Au=o.persistState)==null?void 0:Au.keyPrefix:void 0)!=null?Mu:"persona-"}event-stream`,Q=Ie?new Ms(ae):null,pe=(ku=(Eu=(Tu=o.features)==null?void 0:Tu.eventStream)==null?void 0:Eu.maxEvents)!=null?ku:2e3,ye=Ie?new As(pe,Q):null,ne=Ie?new Ts:null,K=null,oe=!1,Ge=null,Z=0;Q==null||Q.open().then(()=>ye==null?void 0:ye.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let se={onCopy:l=>{var f,h;a.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(v=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",v)}),(h=(f=o.messageActions)==null?void 0:f.onCopy)==null||h.call(f,l)},onFeedback:l=>{var f,h;a.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(v=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",v)}),(h=(f=o.messageActions)==null?void 0:f.onFeedback)==null||h.call(f,l)}},We=(Lu=o.statusIndicator)!=null?Lu:{},Ct=l=>{var f,h,v,W;return l==="idle"?(f=We.idleText)!=null?f:wr.idle:l==="connecting"?(h=We.connectingText)!=null?h:wr.connecting:l==="connected"?(v=We.connectedText)!=null?v:wr.connected:l==="error"?(W=We.errorText)!=null?W:wr.error:wr[l]};function Lt(l,f,h,v){if(v==="idle"&&h.idleLink){l.textContent="";let W=document.createElement("a");W.href=h.idleLink,W.target="_blank",W.rel="noopener noreferrer",W.textContent=f,W.style.color="inherit",W.style.textDecoration="none",l.appendChild(W)}else l.textContent=f}let mt=yh({config:o,showClose:P()}),{wrapper:Oe,panel:fe,pillRoot:Ye}=mt.shell,X=mt.panelElements,{container:ie,body:ve,messagesWrapper:Ve,suggestions:Pt,textarea:we,sendButton:ce,sendButtonWrapper:xr,composerForm:Rt,statusText:ar,introTitle:Co,introSubtitle:yr,closeButton:ze,iconHolder:H,headerTitle:de,headerSubtitle:Te,header:Se,footer:Le,actionsRow:Ze,leftActions:Ke,rightActions:dt}=X,It=X.setSendButtonMode,z=X.micButton,ot=X.micButtonWrapper,j=X.attachmentButton,le=X.attachmentButtonWrapper,Ae=X.attachmentInput,xt=X.attachmentPreviewsContainer;ie.classList.add("persona-relative"),ve.classList.add("persona-relative");let Zt=12,er=()=>{var l;return(l=qe.label)!=null?l:""},fr=()=>{var l;return(l=qe.iconName)!=null?l:"arrow-down"},Ht=()=>qe.enabled!==!1,et=()=>{var l;return(l=Ee.mode)!=null?l:"follow"},Wt=()=>{var l;return(l=Ee.anchorTopOffset)!=null?l:16},st=S("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");st.type="button",st.style.display="none",st.setAttribute("data-persona-scroll-to-bottom","true");let Gt=S("span","persona-flex persona-items-center"),to=S("span",""),Ar=S("span","");Ar.setAttribute("data-persona-scroll-to-bottom-count",""),Ar.style.display="none",st.append(Gt,to,Ar),ie.appendChild(st);let tr=S("div","persona-stream-anchor-spacer");tr.setAttribute("aria-hidden","true"),tr.setAttribute("data-persona-anchor-spacer",""),tr.style.flexShrink="0",tr.style.pointerEvents="none",tr.style.height="0px",ve.appendChild(tr);let Wr=()=>{let f=Le.style.display==="none"?0:Le.offsetHeight;st.style.bottom=`${f+Zt}px`};Wr();let wo=()=>{let l=!!er();st.setAttribute("aria-label",er()||"Jump to latest"),st.title=er(),st.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Gt.innerHTML="";let f=be(fr(),"14px","currentColor",2);f?(Gt.appendChild(f),Gt.style.display=""):Gt.style.display="none",to.textContent=er(),to.style.display=l?"":"none"};wo();let yt=null,Or=null,So=n.find(l=>l.renderHeader);if(So!=null&&So.renderHeader){let l=So.renderHeader({config:o,defaultRenderer:()=>{let f=en({config:o,showClose:P()});return ta(ie,f,o),f.header},onClose:()=>Ut(!1,"user")});if(l){let f=ie.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),Se=l,mt.header.element=l)}}let Fo=()=>{var f,h,v,W;if(!ye)return;if(oe=!0,!K&&ye&&(K=Ih({buffer:ye,getFullHistory:()=>ye.getAllFromStore(),onClose:()=>uo(),config:o,plugins:n,getThroughput:()=>{var D;return(D=ne==null?void 0:ne.getMetric())!=null?D:{status:"idle"}}})),K&&(ve.style.display="none",(f=Le.parentNode)==null||f.insertBefore(K.element,Le),K.update()),gt){gt.style.boxShadow=`inset 0 0 0 1.5px ${Ir.actionIconColor}`;let D=(W=(v=(h=o.features)==null?void 0:h.eventStream)==null?void 0:v.classNames)==null?void 0:W.toggleButtonActive;D&&D.split(/\s+/).forEach($=>$&&gt.classList.add($))}let l=()=>{if(!oe)return;let D=Date.now();D-Z>=200&&(K==null||K.update(),Z=D),Ge=requestAnimationFrame(l)};Z=0,Ge=requestAnimationFrame(l),Je(),a.emit("eventStream:opened",{timestamp:Date.now()})},uo=()=>{var l,f,h;if(oe){if(oe=!1,K&&K.element.remove(),ve.style.display="",gt){gt.style.boxShadow="";let v=(h=(f=(l=o.features)==null?void 0:l.eventStream)==null?void 0:f.classNames)==null?void 0:h.toggleButtonActive;v&&v.split(/\s+/).forEach(W=>W&&gt.classList.remove(W))}Ge!==null&&(cancelAnimationFrame(Ge),Ge=null),Je(),a.emit("eventStream:closed",{timestamp:Date.now()})}},gt=null;if(Ie){let l=(Ru=(Pu=o.features)==null?void 0:Pu.eventStream)==null?void 0:Ru.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");gt=S("button",f),gt.style.width="28px",gt.style.height="28px",gt.style.color=Ir.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let h=be("activity","18px","currentColor",1.5);h&&gt.appendChild(h);let v=X.clearChatButtonWrapper,W=X.closeButtonWrapper,D=v||W;D&&D.parentNode===Se?Se.insertBefore(gt,D):Se.appendChild(gt),gt.addEventListener("click",()=>{oe?uo():Fo()})}let Ln=l=>{var W,D,$,O,F;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=(W=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?W:l.querySelector(".persona-attachment-previews");if(!h){h=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let te=l.querySelector("[data-persona-composer-form]");te!=null&&te.parentNode?te.parentNode.insertBefore(h,te):l.insertBefore(h,l.firstChild)}if(!((D=l.querySelector("[data-persona-composer-attachment-input]"))!=null?D:l.querySelector('input[type="file"]'))){let te=S("input");te.type="file",te.setAttribute("data-persona-composer-attachment-input",""),te.accept=(($=f.allowedTypes)!=null?$:Yo).join(","),te.multiple=((O=f.maxFiles)!=null?O:4)>1,te.style.display="none",te.setAttribute("aria-label",(F=f.buttonTooltipText)!=null?F:"Attach files"),l.appendChild(te)}},Ao=n.find(l=>l.renderComposer);if(Ao!=null&&Ao.renderComposer){let l=o.composer,f=Ao.renderComposer({config:o,defaultRenderer:()=>Wa({config:o}).footer,onSubmit:h=>{var $;if(!_||_.isStreaming())return;let v=h.trim(),W=($=yt==null?void 0:yt.hasAttachments())!=null?$:!1;if(!v&&!W)return;Wc();let D;W&&(D=[],D.push(...yt.getContentParts()),v&&D.push(ps(v))),_.sendMessage(v,{contentParts:D}),W&&yt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ae==null||Ae.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Iu=o.voiceRecognition)==null?void 0:Iu.enabled)===!0?()=>{Or==null||Or()}:void 0});f&&(mt.replaceComposer(f),Le=mt.composer.footer)}let Pn=l=>{let f=(...re)=>{for(let J of re){let xe=l.querySelector(J);if(xe)return xe}return null},h=l.querySelector("[data-persona-composer-form]"),v=l.querySelector("[data-persona-composer-input]"),W=l.querySelector("[data-persona-composer-submit]"),D=l.querySelector("[data-persona-composer-mic]"),$=l.querySelector("[data-persona-composer-status]");h&&(Rt=h),v&&(we=v),W&&(ce=W),D&&(z=D,ot=D.parentElement),$&&(ar=$);let O=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Pt=O);let F=f("[data-persona-composer-attachment-button]",".persona-attachment-button");F&&(j=F,le=F.parentElement),Ae=f("[data-persona-composer-attachment-input]",'input[type="file"]'),xt=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let te=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");te&&(Ze=te)};Ln(Le),Pn(Le);let Hr=(Fu=(Wu=o.layout)==null?void 0:Wu.contentMaxWidth)!=null?Fu:I()?(Du=(Bu=(Hu=o.launcher)==null?void 0:Hu.composerBar)==null?void 0:Bu.contentMaxWidth)!=null?Du:"720px":void 0;if(Hr&&(Ve.style.maxWidth=Hr,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%"),Hr&&Rt&&!I()&&(Rt.style.maxWidth=Hr,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),Hr&&Pt&&!I()&&(Pt.style.maxWidth=Hr,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Hr&&xt&&!I()&&(xt.style.maxWidth=Hr,xt.style.marginLeft="auto",xt.style.marginRight="auto"),(Nu=o.attachments)!=null&&Nu.enabled&&Ae&&xt){yt=Yn.fromConfig(o.attachments),yt.setPreviewsContainer(xt),Ae.addEventListener("change",h=>{let v=h.target;yt==null||yt.handleFileSelect(v.files),v.value=""});let l=o.attachments.dropOverlay,f=Xh(l);ie.appendChild(f)}(()=>{var v,W;let l=(W=(v=o.layout)==null?void 0:v.slots)!=null?W:{},f=D=>{switch(D){case"body-top":return ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ve;case"footer-top":return Pt;case"composer":return Rt;case"footer-bottom":return ar;default:return null}},h=(D,$)=>{var O;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")Se.insertBefore($,Se.firstChild);else if(D==="header-right")Se.appendChild($);else{let F=Se.querySelector(".persona-flex-col");F?(O=F.parentNode)==null||O.insertBefore($,F.nextSibling):Se.appendChild($)}break;case"body-top":{let F=ve.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith($):ve.insertBefore($,ve.firstChild);break}case"body-bottom":ve.appendChild($);break;case"footer-top":Pt.replaceWith($);break;case"footer-bottom":ar.replaceWith($);break;default:break}};for(let[D,$]of Object.entries(l))if($)try{let O=$({config:o,defaultContent:()=>f(D)});O&&h(D,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,O)}})();let rn=l=>{var $,O;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let v=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let W=v.getAttribute("data-message-id");if(!W)return;let D=h.getAttribute("data-bubble-type");if(D==="reasoning")Ba.has(W)?Ba.delete(W):Ba.add(W),wh(W,v);else if(D==="tool")Da.has(W)?Da.delete(W):Da.add(W),Sh(W,v,o);else if(D==="approval"){let F=o.approval!==!1?o.approval:void 0,te=(($=F==null?void 0:F.detailsDisplay)!=null?$:"collapsed")==="expanded",re=(O=Gi.get(W))!=null?O:te;Gi.set(W,!re),Eh(W,v,o)}Lo.delete(W)};Ve.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),rn(l))}),Ve.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),rn(l))}),Ve.addEventListener("copy",l=>{let{clipboardData:f}=l;if(!f)return;let h=Ve.getRootNode(),v=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let W=v.toString(),D=eh(W);!D||D===W||(f.setData("text/plain",D),l.preventDefault())});let No=new Map,on=null,nn="idle",Rn={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},In=(l,f)=>{let{icon:h,label:v}=Rn[f];l.setAttribute("aria-label",v),l.title=v,l.setAttribute("aria-pressed",f==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",f!=="idle"),l.classList.toggle("persona-message-action-loading",f==="loading");let W=be(h,14,"currentColor",2);W&&(l.innerHTML="",l.appendChild(W))},an=()=>{Ve.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{var D;let h=f.closest("[data-actions-for]"),v=(D=h==null?void 0:h.getAttribute("data-actions-for"))!=null?D:null;In(f,v&&v===on?nn:"idle")})};Ve.addEventListener("click",l=>{var $;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.closest("[data-actions-for]");if(!v)return;let W=v.getAttribute("data-actions-for");if(!W)return;let D=h.getAttribute("data-action");if(D==="copy"){let F=_.getMessages().find(te=>te.id===W);if(F&&se.onCopy){let te=F.content||"";navigator.clipboard.writeText(te).then(()=>{h.classList.add("persona-message-action-success");let re=be("check",14,"currentColor",2);re&&(h.innerHTML="",h.appendChild(re)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let J=be("copy",14,"currentColor",2);J&&(h.innerHTML="",h.appendChild(J))},2e3)}).catch(re=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",re)}),se.onCopy(F)}}else if(D==="read-aloud")_.toggleReadAloud(W);else if(D==="upvote"||D==="downvote"){let F=(($=No.get(W))!=null?$:null)===D,te=D==="upvote"?"thumbs-up":"thumbs-down";if(F){No.delete(W),h.classList.remove("persona-message-action-active");let re=be(te,14,"currentColor",2);re&&(h.innerHTML="",h.appendChild(re))}else{let re=D==="upvote"?"downvote":"upvote",J=v.querySelector(`[data-action="${re}"]`);if(J){J.classList.remove("persona-message-action-active");let _e=be(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);_e&&(J.innerHTML="",J.appendChild(_e))}No.set(W,D),h.classList.add("persona-message-action-active");let xe=be(te,14,"currentColor",2);xe&&(xe.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(xe)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ce=_.getMessages().find(rt=>rt.id===W);Ce&&se.onFeedback&&se.onFeedback({type:D,messageId:Ce.id,message:Ce})}}}),Ve.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.closest(".persona-approval-bubble");if(!v)return;let W=v.getAttribute("data-message-id");if(!W)return;let D=h.getAttribute("data-approval-action");if(!D)return;let $=D==="approve"?"approved":"denied",F=_.getMessages().find(re=>re.id===W);if(!(F!=null&&F.approval))return;let te=v.querySelector("[data-approval-buttons]");te&&te.querySelectorAll("button").forEach(J=>{J.disabled=!0,J.style.opacity="0.5",J.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?_.resolveWebMcpApproval(W,$):_.resolveApproval(F.approval,$)});let vt=null,_r=null,Ur={artifacts:[],selectedId:null},Mr=!1,St={current:null};Ve.addEventListener("click",l=>{var J,xe,De,Ce,rt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.getAttribute("data-download-artifact");if(!v||((De=(xe=(J=o.features)==null?void 0:J.artifacts)==null?void 0:xe.onArtifactAction)==null?void 0:De.call(xe,{type:"download",artifactId:v}))===!0)return;let D=_.getArtifactById(v),$=D==null?void 0:D.markdown,O=(D==null?void 0:D.title)||"artifact";if(!$){let _e=h.closest("[data-open-artifact]"),ct=_e==null?void 0:_e.closest("[data-message-id]"),nt=ct==null?void 0:ct.getAttribute("data-message-id");if(nt){let ke=_.getMessages().find(Ue=>Ue.id===nt);if(ke!=null&&ke.rawContent)try{let Ue=JSON.parse(ke.rawContent);$=(Ce=Ue==null?void 0:Ue.props)==null?void 0:Ce.markdown,O=((rt=Ue==null?void 0:Ue.props)==null?void 0:rt.title)||O}catch{}}}if(!$)return;let F=new Blob([$],{type:"text/markdown"}),te=URL.createObjectURL(F),re=document.createElement("a");re.href=te,re.download=`${O}.md`,re.click(),URL.revokeObjectURL(te)}),Ve.addEventListener("click",l=>{var D,$,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let v=h.getAttribute("data-open-artifact");!v||((O=($=(D=o.features)==null?void 0:D.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:O.call($,{type:"open",artifactId:v}))===!0||(l.preventDefault(),l.stopPropagation(),Mr=!1,_.selectArtifact(v),zr())}),Ve.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;f.hasAttribute("data-open-artifact")&&(l.preventDefault(),f.click())});let ro=X.composerOverlay,oo=(l,f,h)=>{var O,F,te,re;let v=f.trim();if(!v||!St.current)return;let W=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",D=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:W,answer:v,answers:h.structured,values:(F=h.values)!=null?F:h.source==="multi"?v.split(", "):[v],isFreeText:D,source:h.source},bubbles:!0,composed:!0})),vn(ro,W);let $=St.current.getMessages().find(J=>{var xe;return((xe=J.toolCall)==null?void 0:xe.id)===W});(te=$==null?void 0:$.agentMetadata)!=null&&te.awaitingLocalTool?St.current.resolveAskUserQuestion($,(re=h.structured)!=null?re:v):St.current.sendMessage(v)},qr=l=>{var W;let f=St.current;if(!f)return;let h=(W=l.getAttribute("data-tool-call-id"))!=null?W:"",v=f.getMessages().find(D=>{var $;return(($=D.toolCall)==null?void 0:$.id)===h});v&&f.persistAskUserQuestionProgress(v,{answers:Js(l,v),currentIndex:po(l)})},sn=l=>Object.entries(l).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Oo=l=>{var W,D,$;if(((D=(W=o.features)==null?void 0:W.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let f=po(l),h=Sa(l);if(f>=h-1)return;let v=($=St.current)==null?void 0:$.getMessages().find(O=>{var F;return((F=O.toolCall)==null?void 0:F.id)===l.getAttribute("data-tool-call-id")});v&&(Qs(l,v,o,f+1),qr(l))};ro.addEventListener("click",l=>{var D,$,O,F,te,re,J,xe,De,Ce,rt,_e,ct,nt;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;let W=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),W==="dismiss"){let Pe=(D=v.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),vn(ro,Pe);let ke=($=St.current)==null?void 0:$.getMessages().find(Ue=>{var je;return((je=Ue.toolCall)==null?void 0:je.id)===Pe});(O=ke==null?void 0:ke.agentMetadata)!=null&&O.awaitingLocalTool&&((F=St.current)==null||F.markAskUserQuestionResolved(ke),(te=St.current)==null||te.resolveAskUserQuestion(ke,"(dismissed)"));return}if(W==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let ke=v.getAttribute("data-multi-select")==="true",Ue=bn(v);if(Ue&&ke){let je=jn(v)[po(v)],ht=new Set(Array.isArray(je)?je:[]);ht.has(Pe)?ht.delete(Pe):ht.add(Pe),Cn(v,Array.from(ht)),qr(v);return}if(Ue){Cn(v,Pe),qr(v),Oo(v);return}if(ke){let je=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",je?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!je);let ht=v.querySelector('[data-ask-user-action="submit-multi"]');ht&&(ht.disabled=Pl(v).length===0);return}oo(v,Pe,{source:"pick",values:[Pe]});return}if(W==="submit-multi"){let Pe=Pl(v);if(Pe.length===0)return;oo(v,Pe.join(", "),{source:"multi",values:Pe});return}if(W==="open-free-text"){let Pe=v.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let ke=Pe.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus()}return}if(W==="focus-free-text"){let Pe=v.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(W==="submit-free-text"){let Pe=v.querySelector('[data-ask-free-text-input="true"]'),ke=(re=Pe==null?void 0:Pe.value)!=null?re:"";if(!ke.trim())return;if(bn(v)){Cn(v,ke.trim()),qr(v),Oo(v);return}oo(v,ke,{source:"free-text"});return}if(W==="next"||W==="back"){if(!St.current)return;let Pe=(J=v.getAttribute("data-tool-call-id"))!=null?J:"",ke=St.current.getMessages().find(He=>{var Re;return((Re=He.toolCall)==null?void 0:Re.id)===Pe});if(!ke)return;let Ue=v.querySelector('[data-ask-free-text-input="true"]'),je=(De=(xe=Ue==null?void 0:Ue.value)==null?void 0:xe.trim())!=null?De:"";if(je){let He=jn(v)[po(v)];(typeof He!="string"||He!==je)&&Cn(v,je)}let ht=W==="next"?1:-1,B=po(v)+ht;Qs(v,ke,o,B),qr(v);return}if(W==="submit-all"){if(!St.current)return;let Pe=(Ce=v.getAttribute("data-tool-call-id"))!=null?Ce:"",ke=St.current.getMessages().find(He=>{var Re;return((Re=He.toolCall)==null?void 0:Re.id)===Pe});if(!ke)return;let Ue=v.querySelector('[data-ask-free-text-input="true"]'),je=(_e=(rt=Ue==null?void 0:Ue.value)==null?void 0:rt.trim())!=null?_e:"";je&&Cn(v,je);let ht=Js(v,ke);St.current.persistAskUserQuestionProgress(ke,{answers:ht,currentIndex:po(v)});let B=sn(ht);oo(v,B||"(submitted)",{source:"submit-all",structured:ht});return}if(W==="skip"){if(!St.current)return;let Pe=(ct=v.getAttribute("data-tool-call-id"))!=null?ct:"",ke=St.current.getMessages().find(Re=>{var ue;return((ue=Re.toolCall)==null?void 0:ue.id)===Pe});if(!ke)return;let Ue=bn(v),je=po(v),ht=Sa(v),B=je>=ht-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),vn(ro,Pe),(nt=ke.agentMetadata)!=null&&nt.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(ke),St.current.resolveAskUserQuestion(ke,"(dismissed)"));return}Cn(v,"");let He=v.querySelector('[data-ask-free-text-input="true"]');if(He&&(He.value=""),B){let Re=Js(v,ke),ue=sn(Re);oo(v,ue||"(skipped)",{source:"submit-all",structured:Re});return}Qs(v,ke,o,je+1),qr(v);return}}),ro.addEventListener("keydown",l=>{var D;if(l.key!=="Enter")return;let h=l.target;if(!((D=h.matches)!=null&&D.call(h,'[data-ask-free-text-input="true"]')))return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;l.preventDefault();let W=h.value;if(W.trim()){if(bn(v)){Cn(v,W.trim()),qr(v),Oo(v);return}oo(v,W,{source:"free-text"})}});let ln=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let f=l.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let h=ro.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let v=Number(l.key),D=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];D&&(l.preventDefault(),D.click())};document.addEventListener("keydown",ln);let Vr=null,Bt=null,Tr=null,no=null,dn=()=>{};function _o(){no==null||no(),no=null}let pn=()=>{var $;if(!Vr||!Bt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=(($=e.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let v=Vr.firstElementChild;if(!v||v===Bt)return;let W=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${W}px`,Bt.style.zIndex="5";let D=v.offsetWidth-W/2;Bt.style.left=`${Math.max(0,D)}px`},Mo=()=>{},zr=()=>{var h,v,W,D,$;if(!vt||!co(o))return;Ji(e,o),Qi(e,o),Mo();let l=(D=(W=(v=(h=o.features)==null?void 0:h.artifacts)==null?void 0:v.layout)==null?void 0:W.narrowHostMaxWidth)!=null?D:520,f=fe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l),vt.update(Ur),Mr?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),($=vt.backdrop)==null||$.classList.add("persona-hidden")):Ur.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),dn()};if(co(o)){fe.style.position="relative";let l=S("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=S("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ie),vt=Bh(o,{onSelect:h=>{var v;return(v=St.current)==null?void 0:v.selectArtifact(h)},onDismiss:()=>{Mr=!0,zr()}}),vt.element.classList.add("persona-hidden"),Vr=f,f.appendChild(l),f.appendChild(vt.element),vt.backdrop&&fe.appendChild(vt.backdrop),fe.appendChild(f),dn=()=>{var v,W,D,$;if(!Vr||!vt)return;if(!(((D=(W=(v=o.features)==null?void 0:v.artifacts)==null?void 0:W.layout)==null?void 0:D.resizable)===!0)){Tr==null||Tr(),Tr=null,_o(),Bt&&(Bt.remove(),Bt=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Bt){let O=S("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let F=e.ownerDocument,te=($=F.defaultView)!=null?$:window,re=J=>{var ct,nt;if(!vt||J.button!==0||e.classList.contains("persona-artifact-narrow-host")||te.innerWidth<=640)return;J.preventDefault(),_o();let xe=J.clientX,De=vt.element.getBoundingClientRect().width,Ce=(nt=(ct=o.features)==null?void 0:ct.artifacts)==null?void 0:nt.layout,rt=Pe=>{let ke=Vr.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),je=Ue?0:Oh(Vr,te),ht=Ue?0:O.getBoundingClientRect().width||6,B=De-(Pe.clientX-xe),He=_h(B,ke,je,ht,Ce==null?void 0:Ce.resizableMinWidth,Ce==null?void 0:Ce.resizableMaxWidth);vt.element.style.width=`${He}px`,vt.element.style.maxWidth="none",pn()},_e=()=>{F.removeEventListener("pointermove",rt),F.removeEventListener("pointerup",_e),F.removeEventListener("pointercancel",_e),no=null;try{O.releasePointerCapture(J.pointerId)}catch{}};no=_e,F.addEventListener("pointermove",rt),F.addEventListener("pointerup",_e),F.addEventListener("pointercancel",_e);try{O.setPointerCapture(J.pointerId)}catch{}};O.addEventListener("pointerdown",re),Bt=O,Vr.insertBefore(O,vt.element),Tr=()=>{O.removeEventListener("pointerdown",re)}}if(Bt){let O=Ur.artifacts.length>0&&!Mr;Bt.classList.toggle("persona-hidden",!O),pn()}},Mo=()=>{var te,re,J,xe,De,Ce,rt,_e,ct,nt,Pe,ke,Ue,je;if(!M||!vt||((re=(te=o.launcher)==null?void 0:te.sidebarMode)!=null?re:!1)||nr(o)&&Zr(o).reveal==="emerge")return;let v=(J=e.ownerDocument.defaultView)!=null?J:window,W=(De=(xe=o.launcher)==null?void 0:xe.mobileFullscreen)!=null?De:!0,D=(rt=(Ce=o.launcher)==null?void 0:Ce.mobileBreakpoint)!=null?rt:640;if(W&&v.innerWidth<=D||!Nh(o,M))return;let $=(nt=(ct=(_e=o.launcher)==null?void 0:_e.width)!=null?ct:o.launcherWidth)!=null?nt:Yr,O=(je=(Ue=(ke=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:ke.layout)==null?void 0:Ue.expandedPanelWidth)!=null?je:"min(720px, calc(100vw - 24px))";Ur.artifacts.length>0&&!Mr?(fe.style.width=O,fe.style.maxWidth=O):(fe.style.width=$,fe.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(_r=new ResizeObserver(()=>{zr()}),_r.observe(fe))}else fe.appendChild(ie),I()&&Ye&&(X.peekBanner&&Ye.appendChild(X.peekBanner),Ye.appendChild(Le));e.appendChild(Oe),Ye&&e.appendChild(Ye);let ge=()=>{var He,Re,ue,Nt,Dt,zt,bt,qt,Xr,Qt,Xe,Et,or,lo,Jr,Fn,Nn,ha,xa,$t,On,gn,hn,Go,_n,ho,Qe,lr;if(I()){fe.style.width="100%",fe.style.maxWidth="100%";let _t=(Re=(He=o.launcher)==null?void 0:He.composerBar)!=null?Re:{},Ot=Oe.dataset.state==="expanded",ut=(ue=_t.expandedSize)!=null?ue:"anchored";if(!(Ot&&ut!=="fullscreen")){ie.style.background="",ie.style.border="",ie.style.borderRadius="",ie.style.overflow="",ie.style.boxShadow="";return}let wt=(Dt=(Nt=o.theme)==null?void 0:Nt.components)==null?void 0:Dt.panel,vr=Ra(o),Er=(Lr,Un)=>{var Ja;return Lr==null||Lr===""?Un:(Ja=La(vr,Lr))!=null?Ja:Lr},Wo="1px solid var(--persona-border)",ur="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",kr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ie.style.background="var(--persona-surface, #ffffff)",ie.style.border=Er(wt==null?void 0:wt.border,Wo),ie.style.borderRadius=Er(wt==null?void 0:wt.borderRadius,kr),ie.style.boxShadow=Er(wt==null?void 0:wt.shadow,ur),ie.style.overflow="hidden";return}let l=nr(o),f=(bt=(zt=o.launcher)==null?void 0:zt.sidebarMode)!=null?bt:!1,h=l||f||((Xr=(qt=o.launcher)==null?void 0:qt.fullHeight)!=null?Xr:!1),v=((Qt=o.launcher)==null?void 0:Qt.enabled)===!1,W=(Et=(Xe=o.theme)==null?void 0:Xe.components)==null?void 0:Et.panel,D=Ra(o),$=(_t,Ot)=>{var ut;return _t==null||_t===""?Ot:(ut=La(D,_t))!=null?ut:_t},O=(or=e.ownerDocument.defaultView)!=null?or:window,F=(Jr=(lo=o.launcher)==null?void 0:lo.mobileFullscreen)!=null?Jr:!0,te=(Nn=(Fn=o.launcher)==null?void 0:Fn.mobileBreakpoint)!=null?Nn:640,re=O.innerWidth<=te,J=F&&re&&M,xe=(xa=(ha=o.launcher)==null?void 0:ha.position)!=null?xa:"bottom-left",De=xe==="bottom-left"||xe==="top-left",Ce=(On=($t=o.launcher)==null?void 0:$t.zIndex)!=null?On:Sr,rt=f||J?"none":"1px solid var(--persona-border)",_e=J?"none":f?De?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!J&&(_e="none",rt="none");let ct=f||J?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",nt=$(W==null?void 0:W.border,rt),Pe=$(W==null?void 0:W.shadow,_e),ke=$(W==null?void 0:W.borderRadius,ct),Ue=ve.scrollTop;e.style.cssText="",Oe.style.cssText="",fe.style.cssText="",ie.style.cssText="",ve.style.cssText="",Le.style.cssText="";let je=()=>{var Ot;if(Ue<=0)return;((Ot=ve.ownerDocument.defaultView)!=null?Ot:window).requestAnimationFrame(()=>{if(ve.scrollTop===Ue)return;let ut=ve.scrollHeight-ve.clientHeight;ut<=0||(ve.scrollTop=Math.min(Ue,ut))})};if(J){Oe.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"),Oe.style.cssText=`
35
+ `,M.addEventListener("click",()=>{f=v,E.forEach((I,H)=>{let R=H<v;I.classList.toggle("selected",R),I.setAttribute("aria-checked",H===v-1?"true":"false")})}),E.push(M),L.appendChild(M)}u.appendChild(L);let A=null;if(c){let v=document.createElement("div");v.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),v.appendChild(A),u.appendChild(v)}let T=document.createElement("div");T.className="persona-feedback-actions";let y=document.createElement("button");y.type="button",y.className="persona-feedback-btn persona-feedback-btn-skip",y.textContent=i,y.addEventListener("click",()=>{r==null||r(),p.remove()});let S=document.createElement("button");return S.type="button",S.className="persona-feedback-btn persona-feedback-btn-submit",S.textContent=s,S.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}S.disabled=!0,S.textContent="Submitting...";try{let v=(A==null?void 0:A.value.trim())||void 0;await t(f,v),p.remove()}catch(v){S.disabled=!1,S.textContent=s,console.error("[CSAT Feedback] Failed to submit:",v)}}),T.appendChild(y),T.appendChild(S),u.appendChild(T),p.appendChild(u),p}function il(e){let{onSubmit:t,onDismiss:r,title:o="How likely are you to recommend us?",subtitle:n="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let u=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,x.appendChild(b);let L=document.createElement("p");L.className="persona-feedback-subtitle",L.textContent=n,x.appendChild(L),m.appendChild(x);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=l;let y=document.createElement("span");y.className="persona-feedback-label-high",y.textContent=p,A.appendChild(T),A.appendChild(y);let S=document.createElement("div");S.className="persona-feedback-numbers";let v=[];for(let D=0;D<=10;D++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${D} out of 10`),O.textContent=String(D),O.dataset.rating=String(D),D<=6?O.classList.add("persona-feedback-detractor"):D<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{u=D,v.forEach((Q,me)=>{Q.classList.toggle("selected",me===D),Q.setAttribute("aria-checked",me===D?"true":"false")})}),v.push(O),S.appendChild(O)}E.appendChild(A),E.appendChild(S),m.appendChild(E);let M=null;if(c){let D=document.createElement("div");D.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),D.appendChild(M),m.appendChild(D)}let I=document.createElement("div");I.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{r==null||r(),f.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=s,R.addEventListener("click",async()=>{if(u===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let D=(M==null?void 0:M.value.trim())||void 0;await t(u,D),f.remove()}catch(D){R.disabled=!1,R.textContent=s,console.error("[NPS Feedback] Failed to submit:",D)}}),I.appendChild(H),I.appendChild(R),m.appendChild(I),f.appendChild(m),f}var za="persona-chat-history",Yv=30*1e3,Zv={"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 e0(e){var o,n,a;if(!e)return[];let t=[],r=Array.from((o=e.items)!=null?o:[]);for(let s of r){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let c=(n=Zv[i.type])!=null?n:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${c}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let s of Array.from((a=e.files)!=null?a:[]))s.type.startsWith("image/")&&t.push(s);return t}function ll(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 t0(e){var t,r,o,n,a,s,i,c,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:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(n=(o=e.persist)==null?void 0:o.openState)!=null?n:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(c=(i=e.persist)==null?void 0:i.focusInput)!=null?c:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function r0(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var gp=e=>!e||typeof e!="object"?{}:{...e},nx=e=>e.map(t=>({...t,streaming:!1})),ax=(e,t,r)=>{let o=e!=null&&e.markdown?Kn(e.markdown):null,n=Ta(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&n&&(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."),a=>{var p,f,u;let s=(p=a.text)!=null?p:"",i=(f=a.message.rawContent)!=null?f:null;if(t){let m=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});m!==null&&(s=m.text,m.persist||(a.message.__skipPersist=!0),m.resubmit&&!a.streaming&&r&&r())}let c=Gn()!==null,l;if(e!=null&&e.postprocessMessage){let m=e.postprocessMessage({...a,text:s,raw:(u=i!=null?i:a.text)!=null?u:""});l=n?n(m):m}else if(o){let m=a.streaming?ug(s):s,x=o(m);l=n&&c?n(x):x}else l=No(s);return l}};function sx(e){var i,c,l,p;let t=C("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 r=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(c=e==null?void 0:e.iconSize)!=null?c:"48px",n=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",a=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,s=fe(r,o,n,a);if(s&&t.appendChild(s),e!=null&&e.label){let f=C("span","persona-drop-overlay-label");f.textContent=e.label,t.appendChild(f)}return t}var dl=(e,t,r)=>{var au,su,iu,lu,du,cu,pu,uu,fu,mu,gu,hu,xu,yu,bu,vu,Cu,wu,Su,Au,Mu,Tu,Eu,ku,Lu,Pu,Ru,Iu,Hu,Wu,Bu,Du,Fu,Nu,Ou,_u,Uu,qu,Vu,zu,$u,ju,Gu,Ku,Xu,Ju,Qu,Yu,Zu,ef;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 o=ki(t),n=Is.getForInstance(o.plugins),{plugin:a,teardown:s}=Nh();o.components&&on.registerAll(o.components);let i=Zh(),l=o.persistState===!1?null:(au=o.storageAdapter)!=null?au:tl(),p={},f=null,u=!1,m=d=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(d);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:w}=g;return w&&(u=!0),h}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return d};if(l!=null&&l.load)try{let d=l.load();if(d&&typeof d.then=="function")f=d.then(g=>{let h=g!=null?g:{messages:[],metadata:{}};return m(h)});else{let g=d!=null?d:{messages:[],metadata:{}},h=m(g);h.metadata&&(p=gp(h.metadata)),(su=h.messages)!=null&&su.length&&(o={...o,initialMessages:h.messages}),(iu=h.artifacts)!=null&&iu.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(lu=h.selectedArtifactId)!=null?lu:null})}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",d)}else if(o.onStateLoaded)try{let d=m({messages:[],metadata:{}});(du=d.messages)!=null&&du.length&&(o={...o,initialMessages:d.messages})}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",d)}let x=()=>p,b=d=>{var h;p=(h=d({...p}))!=null?h:{},k()},L=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Hs],E=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[da.message,da.messageAndClick],A=Ws({parsers:L,handlers:E,getSessionMetadata:x,updateSessionMetadata:b,emit:i.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let T=(pu=(cu=o.launcher)==null?void 0:cu.enabled)!=null?pu:!0,y=(fu=(uu=o.launcher)==null?void 0:uu.autoExpand)!=null?fu:!1,S=(mu=o.autoFocusInput)!=null?mu:!1,v=y,M=T,I=(hu=(gu=o.layout)==null?void 0:gu.header)==null?void 0:hu.layout,H=!1,R=()=>Rn(o),D=()=>T||R(),O=R()?!1:T?y:!0,Q=!1,me=null,ce=()=>{Q=!0,me&&clearTimeout(me),me=setTimeout(()=>{Q&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Q=!1)},1e4)},ee=ax(o,A,ce),Ce=(yu=(xu=o.features)==null?void 0:xu.showReasoning)!=null?yu:!0,Ie=(vu=(bu=o.features)==null?void 0:bu.showToolCalls)!=null?vu:!0,le=(wu=(Cu=o.features)==null?void 0:Cu.showEventStreamToggle)!=null?wu:!1,ve=(Au=(Su=o.features)==null?void 0:Su.scrollToBottom)!=null?Au:{},ae=(Tu=(Mu=o.features)==null?void 0:Mu.scrollBehavior)!=null?Tu:{},pe=`${(ku=typeof o.persistState=="object"?(Eu=o.persistState)==null?void 0:Eu.keyPrefix:void 0)!=null?ku:"persona-"}event-stream`,ze=le?new Ps(pe):null,_e=(Ru=(Pu=(Lu=o.features)==null?void 0:Lu.eventStream)==null?void 0:Pu.maxEvents)!=null?Ru:2e3,K=le?new Ls(_e,ze):null,J=le?new Rs:null,Se=null,Y=!1,ie=null,Re=0;ze==null||ze.open().then(()=>K==null?void 0:K.restore()).catch(d=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",d)});let rt={onCopy:d=>{var g,h;i.emit("message:copy",d),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(d.id,"copy").catch(w=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",w)}),(h=(g=o.messageActions)==null?void 0:g.onCopy)==null||h.call(g,d)},onFeedback:d=>{var g,h;i.emit("message:feedback",d),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(d.messageId,d.type).catch(w=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",w)}),(h=(g=o.messageActions)==null?void 0:g.onFeedback)==null||h.call(g,d)}},bt=(Iu=o.statusIndicator)!=null?Iu:{},qt=d=>{var g,h,w,P;return d==="idle"?(g=bt.idleText)!=null?g:Mr.idle:d==="connecting"?(h=bt.connectingText)!=null?h:Mr.connecting:d==="connected"?(w=bt.connectedText)!=null?w:Mr.connected:d==="error"?(P=bt.errorText)!=null?P:Mr.error:Mr[d]};function Gt(d,g,h,w){if(w==="idle"&&h.idleLink){d.textContent="";let P=document.createElement("a");P.href=h.idleLink,P.target="_blank",P.rel="noopener noreferrer",P.textContent=g,P.style.color="inherit",P.style.textDecoration="none",d.appendChild(P)}else d.textContent=g}let at=Mh({config:o,showClose:D()}),{wrapper:Ne,panel:G,pillRoot:je}=at.shell,$e=at.panelElements,{container:ye,body:we,messagesWrapper:Qe,suggestions:Xe,textarea:Ae,sendButton:Oe,sendButtonWrapper:fr,composerForm:Dt,statusText:Yt,introTitle:Uo,introSubtitle:F,closeButton:j,iconHolder:de,headerTitle:He,headerSubtitle:Ue,header:We,footer:Ee,actionsRow:st,leftActions:Pt,rightActions:gt}=$e,Rt=$e.setSendButtonMode,W=$e.micButton,ne=$e.micButtonWrapper,Me=$e.attachmentButton,Mt=$e.attachmentButtonWrapper,Ye=$e.attachmentInput,Vt=$e.attachmentPreviewsContainer;ye.classList.add("persona-relative"),we.classList.add("persona-relative");let br=12,xt=()=>{var d;return(d=ve.label)!=null?d:""},yt=()=>{var d;return(d=ve.iconName)!=null?d:"arrow-down"},It=()=>ve.enabled!==!1,vt=()=>{var d;return(d=ae.mode)!=null?d:"follow"},mr=()=>{var d;return(d=ae.anchorTopOffset)!=null?d:16},_t=C("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");_t.type="button",_t.style.display="none",_t.setAttribute("data-persona-scroll-to-bottom","true");let Ur=C("span","persona-flex persona-items-center"),Er=C("span",""),kr=C("span","");kr.setAttribute("data-persona-scroll-to-bottom-count",""),kr.style.display="none",_t.append(Ur,Er,kr),ye.appendChild(_t);let Cr=C("div","persona-stream-anchor-spacer");Cr.setAttribute("aria-hidden","true"),Cr.setAttribute("data-persona-anchor-spacer",""),Cr.style.flexShrink="0",Cr.style.pointerEvents="none",Cr.style.height="0px",we.appendChild(Cr);let Lr=()=>{let g=Ee.style.display==="none"?0:Ee.offsetHeight;_t.style.bottom=`${g+br}px`};Lr();let fo=()=>{let d=!!xt();_t.setAttribute("aria-label",xt()||"Jump to latest"),_t.title=xt(),_t.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false"),Ur.innerHTML="";let g=fe(yt(),"14px","currentColor",2);g?(Ur.appendChild(g),Ur.style.display=""):Ur.style.display="none",Er.textContent=xt(),Er.style.display=d?"":"none"};fo();let Ct=null,Ao=null,Mo=n.find(d=>d.renderHeader);if(Mo!=null&&Mo.renderHeader){let d=Mo.renderHeader({config:o,defaultRenderer:()=>{let g=rn({config:o,showClose:D()});return na(ye,g,o),g.header},onClose:()=>zt(!1,"user")});if(d){let g=ye.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(d),We=d,at.header.element=d)}}let qo=()=>{var g,h,w,P;if(!K)return;if(Y=!0,!Se&&K&&(Se=Vh({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>mo(),config:o,plugins:n,getThroughput:()=>{var N;return(N=J==null?void 0:J.getMetric())!=null?N:{status:"idle"}}})),Se&&(we.style.display="none",(g=Ee.parentNode)==null||g.insertBefore(Se.element,Ee),Se.update()),ct){ct.style.boxShadow=`inset 0 0 0 1.5px ${Dr.actionIconColor}`;let N=(P=(w=(h=o.features)==null?void 0:h.eventStream)==null?void 0:w.classNames)==null?void 0:P.toggleButtonActive;N&&N.split(/\s+/).forEach($=>$&&ct.classList.add($))}let d=()=>{if(!Y)return;let N=Date.now();N-Re>=200&&(Se==null||Se.update(),Re=N),ie=requestAnimationFrame(d)};Re=0,ie=requestAnimationFrame(d),Kr(),i.emit("eventStream:opened",{timestamp:Date.now()})},mo=()=>{var d,g,h;if(Y){if(Y=!1,Se&&Se.element.remove(),we.style.display="",ct){ct.style.boxShadow="";let w=(h=(g=(d=o.features)==null?void 0:d.eventStream)==null?void 0:g.classNames)==null?void 0:h.toggleButtonActive;w&&w.split(/\s+/).forEach(P=>P&&ct.classList.remove(P))}ie!==null&&(cancelAnimationFrame(ie),ie=null),Kr(),i.emit("eventStream:closed",{timestamp:Date.now()})}},ct=null;if(le){let d=(Wu=(Hu=o.features)==null?void 0:Hu.eventStream)==null?void 0:Wu.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"+(d!=null&&d.toggleButton?" "+d.toggleButton:"");ct=C("button",g),ct.style.width="28px",ct.style.height="28px",ct.style.color=Dr.actionIconColor,ct.type="button",ct.setAttribute("aria-label","Event Stream"),ct.title="Event Stream";let h=fe("activity","18px","currentColor",1.5);h&&ct.appendChild(h);let w=$e.clearChatButtonWrapper,P=$e.closeButtonWrapper,N=w||P;N&&N.parentNode===We?We.insertBefore(ct,N):We.appendChild(ct),ct.addEventListener("click",()=>{Y?mo():qo()})}let Hn=d=>{var P,N,$,U,_;let g=o.attachments;if(!(g!=null&&g.enabled))return;let h=(P=d.querySelector("[data-persona-composer-attachment-previews]"))!=null?P:d.querySelector(".persona-attachment-previews");if(!h){h=C("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let re=d.querySelector("[data-persona-composer-form]");re!=null&&re.parentNode?re.parentNode.insertBefore(h,re):d.insertBefore(h,d.firstChild)}if(!((N=d.querySelector("[data-persona-composer-attachment-input]"))!=null?N:d.querySelector('input[type="file"]'))){let re=C("input");re.type="file",re.setAttribute("data-persona-composer-attachment-input",""),re.accept=(($=g.allowedTypes)!=null?$:en).join(","),re.multiple=((U=g.maxFiles)!=null?U:4)>1,re.style.display="none",re.setAttribute("aria-label",(_=g.buttonTooltipText)!=null?_:"Attach files"),d.appendChild(re)}},To=n.find(d=>d.renderComposer);if(To!=null&&To.renderComposer){let d=o.composer,g=To.renderComposer({config:o,defaultRenderer:()=>Na({config:o}).footer,onSubmit:h=>{var $;if(!q||q.isStreaming())return;let w=h.trim(),P=($=Ct==null?void 0:Ct.hasAttachments())!=null?$:!1;if(!w&&!P)return;Dp();let N;P&&(N=[],N.push(...Ct.getContentParts()),w&&N.push(gs(w))),q.sendMessage(w,{contentParts:N}),P&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ye==null||Ye.click()},models:d==null?void 0:d.models,selectedModelId:d==null?void 0:d.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Bu=o.voiceRecognition)==null?void 0:Bu.enabled)===!0?()=>{Ao==null||Ao()}:void 0});g&&(at.replaceComposer(g),Ee=at.composer.footer)}let Wn=d=>{let g=(...oe)=>{for(let Z of oe){let xe=d.querySelector(Z);if(xe)return xe}return null},h=d.querySelector("[data-persona-composer-form]"),w=d.querySelector("[data-persona-composer-input]"),P=d.querySelector("[data-persona-composer-submit]"),N=d.querySelector("[data-persona-composer-mic]"),$=d.querySelector("[data-persona-composer-status]");h&&(Dt=h),w&&(Ae=w),P&&(Oe=P),N&&(W=N,ne=N.parentElement),$&&(Yt=$);let U=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Xe=U);let _=g("[data-persona-composer-attachment-button]",".persona-attachment-button");_&&(Me=_,Mt=_.parentElement),Ye=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Vt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let re=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");re&&(st=re)};Hn(Ee),Wn(Ee);let Fr=(_u=(Du=o.layout)==null?void 0:Du.contentMaxWidth)!=null?_u:R()?(Ou=(Nu=(Fu=o.launcher)==null?void 0:Fu.composerBar)==null?void 0:Nu.contentMaxWidth)!=null?Ou:"720px":void 0;if(Fr&&(Qe.style.maxWidth=Fr,Qe.style.marginLeft="auto",Qe.style.marginRight="auto",Qe.style.width="100%"),Fr&&Dt&&!R()&&(Dt.style.maxWidth=Fr,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),Fr&&Xe&&!R()&&(Xe.style.maxWidth=Fr,Xe.style.marginLeft="auto",Xe.style.marginRight="auto"),Fr&&Vt&&!R()&&(Vt.style.maxWidth=Fr,Vt.style.marginLeft="auto",Vt.style.marginRight="auto"),(Uu=o.attachments)!=null&&Uu.enabled&&Ye&&Vt){Ct=ta.fromConfig(o.attachments),Ct.setPreviewsContainer(Vt),Ye.addEventListener("change",h=>{let w=h.target;Ct==null||Ct.handleFileSelect(w.files),w.value=""});let d=o.attachments.dropOverlay,g=sx(d);ye.appendChild(g)}(()=>{var w,P;let d=(P=(w=o.layout)==null?void 0:w.slots)!=null?P:{},g=N=>{switch(N){case"body-top":return ye.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Qe;case"footer-top":return Xe;case"composer":return Dt;case"footer-bottom":return Yt;default:return null}},h=(N,$)=>{var U;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")We.insertBefore($,We.firstChild);else if(N==="header-right")We.appendChild($);else{let _=We.querySelector(".persona-flex-col");_?(U=_.parentNode)==null||U.insertBefore($,_.nextSibling):We.appendChild($)}break;case"body-top":{let _=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith($):we.insertBefore($,we.firstChild);break}case"body-bottom":we.appendChild($);break;case"footer-top":Xe.replaceWith($);break;case"footer-bottom":Yt.replaceWith($);break;default:break}};for(let[N,$]of Object.entries(d))if($)try{let U=$({config:o,defaultContent:()=>g(N)});U&&h(N,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,U)}})();let nn=d=>{var $,U;let h=d.target.closest('button[data-expand-header="true"]');if(!h)return;let w=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!w)return;let P=w.getAttribute("data-message-id");if(!P)return;let N=h.getAttribute("data-bubble-type");if(N==="reasoning")_a.has(P)?_a.delete(P):_a.add(P),Lh(P,w);else if(N==="tool")Ua.has(P)?Ua.delete(P):Ua.add(P),Ph(P,w,o);else if(N==="approval"){let _=o.approval!==!1?o.approval:void 0,re=(($=_==null?void 0:_.detailsDisplay)!=null?$:"collapsed")==="expanded",oe=(U=sa.get(P))!=null?U:re;sa.set(P,!oe),Wh(P,w,o)}Ro.delete(P)};Qe.addEventListener("pointerdown",d=>{d.target.closest('button[data-expand-header="true"]')&&(d.preventDefault(),nn(d))}),Qe.addEventListener("keydown",d=>{let g=d.target;(d.key==="Enter"||d.key===" ")&&g.closest('button[data-expand-header="true"]')&&(d.preventDefault(),nn(d))}),Qe.addEventListener("copy",d=>{let{clipboardData:g}=d;if(!g)return;let h=Qe.getRootNode(),w=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!w||w.isCollapsed)return;let P=w.toString(),N=ih(P);!N||N===P||(g.setData("text/plain",N),d.preventDefault())});let Vo=new Map,an=null,sn="idle",Bn={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Dn=(d,g)=>{let{icon:h,label:w}=Bn[g];d.setAttribute("aria-label",w),d.title=w,d.setAttribute("aria-pressed",g==="idle"?"false":"true"),d.classList.toggle("persona-message-action-active",g!=="idle"),d.classList.toggle("persona-message-action-loading",g==="loading");let P=fe(h,14,"currentColor",2);P&&(d.innerHTML="",d.appendChild(P))},ln=()=>{Qe.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{var N;let h=g.closest("[data-actions-for]"),w=(N=h==null?void 0:h.getAttribute("data-actions-for"))!=null?N:null;Dn(g,w&&w===an?sn:"idle")})};Qe.addEventListener("click",d=>{var $;let h=d.target.closest(".persona-message-action-btn[data-action]");if(!h)return;d.preventDefault(),d.stopPropagation();let w=h.closest("[data-actions-for]");if(!w)return;let P=w.getAttribute("data-actions-for");if(!P)return;let N=h.getAttribute("data-action");if(N==="copy"){let _=q.getMessages().find(re=>re.id===P);if(_&&rt.onCopy){let re=_.content||"";navigator.clipboard.writeText(re).then(()=>{h.classList.add("persona-message-action-success");let oe=fe("check",14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=fe("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(oe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",oe)}),rt.onCopy(_)}}else if(N==="read-aloud")q.toggleReadAloud(P);else if(N==="upvote"||N==="downvote"){let _=(($=Vo.get(P))!=null?$:null)===N,re=N==="upvote"?"thumbs-up":"thumbs-down";if(_){Vo.delete(P),h.classList.remove("persona-message-action-active");let oe=fe(re,14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe))}else{let oe=N==="upvote"?"downvote":"upvote",Z=w.querySelector(`[data-action="${oe}"]`);if(Z){Z.classList.remove("persona-message-action-active");let qe=fe(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(Z.innerHTML="",Z.appendChild(qe))}Vo.set(P,N),h.classList.add("persona-message-action-active");let xe=fe(re,14,"currentColor",2);xe&&(xe.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(xe)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let be=q.getMessages().find(Ze=>Ze.id===P);be&&rt.onFeedback&&rt.onFeedback({type:N,messageId:be.id,message:be})}}}),Qe.addEventListener("click",d=>{let h=d.target.closest("button[data-approval-action]");if(!h)return;d.preventDefault(),d.stopPropagation();let w=h.closest(".persona-approval-bubble");if(!w)return;let P=w.getAttribute("data-message-id");if(!P)return;let N=h.getAttribute("data-approval-action");if(!N)return;let $=N==="approve"?"approved":"denied",_=q.getMessages().find(oe=>oe.id===P);if(!(_!=null&&_.approval))return;let re=w.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),_.approval.toolType==="webmcp"?q.resolveWebMcpApproval(P,$):q.resolveApproval(_.approval,$)});let ht=null,qr=null,Vr={artifacts:[],selectedId:null},Pr=!1,wt={current:null};Qe.addEventListener("click",d=>{var Z,xe,Be,be,Ze;let h=d.target.closest("[data-download-artifact]");if(!h)return;d.preventDefault(),d.stopPropagation();let w=h.getAttribute("data-download-artifact");if(!w||((Be=(xe=(Z=o.features)==null?void 0:Z.artifacts)==null?void 0:xe.onArtifactAction)==null?void 0:Be.call(xe,{type:"download",artifactId:w}))===!0)return;let N=q.getArtifactById(w),$=N==null?void 0:N.markdown,U=(N==null?void 0:N.title)||"artifact";if(!$){let qe=h.closest("[data-open-artifact]"),lt=qe==null?void 0:qe.closest("[data-message-id]"),et=lt==null?void 0:lt.getAttribute("data-message-id");if(et){let Te=q.getMessages().find(Ve=>Ve.id===et);if(Te!=null&&Te.rawContent)try{let Ve=JSON.parse(Te.rawContent);$=(be=Ve==null?void 0:Ve.props)==null?void 0:be.markdown,U=((Ze=Ve==null?void 0:Ve.props)==null?void 0:Ze.title)||U}catch{}}}if(!$)return;let _=new Blob([$],{type:"text/markdown"}),re=URL.createObjectURL(_),oe=document.createElement("a");oe.href=re,oe.download=`${U}.md`,oe.click(),URL.revokeObjectURL(re)}),Qe.addEventListener("click",d=>{var N,$,U;let h=d.target.closest("[data-open-artifact]");if(!h)return;let w=h.getAttribute("data-open-artifact");!w||((U=($=(N=o.features)==null?void 0:N.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:U.call($,{type:"open",artifactId:w}))===!0||(d.preventDefault(),d.stopPropagation(),Pr=!1,q.selectArtifact(w),Nr())}),Qe.addEventListener("keydown",d=>{if(d.key!=="Enter"&&d.key!==" ")return;let g=d.target;g.hasAttribute("data-open-artifact")&&(d.preventDefault(),g.click())});let ro=$e.composerOverlay,oo=(d,g,h)=>{var U,_,re,oe;let w=g.trim();if(!w||!wt.current)return;let P=(U=d.getAttribute("data-tool-call-id"))!=null?U:"",N=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:P,answer:w,answers:h.structured,values:(_=h.values)!=null?_:h.source==="multi"?w.split(", "):[w],isFreeText:N,source:h.source},bubbles:!0,composed:!0})),Sn(ro,P);let $=wt.current.getMessages().find(Z=>{var xe;return((xe=Z.toolCall)==null?void 0:xe.id)===P});(re=$==null?void 0:$.agentMetadata)!=null&&re.awaitingLocalTool?wt.current.resolveAskUserQuestion($,(oe=h.structured)!=null?oe:w):wt.current.sendMessage(w)},zr=d=>{var P;let g=wt.current;if(!g)return;let h=(P=d.getAttribute("data-tool-call-id"))!=null?P:"",w=g.getMessages().find(N=>{var $;return(($=N.toolCall)==null?void 0:$.id)===h});w&&g.persistAskUserQuestionProgress(w,{answers:Zs(d,w),currentIndex:po(d)})},dn=d=>Object.entries(d).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),zo=d=>{var P,N,$;if(((N=(P=o.features)==null?void 0:P.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let g=po(d),h=La(d);if(g>=h-1)return;let w=($=wt.current)==null?void 0:$.getMessages().find(U=>{var _;return((_=U.toolCall)==null?void 0:_.id)===d.getAttribute("data-tool-call-id")});w&&(ei(d,w,o,g+1),zr(d))};ro.addEventListener("click",d=>{var N,$,U,_,re,oe,Z,xe,Be,be,Ze,qe,lt,et;let h=d.target.closest("[data-ask-user-action]");if(!h)return;let w=h.closest("[data-persona-ask-sheet-for]");if(!w)return;let P=h.getAttribute("data-ask-user-action");if(d.preventDefault(),d.stopPropagation(),P==="dismiss"){let ke=(N=w.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ke},bubbles:!0,composed:!0})),Sn(ro,ke);let Te=($=wt.current)==null?void 0:$.getMessages().find(Ve=>{var Ge;return((Ge=Ve.toolCall)==null?void 0:Ge.id)===ke});(U=Te==null?void 0:Te.agentMetadata)!=null&&U.awaitingLocalTool&&((_=wt.current)==null||_.markAskUserQuestionResolved(Te),(re=wt.current)==null||re.resolveAskUserQuestion(Te,"(dismissed)"));return}if(P==="pick"){let ke=h.getAttribute("data-option-label");if(!ke)return;let Te=w.getAttribute("data-multi-select")==="true",Ve=wn(w);if(Ve&&Te){let Ge=Xn(w)[po(w)],ft=new Set(Array.isArray(Ge)?Ge:[]);ft.has(ke)?ft.delete(ke):ft.add(ke),An(w,Array.from(ft)),zr(w);return}if(Ve){An(w,ke),zr(w),zo(w);return}if(Te){let Ge=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ge?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ge);let ft=w.querySelector('[data-ask-user-action="submit-multi"]');ft&&(ft.disabled=Il(w).length===0);return}oo(w,ke,{source:"pick",values:[ke]});return}if(P==="submit-multi"){let ke=Il(w);if(ke.length===0)return;oo(w,ke.join(", "),{source:"multi",values:ke});return}if(P==="open-free-text"){let ke=w.querySelector('[data-ask-free-text-row="true"]');if(ke){ke.classList.remove("persona-hidden");let Te=ke.querySelector('[data-ask-free-text-input="true"]');Te==null||Te.focus()}return}if(P==="focus-free-text"){let ke=w.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus();return}if(P==="submit-free-text"){let ke=w.querySelector('[data-ask-free-text-input="true"]'),Te=(oe=ke==null?void 0:ke.value)!=null?oe:"";if(!Te.trim())return;if(wn(w)){An(w,Te.trim()),zr(w),zo(w);return}oo(w,Te,{source:"free-text"});return}if(P==="next"||P==="back"){if(!wt.current)return;let ke=(Z=w.getAttribute("data-tool-call-id"))!=null?Z:"",Te=wt.current.getMessages().find(Pe=>{var Le;return((Le=Pe.toolCall)==null?void 0:Le.id)===ke});if(!Te)return;let Ve=w.querySelector('[data-ask-free-text-input="true"]'),Ge=(Be=(xe=Ve==null?void 0:Ve.value)==null?void 0:xe.trim())!=null?Be:"";if(Ge){let Pe=Xn(w)[po(w)];(typeof Pe!="string"||Pe!==Ge)&&An(w,Ge)}let ft=P==="next"?1:-1,B=po(w)+ft;ei(w,Te,o,B),zr(w);return}if(P==="submit-all"){if(!wt.current)return;let ke=(be=w.getAttribute("data-tool-call-id"))!=null?be:"",Te=wt.current.getMessages().find(Pe=>{var Le;return((Le=Pe.toolCall)==null?void 0:Le.id)===ke});if(!Te)return;let Ve=w.querySelector('[data-ask-free-text-input="true"]'),Ge=(qe=(Ze=Ve==null?void 0:Ve.value)==null?void 0:Ze.trim())!=null?qe:"";Ge&&An(w,Ge);let ft=Zs(w,Te);wt.current.persistAskUserQuestionProgress(Te,{answers:ft,currentIndex:po(w)});let B=dn(ft);oo(w,B||"(submitted)",{source:"submit-all",structured:ft});return}if(P==="skip"){if(!wt.current)return;let ke=(lt=w.getAttribute("data-tool-call-id"))!=null?lt:"",Te=wt.current.getMessages().find(Le=>{var ue;return((ue=Le.toolCall)==null?void 0:ue.id)===ke});if(!Te)return;let Ve=wn(w),Ge=po(w),ft=La(w),B=Ge>=ft-1;if(!Ve){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:ke},bubbles:!0,composed:!0})),Sn(ro,ke),(et=Te.agentMetadata)!=null&&et.awaitingLocalTool&&(wt.current.markAskUserQuestionResolved(Te),wt.current.resolveAskUserQuestion(Te,"(dismissed)"));return}An(w,"");let Pe=w.querySelector('[data-ask-free-text-input="true"]');if(Pe&&(Pe.value=""),B){let Le=Zs(w,Te),ue=dn(Le);oo(w,ue||"(skipped)",{source:"submit-all",structured:Le});return}ei(w,Te,o,Ge+1),zr(w);return}}),ro.addEventListener("keydown",d=>{var N;if(d.key!=="Enter")return;let h=d.target;if(!((N=h.matches)!=null&&N.call(h,'[data-ask-free-text-input="true"]')))return;let w=h.closest("[data-persona-ask-sheet-for]");if(!w)return;d.preventDefault();let P=h.value;if(P.trim()){if(wn(w)){An(w,P.trim()),zr(w),zo(w);return}oo(w,P,{source:"free-text"})}});let cn=d=>{if(!/^[1-9]$/.test(d.key)||d.metaKey||d.ctrlKey||d.altKey)return;let g=d.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let h=ro.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let w=Number(d.key),N=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[w-1];N&&(d.preventDefault(),N.click())};document.addEventListener("keydown",cn);let $r=null,Ht=null,Rr=null,no=null,pn=()=>{};function $o(){no==null||no(),no=null}let un=()=>{var $;if(!$r||!Ht)return;let d=e.classList.contains("persona-artifact-appearance-seamless"),h=(($=e.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!d||e.classList.contains("persona-artifact-narrow-host")||h){Ht.style.removeProperty("position"),Ht.style.removeProperty("left"),Ht.style.removeProperty("top"),Ht.style.removeProperty("bottom"),Ht.style.removeProperty("width"),Ht.style.removeProperty("z-index");return}let w=$r.firstElementChild;if(!w||w===Ht)return;let P=10;Ht.style.position="absolute",Ht.style.top="0",Ht.style.bottom="0",Ht.style.width=`${P}px`,Ht.style.zIndex="5";let N=w.offsetWidth-P/2;Ht.style.left=`${Math.max(0,N)}px`},he=()=>{},Nr=()=>{var h,w,P,N,$;if(!ht||!uo(o))return;Zi(e,o),el(e,o),he();let d=(N=(P=(w=(h=o.features)==null?void 0:h.artifacts)==null?void 0:w.layout)==null?void 0:P.narrowHostMaxWidth)!=null?N:520,g=G.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=d),ht.update(Vr),Pr?(ht.setMobileOpen(!1),ht.element.classList.add("persona-hidden"),($=ht.backdrop)==null||$.classList.add("persona-hidden")):Vr.artifacts.length>0&&(ht.element.classList.remove("persona-hidden"),ht.setMobileOpen(!0)),pn()};if(uo(o)){G.style.position="relative";let d=C("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=C("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");d.appendChild(ye),ht=jh(o,{onSelect:h=>{var w;return(w=wt.current)==null?void 0:w.selectArtifact(h)},onDismiss:()=>{Pr=!0,Nr()}}),ht.element.classList.add("persona-hidden"),$r=g,g.appendChild(d),g.appendChild(ht.element),ht.backdrop&&G.appendChild(ht.backdrop),G.appendChild(g),pn=()=>{var w,P,N,$;if(!$r||!ht)return;if(!(((N=(P=(w=o.features)==null?void 0:w.artifacts)==null?void 0:P.layout)==null?void 0:N.resizable)===!0)){Rr==null||Rr(),Rr=null,$o(),Ht&&(Ht.remove(),Ht=null),ht.element.style.removeProperty("width"),ht.element.style.removeProperty("maxWidth");return}if(!Ht){let U=C("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 _=e.ownerDocument,re=($=_.defaultView)!=null?$:window,oe=Z=>{var lt,et;if(!ht||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||re.innerWidth<=640)return;Z.preventDefault(),$o();let xe=Z.clientX,Be=ht.element.getBoundingClientRect().width,be=(et=(lt=o.features)==null?void 0:lt.artifacts)==null?void 0:et.layout,Ze=ke=>{let Te=$r.getBoundingClientRect().width,Ve=e.classList.contains("persona-artifact-appearance-seamless"),Ge=Ve?0:Jh($r,re),ft=Ve?0:U.getBoundingClientRect().width||6,B=Be-(ke.clientX-xe),Pe=Qh(B,Te,Ge,ft,be==null?void 0:be.resizableMinWidth,be==null?void 0:be.resizableMaxWidth);ht.element.style.width=`${Pe}px`,ht.element.style.maxWidth="none",un()},qe=()=>{_.removeEventListener("pointermove",Ze),_.removeEventListener("pointerup",qe),_.removeEventListener("pointercancel",qe),no=null;try{U.releasePointerCapture(Z.pointerId)}catch{}};no=qe,_.addEventListener("pointermove",Ze),_.addEventListener("pointerup",qe),_.addEventListener("pointercancel",qe);try{U.setPointerCapture(Z.pointerId)}catch{}};U.addEventListener("pointerdown",oe),Ht=U,$r.insertBefore(U,ht.element),Rr=()=>{U.removeEventListener("pointerdown",oe)}}if(Ht){let U=Vr.artifacts.length>0&&!Pr;Ht.classList.toggle("persona-hidden",!U),un()}},he=()=>{var re,oe,Z,xe,Be,be,Ze,qe,lt,et,ke,Te,Ve,Ge;if(!T||!ht||((oe=(re=o.launcher)==null?void 0:re.sidebarMode)!=null?oe:!1)||sr(o)&&eo(o).reveal==="emerge")return;let w=(Z=e.ownerDocument.defaultView)!=null?Z:window,P=(Be=(xe=o.launcher)==null?void 0:xe.mobileFullscreen)!=null?Be:!0,N=(Ze=(be=o.launcher)==null?void 0:be.mobileBreakpoint)!=null?Ze:640;if(P&&w.innerWidth<=N||!Xh(o,T))return;let $=(et=(lt=(qe=o.launcher)==null?void 0:qe.width)!=null?lt:o.launcherWidth)!=null?et:Zr,U=(Ge=(Ve=(Te=(ke=o.features)==null?void 0:ke.artifacts)==null?void 0:Te.layout)==null?void 0:Ve.expandedPanelWidth)!=null?Ge:"min(720px, calc(100vw - 24px))";Vr.artifacts.length>0&&!Pr?(G.style.width=U,G.style.maxWidth=U):(G.style.width=$,G.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(qr=new ResizeObserver(()=>{Nr()}),qr.observe(G))}else G.appendChild(ye),R()&&je&&($e.peekBanner&&je.appendChild($e.peekBanner),je.appendChild(Ee));e.appendChild(Ne),je&&e.appendChild(je);let Eo=()=>{var Pe,Le,ue,Ft,Wt,Xt,mt,$t,Xr,rr,Ke,Tt,ar,lo,Jr,Un,qn,wa,Sa,Jt,Vn,xn,yn,Jo,zn,yo,Do,Je;if(R()){G.style.width="100%",G.style.maxWidth="100%";let Nt=(Le=(Pe=o.launcher)==null?void 0:Pe.composerBar)!=null?Le:{},Kt=Ne.dataset.state==="expanded",Ot=(ue=Nt.expandedSize)!=null?ue:"anchored";if(!(Kt&&Ot!=="fullscreen")){ye.style.background="",ye.style.border="",ye.style.borderRadius="",ye.style.overflow="",ye.style.boxShadow="";return}let Et=(Wt=(Ft=o.theme)==null?void 0:Ft.components)==null?void 0:Wt.panel,Ut=Da(o),hr=(yr,co)=>{var bn;return yr==null||yr===""?co:(bn=Wa(Ut,yr))!=null?bn:yr},Qr="1px solid var(--persona-border)",Fo="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",xr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ye.style.background="var(--persona-surface, #ffffff)",ye.style.border=hr(Et==null?void 0:Et.border,Qr),ye.style.borderRadius=hr(Et==null?void 0:Et.borderRadius,xr),ye.style.boxShadow=hr(Et==null?void 0:Et.shadow,Fo),ye.style.overflow="hidden";return}let d=sr(o),g=(mt=(Xt=o.launcher)==null?void 0:Xt.sidebarMode)!=null?mt:!1,h=d||g||((Xr=($t=o.launcher)==null?void 0:$t.fullHeight)!=null?Xr:!1),w=((rr=o.launcher)==null?void 0:rr.enabled)===!1,P=(Tt=(Ke=o.theme)==null?void 0:Ke.components)==null?void 0:Tt.panel,N=Da(o),$=(Nt,Kt)=>{var Ot;return Nt==null||Nt===""?Kt:(Ot=Wa(N,Nt))!=null?Ot:Nt},U=(ar=e.ownerDocument.defaultView)!=null?ar:window,_=(Jr=(lo=o.launcher)==null?void 0:lo.mobileFullscreen)!=null?Jr:!0,re=(qn=(Un=o.launcher)==null?void 0:Un.mobileBreakpoint)!=null?qn:640,oe=U.innerWidth<=re,Z=_&&oe&&T,xe=(Sa=(wa=o.launcher)==null?void 0:wa.position)!=null?Sa:"bottom-left",Be=xe==="bottom-left"||xe==="top-left",be=(Vn=(Jt=o.launcher)==null?void 0:Jt.zIndex)!=null?Vn:Tr,Ze=g||Z?"none":"1px solid var(--persona-border)",qe=Z?"none":g?Be?"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))";d&&!Z&&(qe="none",Ze="none");let lt=g||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",et=$(P==null?void 0:P.border,Ze),ke=$(P==null?void 0:P.shadow,qe),Te=$(P==null?void 0:P.borderRadius,lt),Ve=we.scrollTop;e.style.cssText="",Ne.style.cssText="",G.style.cssText="",ye.style.cssText="",we.style.cssText="",Ee.style.cssText="";let Ge=()=>{var Kt;if(Ve<=0)return;((Kt=we.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(we.scrollTop===Ve)return;let Ot=we.scrollHeight-we.clientHeight;Ot<=0||(we.scrollTop=Math.min(Ve,Ot))})};if(Z){Ne.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"),Ne.style.cssText=`
34
36
  position: fixed !important;
35
37
  inset: 0 !important;
36
38
  width: 100% !important;
@@ -40,9 +42,9 @@ _Details: ${r.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
40
42
  padding: 0 !important;
41
43
  display: flex !important;
42
44
  flex-direction: column !important;
43
- z-index: ${Ce} !important;
45
+ z-index: ${be} !important;
44
46
  background-color: var(--persona-surface, #ffffff) !important;
45
- `,fe.style.cssText=`
47
+ `,G.style.cssText=`
46
48
  position: relative !important;
47
49
  display: flex !important;
48
50
  flex-direction: column !important;
@@ -55,7 +57,7 @@ _Details: ${r.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
55
57
  padding: 0 !important;
56
58
  box-shadow: none !important;
57
59
  border-radius: 0 !important;
58
- `,ie.style.cssText=`
60
+ `,ye.style.cssText=`
59
61
  display: flex !important;
60
62
  flex-direction: column !important;
61
63
  flex: 1 1 0% !important;
@@ -66,20 +68,20 @@ _Details: ${r.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
66
68
  overflow: hidden !important;
67
69
  border-radius: 0 !important;
68
70
  border: none !important;
69
- `,ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",Le.style.flexShrink="0",T=!0,je();return}let ht=(hn=(gn=o==null?void 0:o.launcher)==null?void 0:gn.width)!=null?hn:o==null?void 0:o.launcherWidth,B=ht!=null?ht:Yr;if(!f&&!l)v&&h?(fe.style.width="100%",fe.style.maxWidth="100%"):(fe.style.width=B,fe.style.maxWidth=B);else if(l)if(Zr(o).reveal==="emerge"){let Ot=Zr(o).width;fe.style.width=Ot,fe.style.maxWidth=Ot}else fe.style.width="100%",fe.style.maxWidth="100%";if(Mo(),fe.style.boxShadow=Pe,fe.style.borderRadius=ke,ie.style.border=nt,ie.style.borderRadius=ke,l&&!J&&(W==null?void 0:W.border)===void 0&&(ie.style.border="none",Zr(o).side==="right"?ie.style.borderLeft="1px solid var(--persona-border)":ie.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),Oe.style.display="flex",Oe.style.flexDirection="column",Oe.style.flex="1 1 0%",Oe.style.minHeight="0",Oe.style.maxHeight="100%",Oe.style.height="100%",v&&(Oe.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",ie.style.display="flex",ie.style.flexDirection="column",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.maxHeight="100%",ie.style.overflow="hidden",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",Le.style.flexShrink="0"),Oe.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"),!f&&!v&&!l&&((Go=vo[xe])!=null?Go:vo["bottom-right"]).split(" ").forEach(Ot=>Oe.classList.add(Ot)),f){let _t=(ho=(_n=o.launcher)==null?void 0:_n.sidebarWidth)!=null?ho:"420px";Oe.style.cssText=`
71
+ `,we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",Ee.style.flexShrink="0",H=!0,Ge();return}let ft=(yn=(xn=o==null?void 0:o.launcher)==null?void 0:xn.width)!=null?yn:o==null?void 0:o.launcherWidth,B=ft!=null?ft:Zr;if(!g&&!d)w&&h?(G.style.width="100%",G.style.maxWidth="100%"):(G.style.width=B,G.style.maxWidth=B);else if(d)if(eo(o).reveal==="emerge"){let Kt=eo(o).width;G.style.width=Kt,G.style.maxWidth=Kt}else G.style.width="100%",G.style.maxWidth="100%";if(he(),G.style.boxShadow=ke,G.style.borderRadius=Te,ye.style.border=et,ye.style.borderRadius=Te,d&&!Z&&(P==null?void 0:P.border)===void 0&&(ye.style.border="none",eo(o).side==="right"?ye.style.borderLeft="1px solid var(--persona-border)":ye.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",w&&(e.style.width="100%"),Ne.style.display="flex",Ne.style.flexDirection="column",Ne.style.flex="1 1 0%",Ne.style.minHeight="0",Ne.style.maxHeight="100%",Ne.style.height="100%",w&&(Ne.style.overflow="hidden"),G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.height="100%",G.style.overflow="hidden",ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.overflow="hidden",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",Ee.style.flexShrink="0"),Ne.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&&!w&&!d&&((Jo=So[xe])!=null?Jo:So["bottom-right"]).split(" ").forEach(Kt=>Ne.classList.add(Kt)),g){let Nt=(yo=(zn=o.launcher)==null?void 0:zn.sidebarWidth)!=null?yo:"420px";Ne.style.cssText=`
70
72
  position: fixed !important;
71
73
  top: 0 !important;
72
74
  bottom: 0 !important;
73
- width: ${_t} !important;
75
+ width: ${Nt} !important;
74
76
  height: 100vh !important;
75
77
  max-height: 100vh !important;
76
78
  margin: 0 !important;
77
79
  padding: 0 !important;
78
80
  display: flex !important;
79
81
  flex-direction: column !important;
80
- z-index: ${Ce} !important;
81
- ${De?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
82
- `,fe.style.cssText=`
82
+ z-index: ${be} !important;
83
+ ${Be?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
84
+ `,G.style.cssText=`
83
85
  position: relative !important;
84
86
  display: flex !important;
85
87
  flex-direction: column !important;
@@ -90,9 +92,9 @@ _Details: ${r.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
90
92
  min-height: 0 !important;
91
93
  margin: 0 !important;
92
94
  padding: 0 !important;
93
- box-shadow: ${Pe} !important;
94
- border-radius: ${ke} !important;
95
- `,fe.style.setProperty("width","100%","important"),fe.style.setProperty("max-width","100%","important"),ie.style.cssText=`
95
+ box-shadow: ${ke} !important;
96
+ border-radius: ${Te} !important;
97
+ `,G.style.setProperty("width","100%","important"),G.style.setProperty("max-width","100%","important"),ye.style.cssText=`
96
98
  display: flex !important;
97
99
  flex-direction: column !important;
98
100
  flex: 1 1 0% !important;
@@ -101,29 +103,29 @@ _Details: ${r.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
101
103
  min-height: 0 !important;
102
104
  max-height: 100% !important;
103
105
  overflow: hidden !important;
104
- border-radius: ${ke} !important;
105
- border: ${nt} !important;
106
- `,Le.style.cssText=`
106
+ border-radius: ${Te} !important;
107
+ border: ${et} !important;
108
+ `,Ee.style.cssText=`
107
109
  flex-shrink: 0 !important;
108
110
  border-top: none !important;
109
111
  padding: 8px 16px 12px 16px !important;
110
- `}if(!v&&!l){let _t="max-height: -moz-available !important; max-height: stretch !important;",Ot=f?"":"padding-top: 1.25em !important;",ut=f?"":`z-index: ${(lr=(Qe=o.launcher)==null?void 0:Qe.zIndex)!=null?lr:Sr} !important;`;Oe.style.cssText+=_t+Ot+ut}je()};ge(),An(e,o),Ji(e,o),Qi(e,o);let it=[];it.push(()=>{document.removeEventListener("keydown",ln)});let Xt=null,sr=null;it.push(()=>{Xt==null||Xt(),Xt=null,sr==null||sr(),sr=null}),_r&&it.push(()=>{_r==null||_r.disconnect(),_r=null}),it.push(()=>{Tr==null||Tr(),Tr=null,_o(),Bt&&(Bt.remove(),Bt=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),Ie&&it.push(()=>{Ge!==null&&(cancelAnimationFrame(Ge),Ge=null),K==null||K.destroy(),K=null,ye==null||ye.destroy(),ye=null,Q=null});let To=null,Ua=()=>{To&&(To(),To=null),o.colorScheme==="auto"&&(To=ki(()=>{An(e,o)}))};Ua(),it.push(()=>{To&&(To(),To=null)});let Uo=(Ou=o.features)==null?void 0:Ou.streamAnimation;if(Uo!=null&&Uo.type&&Uo.type!=="none"){let l=ys(Uo.type,Uo.plugins);l&&($p(l,e),it.push(()=>uh(e)))}let Wn=kh(Pt),Eo=null,_,sa=l=>{var v,W;if(!_)return;let f=l!=null?l:_.getMessages(),h=((W=(v=o.features)==null?void 0:v.suggestReplies)==null?void 0:W.enabled)!==!1?Zs(f):null;h?Wn.render(h,_,we,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(D=>D.role==="user")?Wn.render([],_,we,f):Wn.render(o.suggestionChips,_,we,f,o.suggestionChipsConfig)},ko=!1,Lo=oh(),qo=new Map,Po=new Map,fo=new Map,ia=0,Is=zn()!==null,$r=Ri(),jr=0,mo=null,go=!1,Hn=!1,Vo=0,br=null,Ro=null,la=!1,Bn=!1,da=null,Ws=4,pa=24,Hs=80,ca=new Map,ft={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},qa=(Uu=(_u=o.voiceRecognition)==null?void 0:_u.autoResume)!=null?Uu:!1,ao=l=>{a.emit("voice:state",{active:ft.active,source:l,timestamp:Date.now()})},Br=()=>{m(l=>({...l,voiceState:{active:ft.active,timestamp:Date.now(),manuallyDeactivated:ft.manuallyDeactivated}}))},Bs=()=>{var v,W;if(((v=o.voiceRecognition)==null?void 0:v.enabled)===!1)return;let l=uc(p.voiceState),f=!!l.active,h=Number((W=l.timestamp)!=null?W:0);ft.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-h<Pv&&setTimeout(()=>{var D,$;ft.active||(ft.manuallyDeactivated=!1,(($=(D=o.voiceRecognition)==null?void 0:D.provider)==null?void 0:$.type)==="runtype"?_.toggleVoice().then(()=>{ft.active=_.isVoiceActive(),ao("restore"),_.isVoiceActive()&&ma()}):Ns("restore"))},1e3)},Ds=()=>_?Gh(_.getMessages()).filter(l=>!l.__skipPersist):[];function cn(l){if(!(i!=null&&i.save))return;let h={messages:l?Gh(l):_?Ds():[],metadata:p,artifacts:Ur.artifacts,selectedArtifactId:Ur.selectedId};try{let v=i.save(h);v instanceof Promise&&v.catch(W=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",W)})}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",v)}}let tt=null,E=()=>Oe.querySelector("#persona-scroll-container")||ve,V=()=>{tt!==null&&(cancelAnimationFrame(tt),tt=null),go=!1},q=()=>{mo!==null&&(cancelAnimationFrame(mo),mo=null),Hn=!1,V()},G=()=>{Vo>0?(Ar.textContent=String(Vo),Ar.style.display="",st.setAttribute("aria-label",`${er()||"Jump to latest"} (${Vo} new)`)):(Ar.textContent="",Ar.style.display="none",st.setAttribute("aria-label",er()||"Jump to latest"))},me=()=>{Vo!==0&&(Vo=0,G())},Fe=()=>et()==="follow"?!$r.isFollowing():!Zn(ve,pa),Je=()=>{if(!Ht()||oe){st.parentNode&&st.remove(),st.style.display="none";return}st.parentNode!==ie&&ie.appendChild(st),Wr();let f=Zo(ve)>0&&Fe();f||me(),st.style.display=f?"":"none"},Tt=()=>{$r.pause()&&(q(),Je())},zo=()=>{$r.resume(),me(),Je()},Dr=(l=!1)=>{et()==="follow"&&$r.isFollowing()&&(!l&&!ko||(mo!==null&&(cancelAnimationFrame(mo),mo=null),Hn=!0,mo=requestAnimationFrame(()=>{mo=null,Hn=!1,$r.isFollowing()&&mr(E(),l?220:140)})))},Gr=(l,f,h,v=()=>!0)=>{let W=l.scrollTop,D=f(),$=D-W;V();let O=performance.now();go=!0;let F=re=>1-Math.pow(1-re,3),te=re=>{if(!v()){V();return}let J=f();J!==D&&(D=J,$=D-W);let xe=re-O,De=Math.min(xe/h,1),Ce=F(De),rt=W+$*Ce;l.scrollTop=rt,jr=l.scrollTop,De<1?tt=requestAnimationFrame(te):(l.scrollTop=D,jr=l.scrollTop,tt=null,go=!1)};tt=requestAnimationFrame(te)},mr=(l,f=500)=>{let h=Zo(l)-l.scrollTop;if(Math.abs(h)<1){jr=l.scrollTop;return}if(Math.abs(h)>=Hs){V(),go=!0,l.scrollTop=Zo(l),jr=l.scrollTop,go=!1;return}Gr(l,()=>Zo(l),f,()=>$r.isFollowing())},un=()=>{let l=E();go=!0,l.scrollTop=Zo(l),jr=l.scrollTop,go=!1,Je()},$o=l=>{tr.style.height=`${Math.max(0,Math.round(l))}px`,br&&(br.spacerHeight=Math.max(0,l))},gr=()=>{Ro!==null&&(cancelAnimationFrame(Ro),Ro=null),V(),br=null,tr.style.height="0px"},Fr=l=>{Ro!==null&&cancelAnimationFrame(Ro),Ro=requestAnimationFrame(()=>{var te;Ro=null;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=ve.querySelector(`[data-message-id="${f}"]`);if(!h)return;let v=0,W=h;for(;W&&W!==ve;)v+=W.offsetTop,W=W.offsetParent;let D=(te=br==null?void 0:br.spacerHeight)!=null?te:0,$=ve.scrollHeight-D,{targetScrollTop:O,spacerHeight:F}=lh({anchorOffsetTop:v,topOffset:Wt(),viewportHeight:ve.clientHeight,contentHeight:$});br={initialSpacerHeight:F,contentHeightAtAnchor:$,spacerHeight:F},$o(F),Gr(ve,()=>O,220)})},Kr=()=>{if(et()==="follow"){if(!$r.isFollowing()||Zn(ve,1))return;Dr(!ko);return}if(br&&br.initialSpacerHeight>0){let l=ve.scrollHeight-br.spacerHeight,f=dh({initialSpacerHeight:br.initialSpacerHeight,contentHeightAtAnchor:br.contentHeightAtAnchor,currentContentHeight:l});f!==br.spacerHeight&&$o(f)}Je()},Ix=l=>{let f=et();f==="follow"?(zo(),Dr(!0)):f==="anchor-top"&&Fr(l)},Wx=l=>{let f=new Map;l.forEach(h=>{let v=ca.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!v&&h.role==="assistant"&&(a.emit("assistant:message",h),!Bn&&et()!=="anchor-top"&&Fe()&&(Vo+=1,G(),Je())),h.role==="assistant"&&(v!=null&&v.streaming)&&h.streaming===!1&&a.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(v?h.approval.status!=="pending"&&a.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):a.emit("approval:requested",{approval:h.approval,message:h}))}),ca.clear(),f.forEach((h,v)=>{ca.set(v,h)})},Hx=(l,f,h)=>{var nt,Pe,ke,Ue,je,ht;let v=document.createElement("div"),D=(()=>{var He;let B=n.find(Re=>Re.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((He=o.loadingIndicator)!=null&&He.render)return o.loadingIndicator.render})(),$=(B,He)=>He==null?!1:typeof He=="string"?(B.textContent=He,!0):(B.appendChild(He),!0),O=new Set,F=new Set,te=n.some(B=>B.renderAskUserQuestion),re=[],J=[],xe=o.enableComponentStreaming!==!1,De=n.some(B=>B.renderApproval)&&o.approval!==!1,Ce=[];if(f.forEach(B=>{var Xe,Et,or,lo,Jr,Fn,Nn,ha,xa,$t,On,gn,hn,Go,_n,ho;O.add(B.id);let He=te&&Xo(B),Re=De&&B.variant==="approval"&&!!B.approval,ue=!He&&B.role==="assistant"&&!B.variant&&xe&&tl(B);if(!Re&&fo.has(B.id)){let Qe=l.querySelector(`#wrapper-${B.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),fo.delete(B.id)}if(!ue&&Po.has(B.id)){let Qe=l.querySelector(`#wrapper-${B.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),Po.delete(B.id)}let Nt=Xo(B)?`:${(Xe=B.agentMetadata)!=null&&Xe.askUserQuestionAnswered?"a":"u"}:${(Et=B.agentMetadata)!=null&&Et.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Dt=rh(B,ia)+Nt,zt=He||Re||ue?null:nh(Lo,B.id,Dt);if(zt){v.appendChild(zt.cloneNode(!0)),Xo(B)&&((or=B.toolCall)!=null&&or.id)&&((lo=B.agentMetadata)==null?void 0:lo.awaitingLocalTool)===!0&&!((Jr=B.agentMetadata)!=null&&Jr.askUserQuestionAnswered)&&(F.add(B.toolCall.id),Aa(B,o,X.composerOverlay));return}let bt=null,qt=n.find(Qe=>!!(B.variant==="reasoning"&&Qe.renderReasoning||B.variant==="tool"&&Qe.renderToolCall||!B.variant&&Qe.renderMessage)),Xr=(Fn=o.layout)==null?void 0:Fn.messages;if(Xo(B)&&((Nn=B.agentMetadata)==null?void 0:Nn.askUserQuestionAnswered)===!0){qo.delete(B.id);let Qe=l.querySelector(`#wrapper-${B.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime");return}if(as(B)&&((xa=(ha=o.features)==null?void 0:ha.suggestReplies)==null?void 0:xa.enabled)!==!1)return;if(Xo(B)&&((On=($t=o.features)==null?void 0:$t.askUserQuestion)==null?void 0:On.enabled)!==!1){let Qe=n.find(lr=>typeof lr.renderAskUserQuestion=="function");if(Qe&&St.current){let lr=qo.get(B.id),_t=lr!==Dt,Ot=null;if(_t){let{payload:wt,complete:vr}=Jo(B),Er=B.id,Wo=()=>{var ur;return(ur=St.current)==null?void 0:ur.getMessages().find(kr=>kr.id===Er)};Ot=Qe.renderAskUserQuestion({message:B,payload:wt,complete:vr,resolve:ur=>{var Lr;let kr=Wo();kr&&((Lr=St.current)==null||Lr.resolveAskUserQuestion(kr,ur))},dismiss:()=>{var kr,Lr,Un;let ur=Wo();(kr=ur==null?void 0:ur.agentMetadata)!=null&&kr.awaitingLocalTool&&((Lr=St.current)==null||Lr.markAskUserQuestionResolved(ur),(Un=St.current)==null||Un.resolveAskUserQuestion(ur,"(dismissed)"))},config:o})}let ut=lr!=null;if(_t&&Ot===null&&!ut){((gn=B.agentMetadata)==null?void 0:gn.awaitingLocalTool)===!0&&!((hn=B.agentMetadata)!=null&&hn.askUserQuestionAnswered)&&(F.add(B.toolCall.id),Aa(B,o,X.composerOverlay));return}let jt=document.createElement("div");jt.className="persona-flex",jt.id=`wrapper-${B.id}`,jt.setAttribute("data-wrapper-id",B.id),jt.setAttribute("data-ask-plugin-stub","true"),jt.setAttribute("data-preserve-runtime","true"),v.appendChild(jt),re.push({messageId:B.id,fingerprint:Dt,bubble:Ot});return}else{((Go=B.agentMetadata)==null?void 0:Go.awaitingLocalTool)===!0&&!((_n=B.agentMetadata)!=null&&_n.askUserQuestionAnswered)&&(F.add(B.toolCall.id),Aa(B,o,X.composerOverlay));return}}else if(Re){let Qe=n.find(ut=>typeof ut.renderApproval=="function"),_t=fo.get(B.id)!==Dt,Ot=null;if(_t&&(Qe!=null&&Qe.renderApproval)){let ut=B.id,jt=(wt,vr)=>{var Wo,ur,kr;let Er=(Wo=St.current)==null?void 0:Wo.getMessages().find(Lr=>Lr.id===ut);Er!=null&&Er.approval&&(Er.approval.toolType==="webmcp"?(ur=St.current)==null||ur.resolveWebMcpApproval(Er.id,wt):(kr=St.current)==null||kr.resolveApproval(Er.approval,wt,vr))};Ot=Qe.renderApproval({message:B,defaultRenderer:()=>Ki(B,o),config:o,approve:wt=>jt("approved",wt),deny:wt=>jt("denied",wt)})}if(_t&&Ot===null){let ut=l.querySelector(`#wrapper-${B.id}`);ut==null||ut.removeAttribute("data-preserve-runtime"),fo.delete(B.id),bt=Ki(B,o)}else{let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-${B.id}`,ut.setAttribute("data-wrapper-id",B.id),ut.setAttribute("data-approval-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),v.appendChild(ut),Ce.push({messageId:B.id,fingerprint:Dt,bubble:Ot});return}}else if(qt)if(B.variant==="reasoning"&&B.reasoning&&qt.renderReasoning){if(!$e)return;bt=qt.renderReasoning({message:B,defaultRenderer:()=>oc(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&qt.renderToolCall){if(!Me)return;bt=qt.renderToolCall({message:B,defaultRenderer:()=>ac(B,o),config:o})}else qt.renderMessage&&(bt=qt.renderMessage({message:B,defaultRenderer:()=>{let Qe=Ha(B,h,Xr,o.messageActions,se,{loadingIndicatorRenderer:D,widgetConfig:o});return B.role!=="user"&&dc(Qe,B,o,_),Qe},config:o}));if(!bt&&ue){let Qe=rl(B);if(Qe){let lr=Po.get(B.id),_t=lr!==Dt,Ot=o.wrapComponentDirectiveInBubble!==!1,ut=null;if(_t){let jt=el(Qe,{config:o,message:B,transform:h});if(jt)if(Ot){let wt=document.createElement("div");if(wt.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(" "),wt.id=`bubble-${B.id}`,wt.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let vr=document.createElement("div");vr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",vr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),wt.appendChild(vr)}wt.appendChild(jt),ut=wt}else{let wt=document.createElement("div");if(wt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",wt.id=`bubble-${B.id}`,wt.setAttribute("data-message-id",B.id),wt.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let vr=document.createElement("div");vr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",vr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),wt.appendChild(vr)}wt.appendChild(jt),ut=wt}}if(ut||lr!=null){let jt=document.createElement("div");jt.className="persona-flex",jt.id=`wrapper-${B.id}`,jt.setAttribute("data-wrapper-id",B.id),jt.setAttribute("data-component-directive-stub","true"),jt.setAttribute("data-preserve-runtime","true"),Ot||jt.classList.add("persona-w-full"),v.appendChild(jt),J.push({messageId:B.id,fingerprint:Dt,bubble:ut});return}}}if(!bt)if(B.variant==="reasoning"&&B.reasoning){if(!$e)return;bt=oc(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!Me)return;bt=ac(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;bt=Ki(B,o)}else{let Qe=(ho=o.layout)==null?void 0:ho.messages;Qe!=null&&Qe.renderUserMessage&&B.role==="user"?bt=Qe.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):Qe!=null&&Qe.renderAssistantMessage&&B.role==="assistant"?bt=Qe.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):bt=Ha(B,h,Qe,o.messageActions,se,{loadingIndicatorRenderer:D,widgetConfig:o}),B.role!=="user"&&bt&&dc(bt,B,o,_)}let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),B.role==="user"&&Qt.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&Qt.classList.add("persona-w-full"),Qt.appendChild(bt),ah(Lo,B.id,Dt,Qt),v.appendChild(Qt)}),X.composerOverlay&&X.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(He=>{let Re=He.getAttribute("data-persona-ask-sheet-for");Re&&!F.has(Re)&&vn(X.composerOverlay,Re)}),(Pe=(nt=o.features)==null?void 0:nt.toolCallDisplay)!=null&&Pe.grouped){let B=[],He=[];f.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&Me){He.push(Re);return}He.length>1&&B.push(He),He=[]}),He.length>1&&B.push(He),B.forEach((Re,ue)=>{var Xe,Et;let Nt=Re.map(or=>Array.from(v.children).find(lo=>lo instanceof HTMLElement&&lo.getAttribute("data-wrapper-id")===or.id)).filter(or=>!!or);if(Nt.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${ue}-${Re[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${ue}-${Re[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 bt=document.createElement("div");bt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Re.length} tools`,Xr=(Et=(Xe=o.toolCall)==null?void 0:Xe.renderGroupedSummary)==null?void 0:Et.call(Xe,{messages:Re,toolCalls:Re.map(or=>or.toolCall).filter(or=>!!or),defaultSummary:qt,config:o});$(bt,Xr)||(bt.textContent=qt);let Qt=document.createElement("div");Qt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.append(bt,Qt),Dt.appendChild(zt),Nt[0].before(Dt),Nt.forEach((or,lo)=>{let Jr=document.createElement("div");Jr.className="persona-tool-group-item persona-relative",Jr.setAttribute("data-persona-tool-group-item","true"),lo<Nt.length-1&&Jr.setAttribute("data-persona-tool-group-connector","true"),Jr.appendChild(or),Qt.appendChild(Jr)})})}sh(Lo,O);let rt=f.some(B=>B.role==="assistant"&&B.streaming),_e=f[f.length-1],ct=(_e==null?void 0:_e.role)==="assistant"&&!_e.streaming&&_e.variant!=="approval";if(ko&&f.some(B=>B.role==="user")&&!rt&&!ct){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ra},He=n.find(ue=>ue.renderLoadingIndicator),Re=null;if(He!=null&&He.renderLoadingIndicator&&(Re=He.renderLoadingIndicator(B)),Re===null&&((ke=o.loadingIndicator)!=null&&ke.render)&&(Re=o.loadingIndicator.render(B)),Re===null&&(Re=ra()),Re){let ue=document.createElement("div"),Nt=((Ue=o.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;ue.className=Nt?["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(" "),ue.setAttribute("data-typing-indicator","true"),ue.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ue.appendChild(Re);let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(ue),v.appendChild(Dt)}}if(!ko&&f.length>0){let B=f[f.length-1],He={config:o,lastMessage:B,messageCount:f.length},Re=n.find(Nt=>Nt.renderIdleIndicator),ue=null;if(Re!=null&&Re.renderIdleIndicator&&(ue=Re.renderIdleIndicator(He)),ue===null&&((je=o.loadingIndicator)!=null&&je.renderIdle)&&(ue=o.loadingIndicator.renderIdle(He)),ue){let Nt=document.createElement("div"),Dt=((ht=o.loadingIndicator)==null?void 0:ht.showBubble)!==!1;Nt.className=Dt?["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(" "),Nt.setAttribute("data-idle-indicator","true"),Nt.appendChild(ue);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-idle-indicator",zt.setAttribute("data-wrapper-id","idle-indicator"),zt.appendChild(Nt),v.appendChild(zt)}}if(Li(l,v),re.length>0)for(let{messageId:B,fingerprint:He,bubble:Re}of re){let ue=l.querySelector(`#wrapper-${B}`);ue&&Re!==null&&(ue.replaceChildren(Re),ue.setAttribute("data-bubble-fp",He),qo.set(B,He))}if(qo.size>0)for(let B of qo.keys())O.has(B)||qo.delete(B);if(J.length>0)for(let{messageId:B,fingerprint:He,bubble:Re}of J){let ue=l.querySelector(`#wrapper-${B}`);ue&&Re!==null&&(ue.replaceChildren(Re),ue.setAttribute("data-bubble-fp",He),Po.set(B,He))}if(Po.size>0)for(let B of Po.keys())O.has(B)||Po.delete(B);if(Ce.length>0)for(let{messageId:B,fingerprint:He,bubble:Re}of Ce){let ue=l.querySelector(`#wrapper-${B}`);ue&&Re!==null&&(ue.replaceChildren(Re),ue.setAttribute("data-bubble-fp",He),fo.set(B,He))}if(fo.size>0)for(let B of fo.keys())O.has(B)||fo.delete(B)},Va=(l,f,h)=>{Hx(l,f,h),an()},za=null,Bx=()=>{var h;if(za)return;let l=v=>{let W=v.composedPath();W.includes(Oe)||Ye&&W.includes(Ye)||Ut(!1,"user")};za=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Lc=()=>{var f;if(!za)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",za,!0),za=null};it.push(()=>Lc());let $a=null,Dx=()=>{var h;if($a)return;let l=v=>{v.key==="Escape"&&(v.isComposing||Ut(!1,"user"))};$a=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Pc=()=>{var f;if(!$a)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",$a,!0),$a=null};it.push(()=>Pc());let ja=!1,Rc=new Set,Fx=()=>{var f,h,v,W;let l=(v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:v.streamAnimation;return l||((W=o.features)==null?void 0:W.streamAnimation)},ua=()=>{var ct,nt,Pe,ke;if(!I())return;let l=X.peekBanner,f=X.peekTextNode;if(!l||!f)return;if(k){l.classList.remove("persona-pill-peek--visible");return}let h=(ct=_==null?void 0:_.getMessages())!=null?ct:[],v;for(let Ue=h.length-1;Ue>=0;Ue--){let je=h[Ue];if(je.role==="assistant"&&je.content){v=je;break}}if(!v){l.classList.remove("persona-pill-peek--visible");return}let W=v.content,D=!!v.streaming,$=Fx(),O=Hi($),F=O.type!=="none"?ys(O.type,$==null?void 0:$.plugins):null,te=((nt=F==null?void 0:F.isAnimating)==null?void 0:nt.call(F,v))===!0,re=F!==null&&(D||te);re&&F&&!Rc.has(F.name)&&($p(F,e),Rc.add(F.name));let J=re&&(F!=null&&F.containerClass)?F.containerClass:null,xe=(Pe=f.dataset.personaPeekStreamClass)!=null?Pe:null;xe&&xe!==J&&(f.classList.remove(xe),delete f.dataset.personaPeekStreamClass),J&&xe!==J&&(f.classList.add(J),f.dataset.personaPeekStreamClass=J),re?(f.style.setProperty("--persona-stream-step",`${O.speed}ms`),f.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let De=re?Bi(W,O.buffer,F,v,D):W;if(re&&O.placeholder==="skeleton"&&D&&(!De||!De.trim())){let Ue=document.createElement("div"),je=vs();je.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(je),Li(f,Ue)}else{let Ue=Math.max(0,De.length-100),je=De.length>100?De.slice(-100):De,ht=Ho(je);if(!re||!F){let B=De.length>100?`\u2026${je}`:je;f.textContent!==B&&(f.textContent=B)}else{let B=ht;(F.wrap==="char"||F.wrap==="word")&&(B=bs(ht,F.wrap,`peek-${v.id}`,{skipTags:F.skipTags,startIndex:Ue}));let He=document.createElement("div");if(He.innerHTML=B,F.useCaret&&je.length>0){let Re=Di(),ue=He.querySelectorAll(".persona-stream-char, .persona-stream-word"),Nt=ue[ue.length-1];Nt!=null&&Nt.parentNode?Nt.parentNode.insertBefore(Re,Nt.nextSibling):He.appendChild(Re)}Li(f,He),(ke=F.onAfterRender)==null||ke.call(F,{container:f,bubble:l,messageId:v.id,message:v,speed:O.speed,duration:O.duration})}}let _e=ko||ja;l.classList.toggle("persona-pill-peek--visible",_e)};if(I()){let l=X.peekBanner;if(l){let v=W=>{W.preventDefault(),W.stopPropagation(),Ut(!0,"user")};l.addEventListener("pointerdown",v),it.push(()=>{l.removeEventListener("pointerdown",v)})}let f=()=>{ja||(ja=!0,ua())},h=()=>{ja&&(ja=!1,ua())};fe.addEventListener("pointerenter",f),fe.addEventListener("pointerleave",h),it.push(()=>{fe.removeEventListener("pointerenter",f),fe.removeEventListener("pointerleave",h)}),Ye&&(Ye.addEventListener("pointerenter",f),Ye.addEventListener("pointerleave",h),it.push(()=>{Ye.removeEventListener("pointerenter",f),Ye.removeEventListener("pointerleave",h)}))}let Nx=l=>{var xe,De,Ce,rt,_e,ct,nt,Pe;let f=(De=(xe=o.launcher)==null?void 0:xe.composerBar)!=null?De:{},h=(Ce=f.expandedSize)!=null?Ce:"anchored",v=(rt=f.bottomOffset)!=null?rt:"16px",W=f.collapsedMaxWidth,D=(_e=f.expandedMaxWidth)!=null?_e:"880px",$=(ct=f.expandedTopOffset)!=null?ct:"5vh",O=(nt=f.modalMaxWidth)!=null?nt:"880px",F=(Pe=f.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",te="calc(100vw - 32px)",re="var(--persona-pill-area-height, 80px)",J=Oe.style;if(J.left="",J.right="",J.top="",J.bottom="",J.transform="",J.width="",J.maxWidth="",J.height="",J.maxHeight="",Ye){let ke=Ye.style;ke.bottom=v,ke.width=W!=null?W:""}if(l&&h!=="fullscreen"){if(h==="modal"){J.top="50%",J.left="50%",J.transform="translate(-50%, -50%)",J.bottom="auto",J.right="auto",J.width=O,J.maxWidth=te,J.maxHeight=F,J.height=F;return}J.left="50%",J.transform="translateX(-50%)",J.bottom=`calc(${v} + ${re})`,J.top=$,J.width=D,J.maxWidth=te}},Ga=()=>{var F,te,re,J,xe,De,Ce,rt;if(!P())return;if(I()){let ct=(re=((te=(F=o.launcher)==null?void 0:F.composerBar)!=null?te:{}).expandedSize)!=null?re:"anchored",nt=k?"expanded":"collapsed";Oe.dataset.state=nt,Oe.dataset.expandedSize=ct,Ye&&(Ye.dataset.state=nt,Ye.dataset.expandedSize=ct),Oe.style.removeProperty("display"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Nx(k),ie.style.display=k?"flex":"none",ge(),k?(Bx(),Dx()):(Lc(),Pc()),ua();return}let l=nr(o),f=(J=e.ownerDocument.defaultView)!=null?J:window,h=(De=(xe=o.launcher)==null?void 0:xe.mobileBreakpoint)!=null?De:640,v=(rt=(Ce=o.launcher)==null?void 0:Ce.mobileFullscreen)!=null?rt:!0,W=f.innerWidth<=h,D=v&&W&&M,$=Zr(o).reveal;k?(Oe.style.removeProperty("display"),Oe.style.display=l?"flex":"",Oe.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"),Jt?Jt.element.style.display="none":ir&&(ir.style.display="none")):(l?l&&($==="overlay"||$==="push")&&!D?(Oe.style.removeProperty("display"),Oe.style.display="flex",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.setProperty("display","none","important"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.display="",Oe.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")),Jt?Jt.element.style.display=l?"none":"":ir&&(ir.style.display=l?"none":""))},Ut=(l,f="user")=>{var D,$;if(!P()||k===l)return;let h=k;k=l,Ga();let v=(()=>{var Ce,rt,_e,ct,nt,Pe,ke,Ue,je,ht;let O=(rt=(Ce=o.launcher)==null?void 0:Ce.sidebarMode)!=null?rt:!1,F=(_e=e.ownerDocument.defaultView)!=null?_e:window,te=(nt=(ct=o.launcher)==null?void 0:ct.mobileFullscreen)!=null?nt:!0,re=(ke=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?ke:640,J=F.innerWidth<=re,xe=nr(o)&&te&&J,De=I()&&((ht=(je=(Ue=o.launcher)==null?void 0:Ue.composerBar)==null?void 0:je.expandedSize)!=null?ht:"fullscreen")==="fullscreen";return O||te&&J&&M||xe||De})();if(k&&v){if(!Xt){let O=e.getRootNode(),F=O instanceof ShadowRoot?O.host:e.closest(".persona-host");F&&(Xt=jp(F,($=(D=o.launcher)==null?void 0:D.zIndex)!=null?$:Sr))}sr||(sr=Gp(e.ownerDocument))}else k||(Xt==null||Xt(),Xt=null,sr==null||sr(),sr=null);k&&(Ka(),et()==="follow"?Dr(!0):un());let W={open:k,source:f,timestamp:Date.now()};k&&!h?a.emit("widget:opened",W):!k&&h&&a.emit("widget:closed",W),a.emit("widget:state",{open:k,launcherEnabled:M,voiceActive:ft.active,streaming:_.isStreaming()})},dl=l=>{It(l?"stop":"send"),z&&(z.disabled=l),Wn.buttons.forEach(f=>{f.disabled=l}),Le.dataset.personaComposerStreaming=l?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},pl=()=>{ft.active||we&&we.focus()};a.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>pl(),200)});let Ic=()=>{var h,v,W,D,$,O,F,te,re,J,xe;Co.textContent=(v=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?v:"Hello \u{1F44B}",yr.textContent=(D=(W=o.copy)==null?void 0:W.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",we.placeholder=(O=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?O:"How can I help...";let l=ve.querySelector("[data-persona-intro-card]");if(l){let De=((F=o.copy)==null?void 0:F.showWelcomeCard)!==!1;l.style.display=De?"":"none",De?(ve.classList.remove("persona-gap-3"),ve.classList.add("persona-gap-6")):(ve.classList.remove("persona-gap-6"),ve.classList.add("persona-gap-3"))}!((re=(te=o.sendButton)==null?void 0:te.useIcon)!=null&&re)&&!(_!=null&&_.isStreaming())&&(ce.textContent=(xe=(J=o.copy)==null?void 0:J.sendButtonLabel)!=null?xe:"Send"),we.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',we.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=p.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{m(f=>({...f,sessionId:l}))}});let Dn=null,Ox=()=>{Dn==null&&(Dn=setInterval(()=>{let l=Ve.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Dn),Dn=null;return}let f=Date.now();l.forEach(h=>{let v=Number(h.getAttribute("data-tool-elapsed"));v&&(h.textContent=ti(f-v))})},100))};_=new ka(o,{onMessagesChanged(l){var v;Va(Ve,l,he),Ox(),sa(l),Dr(!ko),Wx(l);let f=[...l].reverse().find(W=>W.role==="user");l.length===0&&gr(),!la||Bn?(la=!0,da=(v=f==null?void 0:f.id)!=null?v:null):f&&f.id!==da&&(da=f.id,Ix(f.id));let h=ft.lastUserMessageId;f&&f.id!==h&&(ft.lastUserMessageId=f.id,a.emit("user:message",f)),ft.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),cn(l),ua()},onStatusChanged(l){var v;let f=(v=o.statusIndicator)!=null?v:{};Lt(ar,(W=>{var D,$,O,F;return W==="idle"?(D=f.idleText)!=null?D:wr.idle:W==="connecting"?($=f.connectingText)!=null?$:wr.connecting:W==="connected"?(O=f.connectedText)!=null?O:wr.connected:W==="error"?(F=f.errorText)!=null?F:wr.error:wr[W]})(l),f,l)},onStreamingChanged(l){ko=l,dl(l),_&&Va(Ve,_.getMessages(),he),l||Dr(!0),ua()},onVoiceStatusChanged(l){var f,h;if(a.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":jo(),ma();break;case"processing":jo(),zx();break;case"speaking":jo(),$x();break;default:l==="idle"&&_.isBargeInActive()?(jo(),ma(),z==null||z.setAttribute("aria-label","End voice session")):(ft.active=!1,jo(),ao("system"),Br());break}},onArtifactsState(l){Ur=l,zr(),cn()}}),St.current=_;let cl=null;if(_.onReadAloudChange((l,f)=>{var W;on=l,nn=f,an();let h=l!=null?l:cl;l&&(cl=l);let v=h&&(W=_.getMessages().find(D=>D.id===h))!=null?W:null;a.emit("message:read-aloud",{messageId:h,message:v,state:f,timestamp:Date.now()}),f==="idle"&&(cl=null)}),la=!0,((Vu=(qu=o.voiceRecognition)==null?void 0:qu.provider)==null?void 0:Vu.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&_.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(ye||o.onSSEEvent)&&_.setSSEEventCallback((l,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,l,f),ne==null||ne.processEvent(l,f),ye==null||ye.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(f)})}),d&&d.then(l=>{var f,h,v;if(l){if(l.metadata&&(p=uc(l.metadata),R.syncFromMetadata()),(f=l.messages)!=null&&f.length){Bn=!0;try{_.hydrateMessages(l.messages)}finally{Bn=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(v=l.selectedArtifactId)!=null?v:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Wc=()=>{var f,h,v;!I()||k||!((v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||v)||Ut(!0,"auto")},Hc=l=>{var W;if(l.preventDefault(),_.isStreaming()){_.cancel(),ne==null||ne.reset(),K==null||K.update();return}let f=we.value.trim(),h=(W=yt==null?void 0:yt.hasAttachments())!=null?W:!1;if(!f&&!h)return;Wc();let v;h&&(v=[],v.push(...yt.getContentParts()),f&&v.push(ps(f))),we.value="",we.style.height="auto",Fs(),_.sendMessage(f,{contentParts:v}),h&&yt.clearAttachments()},_x=()=>{var l;return((l=o.features)==null?void 0:l.composerHistory)!==!1},ul={...Pi},fl=!1,Fs=()=>{ul={...Pi}},Ux=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var f;return(f=l.content)!=null?f:""}).filter(l=>l.length>0),qx=l=>{if(!we)return;fl=!0,we.value=l,we.dispatchEvent(new Event("input",{bubbles:!0})),fl=!1;let f=we.value.length;we.setSelectionRange(f,f)},Bc=()=>{fl||Fs()},Dc=l=>{if(we){if(_x()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=we.selectionStart===0&&we.selectionEnd===0,h=th({direction:l.key==="ArrowUp"?"up":"down",history:Ux(),currentValue:we.value,atStart:f,state:ul});if(ul=h.state,h.handled){l.preventDefault(),h.value!==void 0&&qx(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Fs(),l.preventDefault(),ce.click()}}},Fc=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(ie)&&(_.cancel(),ne==null||ne.reset(),K==null||K.update(),Fs(),l.preventDefault(),l.stopImmediatePropagation())},Nc=async l=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!yt)return;let f=Iv(l.clipboardData);f.length!==0&&(l.preventDefault(),await yt.handleFiles(f))},so=null,Io=!1,fa=null,pt=null,Oc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ns=(l="user")=>{var D,$,O,F,te,re,J;if(Io||_.isStreaming())return;let f=Oc();if(!f)return;so=new f;let v=($=((D=o.voiceRecognition)!=null?D:{}).pauseDuration)!=null?$:2e3;so.continuous=!0,so.interimResults=!0,so.lang="en-US";let W=we.value;so.onresult=xe=>{let De="",Ce="";for(let _e=0;_e<xe.results.length;_e++){let ct=xe.results[_e],nt=ct[0].transcript;ct.isFinal?De+=nt+" ":Ce=nt}let rt=W+De+Ce;we.value=rt,fa&&clearTimeout(fa),(De||Ce)&&(fa=window.setTimeout(()=>{let _e=we.value.trim();_e&&so&&Io&&(fn(),we.value="",we.style.height="auto",_.sendMessage(_e,{viaVoice:!0}))},v))},so.onerror=xe=>{xe.error!=="no-speech"&&fn()},so.onend=()=>{if(Io){let xe=we.value.trim();xe&&xe!==W.trim()&&(we.value="",we.style.height="auto",_.sendMessage(xe,{viaVoice:!0})),fn()}};try{if(so.start(),Io=!0,ft.active=!0,l!=="system"&&(ft.manuallyDeactivated=!1),ao(l),Br(),z){let xe=(O=o.voiceRecognition)!=null?O:{};pt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(F=xe.iconName)!=null?F:"mic",iconSize:parseFloat((J=(re=xe.iconSize)!=null?re:(te=o.sendButton)==null?void 0:te.size)!=null?J:"40")||24};let De=xe.recordingBackgroundColor,Ce=xe.recordingIconColor,rt=xe.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=De!=null?De:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=Ce!=null?Ce:"var(--persona-voice-recording-indicator, #ffffff)",Ce){let _e=z.querySelector("svg");_e&&_e.setAttribute("stroke",Ce)}rt&&(z.style.borderColor=rt),z.setAttribute("aria-label","Stop voice recognition")}}catch{fn("system")}},fn=(l="user")=>{if(Io){if(Io=!1,fa&&(clearTimeout(fa),fa=null),so){try{so.stop()}catch{}so=null}if(ft.active=!1,ao(l),Br(),z){if(z.classList.remove("persona-voice-recording"),pt){z.style.backgroundColor=pt.backgroundColor,z.style.color=pt.color,z.style.borderColor=pt.borderColor;let f=z.querySelector("svg");f&&f.setAttribute("stroke",pt.color||"currentColor"),pt=null}z.setAttribute("aria-label","Start voice recognition")}}},Vx=(l,f)=>{var nt,Pe,ke,Ue,je,ht,B,He,Re;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),v=((nt=l==null?void 0:l.provider)==null?void 0:nt.type)==="runtype",W=((Pe=l==null?void 0:l.provider)==null?void 0:Pe.type)==="custom";if(!(h||v||W))return null;let $=S("div","persona-send-button-wrapper"),O=S("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 F=(ke=l==null?void 0:l.iconName)!=null?ke:"mic",te=(Ue=f==null?void 0:f.size)!=null?Ue:"40px",re=(je=l==null?void 0:l.iconSize)!=null?je:te,J=parseFloat(re)||24,xe=(ht=l==null?void 0:l.backgroundColor)!=null?ht:f==null?void 0:f.backgroundColor,De=(B=l==null?void 0:l.iconColor)!=null?B:f==null?void 0:f.textColor;O.style.width=re,O.style.height=re,O.style.minWidth=re,O.style.minHeight=re,O.style.fontSize="18px",O.style.lineHeight="1",De?O.style.color=De:O.style.color="var(--persona-text, #111827)";let rt=be(F,J,De||"currentColor",1.5);rt?O.appendChild(rt):O.textContent="\u{1F3A4}",xe?O.style.backgroundColor=xe:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),$.appendChild(O);let _e=(He=l==null?void 0:l.tooltipText)!=null?He:"Start voice recognition";if(((Re=l==null?void 0:l.showTooltip)!=null?Re:!1)&&_e){let ue=S("div","persona-send-button-tooltip");ue.textContent=_e,$.appendChild(ue)}return{micButton:O,micButtonWrapper:$}},ml=()=>{var f,h,v,W,D;if(!z||pt)return;let l=(f=o.voiceRecognition)!=null?f:{};pt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((D=(W=l.iconSize)!=null?W:(v=o.sendButton)==null?void 0:v.size)!=null?D:"40")||24}},gl=(l,f)=>{var D,$,O,F,te;if(!z)return;let h=z.querySelector("svg");h&&h.remove();let v=(te=pt==null?void 0:pt.iconSize)!=null?te:parseFloat((F=(O=(D=o.voiceRecognition)==null?void 0:D.iconSize)!=null?O:($=o.sendButton)==null?void 0:$.size)!=null?F:"40")||24,W=be(l,v,f,1.5);W&&z.appendChild(W)},Os=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ma=()=>{var W;if(!z)return;ml();let l=(W=o.voiceRecognition)!=null?W:{},f=l.recordingBackgroundColor,h=l.recordingIconColor,v=l.recordingBorderColor;if(Os(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let D=z.querySelector("svg");D&&D.setAttribute("stroke",h)}v&&(z.style.borderColor=v),z.setAttribute("aria-label","Stop voice recognition")},zx=()=>{var O,F,te,re,J,xe,De,Ce;if(!z)return;ml();let l=(O=o.voiceRecognition)!=null?O:{},f=_.getVoiceInterruptionMode(),h=(F=l.processingIconName)!=null?F:"loader",v=(re=(te=l.processingIconColor)!=null?te:pt==null?void 0:pt.color)!=null?re:"",W=(xe=(J=l.processingBackgroundColor)!=null?J:pt==null?void 0:pt.backgroundColor)!=null?xe:"",D=(Ce=(De=l.processingBorderColor)!=null?De:pt==null?void 0:pt.borderColor)!=null?Ce:"";Os(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=W,z.style.borderColor=D;let $=v||"currentColor";z.style.color=$,gl(h,$),z.setAttribute("aria-label","Processing voice input"),f==="none"&&(z.style.cursor="default")},$x=()=>{var te,re,J,xe,De,Ce,rt,_e,ct,nt,Pe,ke;if(!z)return;ml();let l=(te=o.voiceRecognition)!=null?te:{},f=_.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",v=(re=l.speakingIconName)!=null?re:h,W=(Ce=l.speakingIconColor)!=null?Ce:f==="barge-in"?(xe=(J=l.recordingIconColor)!=null?J:pt==null?void 0:pt.color)!=null?xe:"":(De=pt==null?void 0:pt.color)!=null?De:"",D=(ct=l.speakingBackgroundColor)!=null?ct:f==="barge-in"?(rt=l.recordingBackgroundColor)!=null?rt:"var(--persona-voice-recording-bg, #ef4444)":(_e=pt==null?void 0:pt.backgroundColor)!=null?_e:"",$=(ke=l.speakingBorderColor)!=null?ke:f==="barge-in"?(nt=l.recordingBorderColor)!=null?nt:"":(Pe=pt==null?void 0:pt.borderColor)!=null?Pe:"";Os(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=D,z.style.borderColor=$;let O=W||"currentColor";z.style.color=O,gl(v,O);let F=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",F),f==="none"&&(z.style.cursor="default"),f==="barge-in"&&z.classList.add("persona-voice-recording")},jo=()=>{var l,f,h;z&&(Os(),pt&&(z.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",z.style.color=(f=pt.color)!=null?f:"",z.style.borderColor=(h=pt.borderColor)!=null?h:"",gl(pt.iconName,pt.color||"currentColor"),pt=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},_s=()=>{var l,f;if(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"){let h=_.getVoiceStatus(),v=_.getVoiceInterruptionMode();if(v==="none"&&(h==="processing"||h==="speaking"))return;if(v==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{ft.active=!1,ft.manuallyDeactivated=!0,Br(),ao("user"),jo()});return}_.toggleVoice().then(()=>{ft.active=_.isVoiceActive(),ft.manuallyDeactivated=!_.isVoiceActive(),Br(),ao("user"),_.isVoiceActive()?ma():jo()});return}if(Io){let h=we.value.trim();ft.manuallyDeactivated=!0,Br(),fn("user"),h&&(we.value="",we.style.height="auto",_.sendMessage(h))}else ft.manuallyDeactivated=!1,Br(),Ns("user")};Or=_s,z&&(z.addEventListener("click",_s),it.push(()=>{var l,f;((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),jo()):fn("system"),z&&z.removeEventListener("click",_s)}));let jx=a.on("assistant:complete",()=>{qa&&(ft.active||ft.manuallyDeactivated||qa==="assistant"&&!ft.lastUserMessageWasVoice||setTimeout(()=>{var l,f;!ft.active&&!ft.manuallyDeactivated&&(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?_.toggleVoice().then(()=>{ft.active=_.isVoiceActive(),ao("auto"),_.isVoiceActive()&&ma()}):Ns("auto"))},600))});it.push(jx);let Gx=a.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});it.push(Gx);let _c=()=>{Ut(!k,"user")},Jt=null,ir=null;if(M&&!I()){let{instance:l,element:f}=Yp({config:o,plugins:n,onToggle:_c});Jt=l,l||(ir=f)}Jt?e.appendChild(Jt.element):ir&&e.appendChild(ir),Ga(),sa(),Ic(),dl(_.isStreaming()),et()==="follow"?Dr(!0):un(),Bs(),L&&(!M||I()?setTimeout(()=>pl(),0):k&&setTimeout(()=>pl(),200));let Ka=()=>{var F,te,re,J,xe,De,Ce,rt,_e,ct,nt,Pe,ke,Ue,je,ht,B,He,Re,ue,Nt,Dt;if(I()){Wr(),Ga();return}let l=nr(o),f=(te=(F=o.launcher)==null?void 0:F.sidebarMode)!=null?te:!1,h=l||f||((J=(re=o.launcher)==null?void 0:re.fullHeight)!=null?J:!1),v=(xe=e.ownerDocument.defaultView)!=null?xe:window,W=(Ce=(De=o.launcher)==null?void 0:De.mobileFullscreen)!=null?Ce:!0,D=(_e=(rt=o.launcher)==null?void 0:rt.mobileBreakpoint)!=null?_e:640,$=v.innerWidth<=D,O=W&&$&&M;try{if(O){ge(),An(e,o);return}if(T&&(T=!1,ge(),An(e,o)),!M&&!l){fe.style.height="",fe.style.width="";return}if(!f&&!l){let zt=(nt=(ct=o==null?void 0:o.launcher)==null?void 0:ct.width)!=null?nt:o==null?void 0:o.launcherWidth,bt=zt!=null?zt:Yr;fe.style.width=bt,fe.style.maxWidth=bt}if(Mo(),!h){let zt=v.innerHeight,bt=64,qt=(ke=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?ke:0,Xr=Math.max(200,zt-bt),Qt=Math.min(640,Xr),Xe=Math.max(200,Qt-qt);fe.style.height=`${Xe}px`}}finally{if(Wr(),Ga(),k&&M){let bt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((ht=(je=o.launcher)==null?void 0:je.mobileBreakpoint)!=null?ht:640),qt=(He=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?He:!1,Xr=(ue=(Re=o.launcher)==null?void 0:Re.mobileFullscreen)!=null?ue:!0,Qt=nr(o)&&Xr&&bt,Xe=qt||Xr&&bt&&M||Qt;if(Xe&&!sr){let Et=e.getRootNode(),or=Et instanceof ShadowRoot?Et.host:e.closest(".persona-host");or&&!Xt&&(Xt=jp(or,(Dt=(Nt=o.launcher)==null?void 0:Nt.zIndex)!=null?Dt:Sr)),sr=Gp(e.ownerDocument)}else Xe||(Xt==null||Xt(),Xt=null,sr==null||sr(),sr=null)}}};Ka();let Uc=(zu=e.ownerDocument.defaultView)!=null?zu:window;if(Uc.addEventListener("resize",Ka),it.push(()=>Uc.removeEventListener("resize",Ka)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Wr()});l.observe(Le),it.push(()=>l.disconnect())}jr=ve.scrollTop;let qc=Zo(ve),Kx=()=>{let l=ve.getRootNode(),f=typeof l.getSelection=="function"?l.getSelection():null;return f!=null?f:ve.ownerDocument.getSelection()},hl=()=>ih(Kx(),ve),Vc=()=>{let l=ve.scrollTop,f=Zo(ve),h=f<qc;if(qc=f,et()!=="follow"){jr=l,Je();return}let{action:v,nextLastScrollTop:W}=Ii({following:$r.isFollowing(),currentScrollTop:l,lastScrollTop:jr,nearBottom:Zn(ve,pa),userScrollThreshold:Ws,isAutoScrolling:go||Hn||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(jr=W,v==="resume"){hl()||zo();return}v==="pause"&&Tt()};if(ve.addEventListener("scroll",Vc,{passive:!0}),it.push(()=>ve.removeEventListener("scroll",Vc)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Kr()});l.observe(Ve),l.observe(ve),it.push(()=>l.disconnect())}let zc=()=>{et()==="follow"&&$r.isFollowing()&&hl()&&Tt()},$c=ve.ownerDocument;$c.addEventListener("selectionchange",zc),it.push(()=>{$c.removeEventListener("selectionchange",zc)});let jc=l=>{if(et()!=="follow")return;let f=Wi({following:$r.isFollowing(),deltaY:l.deltaY,nearBottom:Zn(ve,pa),resumeWhenNearBottom:!0});f==="pause"?Tt():f==="resume"&&!hl()&&zo()};ve.addEventListener("wheel",jc,{passive:!0}),it.push(()=>ve.removeEventListener("wheel",jc)),st.addEventListener("click",()=>{gr(),ve.scrollTop=ve.scrollHeight,jr=ve.scrollTop,zo(),Dr(!0),Je()}),it.push(()=>st.remove()),it.push(()=>{q(),gr()});let Gc=()=>{ze&&(Eo&&(ze.removeEventListener("click",Eo),Eo=null),P()?(ze.style.display="",Eo=()=>{Ut(!1,"user")},ze.addEventListener("click",Eo)):ze.style.display="none")};Gc(),(()=>{let{clearChatButton:l}=X;l&&l.addEventListener("click",()=>{_.clearMessages(),Lo.clear(),zo(),vn(X.composerOverlay);try{localStorage.removeItem(Oa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Oa}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Oa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(v=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",v)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},R.syncFromMetadata(),ye==null||ye.clear(),ne==null||ne.reset(),K==null||K.update()})})(),Rt&&Rt.addEventListener("submit",Hc),we==null||we.addEventListener("keydown",Dc),we==null||we.addEventListener("input",Bc),we==null||we.addEventListener("paste",Nc);let Kc=($u=e.ownerDocument)!=null?$u:document;Kc.addEventListener("keydown",Fc,!0);let Xc="persona-attachment-drop-active",Xa=0,xl=()=>{Xa=0,ie.classList.remove(Xc)},ga=()=>{var l;return((l=o.attachments)==null?void 0:l.enabled)===!0&&yt!==null},Jc=l=>{!al(l.dataTransfer)||!ga()||(Xa++,Xa===1&&ie.classList.add(Xc))},Qc=l=>{!al(l.dataTransfer)||!ga()||(Xa--,Xa<=0&&xl())},Yc=l=>{!al(l.dataTransfer)||!ga()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Zc=l=>{var h;if(!al(l.dataTransfer)||!ga())return;l.preventDefault(),l.stopPropagation(),xl();let f=Array.from((h=l.dataTransfer.files)!=null?h:[]);f.length!==0&&yt.handleFiles(f)},mn=!0;ie.addEventListener("dragenter",Jc,mn),ie.addEventListener("dragleave",Qc,mn),e.addEventListener("dragover",Yc,mn),e.addEventListener("drop",Zc,mn);let Us=e.ownerDocument,eu=l=>{ga()&&l.preventDefault()},tu=l=>{ga()&&l.preventDefault()};Us.addEventListener("dragover",eu),Us.addEventListener("drop",tu),it.push(()=>{Rt&&Rt.removeEventListener("submit",Hc),we==null||we.removeEventListener("keydown",Dc),we==null||we.removeEventListener("input",Bc),we==null||we.removeEventListener("paste",Nc),Kc.removeEventListener("keydown",Fc,!0)}),it.push(()=>{ie.removeEventListener("dragenter",Jc,mn),ie.removeEventListener("dragleave",Qc,mn),e.removeEventListener("dragover",Yc,mn),e.removeEventListener("drop",Zc,mn),Us.removeEventListener("dragover",eu),Us.removeEventListener("drop",tu),xl()}),it.push(()=>{_.cancel()}),Jt?it.push(()=>{Jt==null||Jt.destroy()}):ir&&it.push(()=>{ir==null||ir.remove()});let rr={update(l){var vr,Er,Wo,ur,kr,Lr,Un,Ja,Yu,Zu,ef,tf,rf,of,nf,af,sf,lf,df,pf,cf,uf,ff,mf,gf,hf,xf,yf,bf,vf,Cf,wf,Sf,Af,Mf,Tf,Ef,kf,Lf,Pf,Rf,If,Wf,Hf,Bf,Df,Ff,Nf,Of,_f,Uf,qf,Vf,zf,$f,jf,Gf,Kf,Xf,Jf,Qf,Yf,Zf,em,tm,rm,om,nm,am,sm,im,lm,dm,pm,cm,um,fm,mm,gm,hm,xm,ym,bm,vm,Cm,wm,Sm,Am,Mm,Tm,Em,km,Lm,Pm,Rm,Im,Wm,Hm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,Vm,zm,$m,jm,Gm,Km,Xm,Jm,Qm;let f=o.toolCall,h=o.messageActions,v=(vr=o.layout)==null?void 0:vr.messages,W=o.colorScheme,D=o.loadingIndicator,$=o.iterationDisplay,O=(Er=o.features)==null?void 0:Er.showReasoning,F=(Wo=o.features)==null?void 0:Wo.showToolCalls,te=(ur=o.features)==null?void 0:ur.toolCallDisplay,re=(kr=o.features)==null?void 0:kr.reasoningDisplay;o={...o,...l},ge(),An(e,o),Ji(e,o),Qi(e,o),zr(),o.colorScheme!==W&&Ua();let J=Es.getForInstance(o.plugins);n.length=0,n.push(...J),M=(Un=(Lr=o.launcher)==null?void 0:Lr.enabled)!=null?Un:!0,A=(Yu=(Ja=o.launcher)==null?void 0:Ja.autoExpand)!=null?Yu:!1,$e=(ef=(Zu=o.features)==null?void 0:Zu.showReasoning)!=null?ef:!0,Me=(rf=(tf=o.features)==null?void 0:tf.showToolCalls)!=null?rf:!0,qe=(nf=(of=o.features)==null?void 0:of.scrollToBottom)!=null?nf:{};let xe=et();Ee=(sf=(af=o.features)==null?void 0:af.scrollBehavior)!=null?sf:{},xe!==et()&&(gr(),zo()),wo(),Je();let De=Ie;if(Ie=(df=(lf=o.features)==null?void 0:lf.showEventStreamToggle)!=null?df:!1,Ie&&!De){if(ye||(Q=new Ms(ae),ye=new As(pe,Q),ne=ne!=null?ne:new Ts,Q.open().then(()=>ye==null?void 0:ye.restore()).catch(()=>{}),_.setSSEEventCallback((ee,At)=>{var Vt;(Vt=o.onSSEEvent)==null||Vt.call(o,ee,At),ne==null||ne.processEvent(ee,At),ye.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(At)})})),!gt&&Se){let ee=(cf=(pf=o.features)==null?void 0:pf.eventStream)==null?void 0:cf.classNames,At="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"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");gt=S("button",At),gt.style.width="28px",gt.style.height="28px",gt.style.color=Ir.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let Vt=be("activity","18px","currentColor",1.5);Vt&&gt.appendChild(Vt);let at=X.clearChatButtonWrapper,kt=X.closeButtonWrapper,dr=at||kt;dr&&dr.parentNode===Se?Se.insertBefore(gt,dr):Se.appendChild(gt),gt.addEventListener("click",()=>{oe?uo():Fo()})}}else!Ie&&De&&(uo(),gt&&(gt.remove(),gt=null),ye==null||ye.clear(),Q==null||Q.destroy(),ye=null,Q=null,ne==null||ne.reset(),ne=null);if(((uf=o.launcher)==null?void 0:uf.enabled)===!1&&Jt&&(Jt.destroy(),Jt=null),((ff=o.launcher)==null?void 0:ff.enabled)===!1&&ir&&(ir.remove(),ir=null),((mf=o.launcher)==null?void 0:mf.enabled)!==!1&&!Jt&&!ir){let{instance:ee,element:At}=Yp({config:o,plugins:n,onToggle:_c});Jt=ee,ee||(ir=At),e.appendChild(At)}Jt&&Jt.update(o),de&&((gf=o.launcher)==null?void 0:gf.title)!==void 0&&(de.textContent=o.launcher.title),Te&&((hf=o.launcher)==null?void 0:hf.subtitle)!==void 0&&(Te.textContent=o.launcher.subtitle);let Ce=(xf=o.layout)==null?void 0:xf.header;if((Ce==null?void 0:Ce.layout)!==b&&Se){let ee=Ce?Ia(o,Ce,{showClose:P(),onClose:()=>Ut(!1,"user")}):en({config:o,showClose:P(),onClose:()=>Ut(!1,"user")});mt.replaceHeader(ee),Se=mt.header.element,H=mt.header.iconHolder,de=mt.header.headerTitle,Te=mt.header.headerSubtitle,ze=mt.header.closeButton,b=Ce==null?void 0:Ce.layout}else if(Ce&&(H&&(H.style.display=Ce.showIcon===!1?"none":""),de&&(de.style.display=Ce.showTitle===!1?"none":""),Te&&(Te.style.display=Ce.showSubtitle===!1?"none":""),ze&&(ze.style.display=Ce.showCloseButton===!1?"none":""),X.clearChatButtonWrapper)){let ee=Ce.showClearChat;if(ee!==void 0){X.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:At}=X;At&&!At.classList.contains("persona-absolute")&&(ee?At.classList.remove("persona-ml-auto"):At.classList.add("persona-ml-auto"))}}let _e=((yf=o.layout)==null?void 0:yf.showHeader)!==!1;Se&&(Se.style.display=_e?"":"none");let ct=((bf=o.layout)==null?void 0:bf.showFooter)!==!1;Le&&(Le.style.display=ct?"":"none"),Wr(),Je(),M!==w?M?Ut(A,"auto"):(k=!0,Ga()):A!==y&&Ut(A,"auto"),y=A,w=M,Ka(),Gc();let ke=JSON.stringify(l.toolCall)!==JSON.stringify(f),Ue=JSON.stringify(o.messageActions)!==JSON.stringify(h),je=JSON.stringify((vf=o.layout)==null?void 0:vf.messages)!==JSON.stringify(v),ht=((Cf=o.loadingIndicator)==null?void 0:Cf.render)!==(D==null?void 0:D.render)||((wf=o.loadingIndicator)==null?void 0:wf.renderIdle)!==(D==null?void 0:D.renderIdle)||((Sf=o.loadingIndicator)==null?void 0:Sf.showBubble)!==(D==null?void 0:D.showBubble),B=o.iterationDisplay!==$,He=((Mf=(Af=o.features)==null?void 0:Af.showReasoning)!=null?Mf:!0)!==(O!=null?O:!0)||((Ef=(Tf=o.features)==null?void 0:Tf.showToolCalls)!=null?Ef:!0)!==(F!=null?F:!0)||JSON.stringify((kf=o.features)==null?void 0:kf.toolCallDisplay)!==JSON.stringify(te)||JSON.stringify((Lf=o.features)==null?void 0:Lf.reasoningDisplay)!==JSON.stringify(re);(ke||Ue||je||ht||B||He)&&_&&(ia++,Va(Ve,_.getMessages(),he));let ue=(Pf=o.launcher)!=null?Pf:{},Nt=(Rf=ue.headerIconHidden)!=null?Rf:!1,Dt=(Wf=(If=o.layout)==null?void 0:If.header)==null?void 0:Wf.showIcon,zt=Nt||Dt===!1,bt=ue.headerIconName,qt=(Hf=ue.headerIconSize)!=null?Hf:"48px";if(H){let ee=ie.querySelector(".persona-border-b-persona-divider"),At=ee==null?void 0:ee.querySelector(".persona-flex-col");if(zt)H.style.display="none",ee&&At&&!ee.contains(At)&&ee.insertBefore(At,ee.firstChild);else{if(H.style.display="",H.style.height=qt,H.style.width=qt,ee&&At&&(ee.contains(H)?H.nextSibling!==At&&(H.remove(),ee.insertBefore(H,At)):ee.insertBefore(H,At)),bt){let at=parseFloat(qt)||24,kt=be(bt,at*.6,"currentColor",1);kt?H.replaceChildren(kt):H.textContent=(Bf=ue.agentIconText)!=null?Bf:"\u{1F4AC}"}else if(ue.iconUrl){let at=H.querySelector("img");if(at)at.src=ue.iconUrl,at.style.height=qt,at.style.width=qt;else{let kt=document.createElement("img");kt.src=ue.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=qt,kt.style.width=qt,H.replaceChildren(kt)}}else{let at=H.querySelector("svg"),kt=H.querySelector("img");(at||kt)&&H.replaceChildren(),H.textContent=(Df=ue.agentIconText)!=null?Df:"\u{1F4AC}"}let Vt=H.querySelector("img");Vt&&(Vt.style.height=qt,Vt.style.width=qt)}}let Xr=(Nf=(Ff=o.layout)==null?void 0:Ff.header)==null?void 0:Nf.showTitle,Qt=(_f=(Of=o.layout)==null?void 0:Of.header)==null?void 0:_f.showSubtitle;if(de&&(de.style.display=Xr===!1?"none":""),Te&&(Te.style.display=Qt===!1?"none":""),ze){((qf=(Uf=o.layout)==null?void 0:Uf.header)==null?void 0:qf.showCloseButton)===!1?ze.style.display="none":ze.style.display="";let At=(Vf=ue.closeButtonSize)!=null?Vf:"32px",Vt=(zf=ue.closeButtonPlacement)!=null?zf:"inline";ze.style.height=At,ze.style.width=At;let{closeButtonWrapper:at}=X,kt=Vt==="top-right",dr=at==null?void 0:at.classList.contains("persona-absolute");if(at&&kt!==dr)if(at.remove(),kt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ie.style.position="relative",ie.appendChild(at);else{let lt=(jf=($f=ue.clearChat)==null?void 0:$f.placement)!=null?jf:"inline",pr=(Kf=(Gf=ue.clearChat)==null?void 0:Gf.enabled)!=null?Kf:!0;at.className=pr&&lt==="inline"?"":"persona-ml-auto";let Nr=ie.querySelector(".persona-border-b-persona-divider");Nr&&Nr.appendChild(at)}if(ze.style.color=ue.closeButtonColor||Ir.actionIconColor,ue.closeButtonBackgroundColor?(ze.style.backgroundColor=ue.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),ue.closeButtonBorderWidth||ue.closeButtonBorderColor){let lt=ue.closeButtonBorderWidth||"0px",pr=ue.closeButtonBorderColor||"transparent";ze.style.border=`${lt} solid ${pr}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");ue.closeButtonBorderRadius?(ze.style.borderRadius=ue.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),ue.closeButtonPaddingX?(ze.style.paddingLeft=ue.closeButtonPaddingX,ze.style.paddingRight=ue.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),ue.closeButtonPaddingY?(ze.style.paddingTop=ue.closeButtonPaddingY,ze.style.paddingBottom=ue.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let Cr=(Xf=ue.closeButtonIconName)!=null?Xf:"x",xo=(Jf=ue.closeButtonIconText)!=null?Jf:"\xD7";ze.innerHTML="";let Pr=be(Cr,"28px","currentColor",1);Pr?ze.appendChild(Pr):ze.textContent=xo;let Kt=(Qf=ue.closeButtonTooltipText)!=null?Qf:"Close chat",Qr=(Yf=ue.closeButtonShowTooltip)!=null?Yf:!0;if(ze.setAttribute("aria-label",Kt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),Qr&&Kt)){let lt=null,pr=()=>{if(lt||!ze)return;let qn=ze.ownerDocument,Qa=qn.body;if(!Qa)return;lt=Bo(qn,"div","persona-clear-chat-tooltip"),lt.textContent=Kt;let Ya=Bo(qn,"div");Ya.className="persona-clear-chat-tooltip-arrow",lt.appendChild(Ya);let Vn=ze.getBoundingClientRect();lt.style.position="fixed",lt.style.zIndex=String(Mn),lt.style.left=`${Vn.left+Vn.width/2}px`,lt.style.top=`${Vn.top-8}px`,lt.style.transform="translate(-50%, -100%)",Qa.appendChild(lt)},Nr=()=>{lt&&lt.parentNode&&(lt.parentNode.removeChild(lt),lt=null)};at.addEventListener("mouseenter",pr),at.addEventListener("mouseleave",Nr),ze.addEventListener("focus",pr),ze.addEventListener("blur",Nr),at._cleanupTooltip=()=>{Nr(),at&&(at.removeEventListener("mouseenter",pr),at.removeEventListener("mouseleave",Nr)),ze&&(ze.removeEventListener("focus",pr),ze.removeEventListener("blur",Nr))}}}let{clearChatButton:Xe,clearChatButtonWrapper:Et}=X;if(Xe){let ee=(Zf=ue.clearChat)!=null?Zf:{},At=(em=ee.enabled)!=null?em:!0,Vt=(rm=(tm=o.layout)==null?void 0:tm.header)==null?void 0:rm.showClearChat,at=Vt!==void 0?Vt:At,kt=(om=ee.placement)!=null?om:"inline";if(Et){Et.style.display=at?"":"none";let{closeButtonWrapper:dr}=X;!I()&&dr&&!dr.classList.contains("persona-absolute")&&(at?dr.classList.remove("persona-ml-auto"):dr.classList.add("persona-ml-auto"));let Cr=kt==="top-right",xo=Et.classList.contains("persona-absolute");if(!I()&&Cr!==xo&&at){if(Et.remove(),Cr)Et.className="persona-absolute persona-top-4 persona-z-50",Et.style.right="48px",ie.style.position="relative",ie.appendChild(Et);else{Et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Et.style.right="";let Kt=ie.querySelector(".persona-border-b-persona-divider"),Qr=X.closeButtonWrapper;Kt&&Qr&&Qr.parentElement===Kt?Kt.insertBefore(Et,Qr):Kt&&Kt.appendChild(Et)}let Pr=X.closeButtonWrapper;Pr&&!Pr.classList.contains("persona-absolute")&&(Cr?Pr.classList.add("persona-ml-auto"):Pr.classList.remove("persona-ml-auto"))}}if(at){if(!I()){let lt=(nm=ee.size)!=null?nm:"32px";Xe.style.height=lt,Xe.style.width=lt}let dr=(am=ee.iconName)!=null?am:"refresh-cw",Cr=(sm=ee.iconColor)!=null?sm:"";Xe.style.color=Cr||Ir.actionIconColor,Xe.innerHTML="";let xo=I()?"14px":"20px",Pr=be(dr,xo,"currentColor",2);if(Pr&&Xe.appendChild(Pr),ee.backgroundColor?(Xe.style.backgroundColor=ee.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let lt=ee.borderWidth||"0px",pr=ee.borderColor||"transparent";Xe.style.border=`${lt} solid ${pr}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");ee.borderRadius?(Xe.style.borderRadius=ee.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),ee.paddingX?(Xe.style.paddingLeft=ee.paddingX,Xe.style.paddingRight=ee.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),ee.paddingY?(Xe.style.paddingTop=ee.paddingY,Xe.style.paddingBottom=ee.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let Kt=(im=ee.tooltipText)!=null?im:"Clear chat",Qr=(lm=ee.showTooltip)!=null?lm:!0;if(Xe.setAttribute("aria-label",Kt),Et&&(Et._cleanupTooltip&&(Et._cleanupTooltip(),delete Et._cleanupTooltip),Qr&&Kt)){let lt=null,pr=()=>{if(lt||!Xe)return;let qn=Xe.ownerDocument,Qa=qn.body;if(!Qa)return;lt=Bo(qn,"div","persona-clear-chat-tooltip"),lt.textContent=Kt;let Ya=Bo(qn,"div");Ya.className="persona-clear-chat-tooltip-arrow",lt.appendChild(Ya);let Vn=Xe.getBoundingClientRect();lt.style.position="fixed",lt.style.zIndex=String(Mn),lt.style.left=`${Vn.left+Vn.width/2}px`,lt.style.top=`${Vn.top-8}px`,lt.style.transform="translate(-50%, -100%)",Qa.appendChild(lt)},Nr=()=>{lt&&lt.parentNode&&(lt.parentNode.removeChild(lt),lt=null)};Et.addEventListener("mouseenter",pr),Et.addEventListener("mouseleave",Nr),Xe.addEventListener("focus",pr),Xe.addEventListener("blur",Nr),Et._cleanupTooltip=()=>{Nr(),Et&&(Et.removeEventListener("mouseenter",pr),Et.removeEventListener("mouseleave",Nr)),Xe&&(Xe.removeEventListener("focus",pr),Xe.removeEventListener("blur",Nr))}}}}let or=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ks],lo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[na.message,na.messageAndClick];R=Ls({parsers:or,handlers:lo,getSessionMetadata:c,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),he=Kh(o,R,Y),_.updateConfig(o),Va(Ve,_.getMessages(),he),sa(),Ic(),dl(_.isStreaming());let Jr=((dm=o.voiceRecognition)==null?void 0:dm.enabled)===!0,Fn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Nn=((cm=(pm=o.voiceRecognition)==null?void 0:pm.provider)==null?void 0:cm.type)==="runtype";if(Jr&&(Fn||Nn))if(!z||!ot){let ee=Vx(o.voiceRecognition,o.sendButton);ee&&(z=ee.micButton,ot=ee.micButtonWrapper,dt.insertBefore(ot,xr),z.addEventListener("click",_s),z.disabled=_.isStreaming())}else{let ee=(um=o.voiceRecognition)!=null?um:{},At=(fm=o.sendButton)!=null?fm:{},Vt=(mm=ee.iconName)!=null?mm:"mic",at=(gm=At.size)!=null?gm:"40px",kt=(hm=ee.iconSize)!=null?hm:at,dr=parseFloat(kt)||24;z.style.width=kt,z.style.height=kt,z.style.minWidth=kt,z.style.minHeight=kt;let Cr=(ym=(xm=ee.iconColor)!=null?xm:At.textColor)!=null?ym:"currentColor";z.innerHTML="";let xo=be(Vt,dr,Cr,2);xo?z.appendChild(xo):z.textContent="\u{1F3A4}";let Pr=(bm=ee.backgroundColor)!=null?bm:At.backgroundColor;Pr?z.style.backgroundColor=Pr:z.style.backgroundColor="",Cr?z.style.color=Cr:z.style.color="var(--persona-text, #111827)",ee.borderWidth?(z.style.borderWidth=ee.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),ee.borderColor?z.style.borderColor=ee.borderColor:z.style.borderColor="",ee.paddingX?(z.style.paddingLeft=ee.paddingX,z.style.paddingRight=ee.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),ee.paddingY?(z.style.paddingTop=ee.paddingY,z.style.paddingBottom=ee.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let Kt=ot==null?void 0:ot.querySelector(".persona-send-button-tooltip"),Qr=(vm=ee.tooltipText)!=null?vm:"Start voice recognition";if(((Cm=ee.showTooltip)!=null?Cm:!1)&&Qr)if(Kt)Kt.textContent=Qr,Kt.style.display="";else{let pr=document.createElement("div");pr.className="persona-send-button-tooltip",pr.textContent=Qr,ot==null||ot.insertBefore(pr,z)}else Kt&&(Kt.style.display="none");ot.style.display="",z.disabled=_.isStreaming()}else z&&ot&&(ot.style.display="none",((Sm=(wm=o.voiceRecognition)==null?void 0:wm.provider)==null?void 0:Sm.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Io&&fn());if(((Am=o.attachments)==null?void 0:Am.enabled)===!0)if(!le||!j){let ee=(Mm=o.attachments)!=null?Mm:{},Vt=(Em=((Tm=o.sendButton)!=null?Tm:{}).size)!=null?Em:"40px";xt||(xt=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),xt.style.display="none",Rt.insertBefore(xt,we)),Ae||(Ae=document.createElement("input"),Ae.type="file",Ae.accept=((km=ee.allowedTypes)!=null?km:Yo).join(","),Ae.multiple=((Lm=ee.maxFiles)!=null?Lm:4)>1,Ae.style.display="none",Ae.setAttribute("aria-label","Attach files"),Rt.insertBefore(Ae,we)),le=S("div","persona-send-button-wrapper"),j=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),j.type="button",j.setAttribute("aria-label",(Pm=ee.buttonTooltipText)!=null?Pm:"Attach file");let at=(Rm=ee.buttonIconName)!=null?Rm:"paperclip",kt=Vt,dr=parseFloat(kt)||40,Cr=Math.round(dr*.6);j.style.width=kt,j.style.height=kt,j.style.minWidth=kt,j.style.minHeight=kt,j.style.fontSize="18px",j.style.lineHeight="1",j.style.backgroundColor="transparent",j.style.color="var(--persona-primary, #111827)",j.style.border="none",j.style.borderRadius="6px",j.style.transition="background-color 0.15s ease",j.addEventListener("mouseenter",()=>{j.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),j.addEventListener("mouseleave",()=>{j.style.backgroundColor="transparent"});let xo=be(at,Cr,"currentColor",1.5);xo?j.appendChild(xo):j.textContent="\u{1F4CE}",j.addEventListener("click",Qr=>{Qr.preventDefault(),Ae==null||Ae.click()}),le.appendChild(j);let Pr=(Im=ee.buttonTooltipText)!=null?Im:"Attach file",Kt=S("div","persona-send-button-tooltip");Kt.textContent=Pr,le.appendChild(Kt),Ke.append(le),!yt&&Ae&&xt&&(yt=Yn.fromConfig(ee),yt.setPreviewsContainer(xt),Ae.addEventListener("change",async()=>{yt&&(Ae!=null&&Ae.files)&&(await yt.handleFileSelect(Ae.files),Ae.value="")})),ie.querySelector(".persona-attachment-drop-overlay")||ie.appendChild(Xh(ee.dropOverlay))}else{le.style.display="";let ee=(Wm=o.attachments)!=null?Wm:{};Ae&&(Ae.accept=((Hm=ee.allowedTypes)!=null?Hm:Yo).join(","),Ae.multiple=((Bm=ee.maxFiles)!=null?Bm:4)>1),yt&&yt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else le&&(le.style.display="none"),yt&&yt.clearAttachments(),(Dm=ie.querySelector(".persona-attachment-drop-overlay"))==null||Dm.remove();let $t=(Fm=o.sendButton)!=null?Fm:{},On=(Nm=$t.useIcon)!=null?Nm:!1,gn=(Om=$t.iconText)!=null?Om:"\u2191",hn=$t.iconName,Go=(_m=$t.tooltipText)!=null?_m:"Send message",_n=(Um=$t.showTooltip)!=null?Um:!1,ho=(qm=$t.size)!=null?qm:"40px",Qe=$t.backgroundColor,lr=$t.textColor;if(On){if(ce.style.width=ho,ce.style.height=ho,ce.style.minWidth=ho,ce.style.minHeight=ho,ce.style.fontSize="18px",ce.style.lineHeight="1",ce.innerHTML="",lr?ce.style.color=lr:ce.style.color="var(--persona-button-primary-fg, #ffffff)",hn){let ee=parseFloat(ho)||24,At=(lr==null?void 0:lr.trim())||"currentColor",Vt=be(hn,ee,At,2);Vt?ce.appendChild(Vt):ce.textContent=gn}else ce.textContent=gn;ce.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Qe?(ce.style.backgroundColor=Qe,ce.classList.remove("persona-bg-persona-primary")):(ce.style.backgroundColor="",ce.classList.add("persona-bg-persona-primary"))}else ce.textContent=(zm=(Vm=o.copy)==null?void 0:Vm.sendButtonLabel)!=null?zm:"Send",ce.style.width="",ce.style.height="",ce.style.minWidth="",ce.style.minHeight="",ce.style.fontSize="",ce.style.lineHeight="",ce.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",Qe?(ce.style.backgroundColor=Qe,ce.classList.remove("persona-bg-persona-accent")):ce.classList.add("persona-bg-persona-accent"),lr?ce.style.color=lr:ce.classList.add("persona-text-white");$t.borderWidth?(ce.style.borderWidth=$t.borderWidth,ce.style.borderStyle="solid"):(ce.style.borderWidth="",ce.style.borderStyle=""),$t.borderColor?ce.style.borderColor=$t.borderColor:ce.style.borderColor="",$t.paddingX?(ce.style.paddingLeft=$t.paddingX,ce.style.paddingRight=$t.paddingX):(ce.style.paddingLeft="",ce.style.paddingRight=""),$t.paddingY?(ce.style.paddingTop=$t.paddingY,ce.style.paddingBottom=$t.paddingY):(ce.style.paddingTop="",ce.style.paddingBottom="");let _t=xr==null?void 0:xr.querySelector(".persona-send-button-tooltip");if(_n&&Go)if(_t)_t.textContent=Go,_t.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=Go,xr==null||xr.insertBefore(ee,ce)}else _t&&(_t.style.display="none");let Ot=(Xm=($m=o.layout)==null?void 0:$m.contentMaxWidth)!=null?Xm:I()?(Km=(Gm=(jm=o.launcher)==null?void 0:jm.composerBar)==null?void 0:Gm.contentMaxWidth)!=null?Km:"720px":void 0;Ot?(Ve.style.maxWidth=Ot,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%",Rt&&(Rt.style.maxWidth=Ot,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),Pt&&(Pt.style.maxWidth=Ot,Pt.style.marginLeft="auto",Pt.style.marginRight="auto")):(Ve.style.maxWidth="",Ve.style.marginLeft="",Ve.style.marginRight="",Ve.style.width="",Rt&&(Rt.style.maxWidth="",Rt.style.marginLeft="",Rt.style.marginRight=""),Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""));let ut=(Jm=o.statusIndicator)!=null?Jm:{},jt=(Qm=ut.visible)!=null?Qm:!0;if(ar.style.display=jt?"":"none",_){let ee=_.getStatus();Lt(ar,(Vt=>{var at,kt,dr,Cr;return Vt==="idle"?(at=ut.idleText)!=null?at:wr.idle:Vt==="connecting"?(kt=ut.connectingText)!=null?kt:wr.connecting:Vt==="connected"?(dr=ut.connectedText)!=null?dr:wr.connected:Vt==="error"?(Cr=ut.errorText)!=null?Cr:wr.error:wr[Vt]})(ee),ut,ee)}ar.classList.remove("persona-text-left","persona-text-center","persona-text-right");let wt=ut.align==="left"?"persona-text-left":ut.align==="center"?"persona-text-center":"persona-text-right";ar.classList.add(wt)},open(){P()&&Ut(!0,"api")},close(){P()&&Ut(!1,"api")},toggle(){P()&&Ut(!k,"api")},clearChat(){Mr=!1,_.clearMessages(),Lo.clear(),zo();try{localStorage.removeItem(Oa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Oa}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Oa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}p={},R.syncFromMetadata(),ye==null||ye.clear(),ne==null||ne.reset(),K==null||K.update()},setMessage(l){return!we||_.isStreaming()?!1:(!k&&P()&&Ut(!0,"system"),we.value=l,we.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let f=(l==null?void 0:l.trim())||we.value.trim();return f?(!k&&P()&&Ut(!0,"system"),we.value="",we.style.height="auto",_.sendMessage(f),!0):!1},startVoiceRecognition(){var f,h;return _.isStreaming()?!1:((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!k&&P()&&Ut(!0,"system"),ft.manuallyDeactivated=!1,Br(),_.toggleVoice().then(()=>{ft.active=_.isVoiceActive(),ao("user"),_.isVoiceActive()&&ma()})),!0):Io?!0:Oc()?(!k&&P()&&Ut(!0,"system"),ft.manuallyDeactivated=!1,Br(),Ns("user"),!0):!1},stopVoiceRecognition(){var l,f;return((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{ft.active=!1,ft.manuallyDeactivated=!0,Br(),ao("user"),jo()}),!0):!1:Io?(ft.manuallyDeactivated=!0,Br(),fn("user"),!0):!1},injectMessage(l){return!k&&P()&&Ut(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!k&&P()&&Ut(!0,"system");let f=_.injectAssistantMessage(l);return N&&(N=!1,U&&(clearTimeout(U),U=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),f},injectUserMessage(l){return!k&&P()&&Ut(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!k&&P()&&Ut(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!k&&P()&&Ut(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!k&&P()&&Ut(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!k&&P()&&Ut(!0,"system"),_.injectTestEvent(l)},async connectStream(l,f){return _.connectStream(l,f)},__pushEventStreamEvent(l){ye&&(ne==null||ne.processEvent(l.type,l.payload),ye.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Ie||!ye||Fo()},hideEventStream(){oe&&uo()},isEventStreamVisible(){return oe},showArtifacts(){co(o)&&(Mr=!1,zr(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){co(o)&&(Mr=!0,zr())},upsertArtifact(l){return co(o)?(Mr=!1,_.upsertArtifact(l)):null},selectArtifact(l){co(o)&&_.selectArtifact(l)},clearArtifacts(){co(o)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return M&&!k&&!I()||!we?!1:(we.focus(),!0)},async resolveApproval(l,f,h){let W=_.getMessages().find(D=>{var $;return D.variant==="approval"&&(($=D.approval)==null?void 0:$.id)===l});if(!(W!=null&&W.approval))throw new Error(`Approval not found: ${l}`);if(W.approval.toolType==="webmcp"){_.resolveWebMcpApproval(W.id,f);return}return _.resolveApproval(W.approval,f,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(l){m(l)},on(l,f){return a.on(l,f)},off(l,f){a.off(l,f)},isOpen(){return P()&&k},isVoiceActive(){return ft.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:P()&&k,launcherEnabled:M,voiceActive:ft.active,streaming:_.isStreaming()}},showCSATFeedback(l){!k&&P()&&Ut(!0,"system");let f=Ve.querySelector(".persona-feedback-container");f&&f.remove();let h=ol({onSubmit:async(v,W)=>{var D;_.isClientTokenMode()&&await _.submitCSATFeedback(v,W),(D=l==null?void 0:l.onSubmit)==null||D.call(l,v,W)},onDismiss:l==null?void 0:l.onDismiss,...l});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&P()&&Ut(!0,"system");let f=Ve.querySelector(".persona-feedback-container");f&&f.remove();let h=nl({onSubmit:async(v,W)=>{var D;_.isClientTokenMode()&&await _.submitNPSFeedback(v,W),(D=l==null?void 0:l.onSubmit)==null||D.call(l,v,W)},onDismiss:l==null?void 0:l.onDismiss,...l});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,f){return _.submitCSATFeedback(l,f)},async submitNPSFeedback(l,f){return _.submitNPSFeedback(l,f)},destroy(){Dn!=null&&(clearInterval(Dn),Dn=null),it.forEach(l=>l()),Oe.remove(),Ye==null||Ye.remove(),Jt==null||Jt.destroy(),ir==null||ir.remove(),Eo&&ze.removeEventListener("click",Eo)}};if((((ju=r==null?void 0:r.debugTools)!=null?ju:!1)||!!o.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,f={controller:rr,getMessages:rr.getMessages,getStatus:rr.getStatus,getMetadata:rr.getPersistentMetadata,updateMetadata:rr.updatePersistentMetadata,clearHistory:()=>rr.clearChat(),setVoiceActive:h=>h?rr.startVoiceRecognition():rr.stopVoiceRecognition()};window.AgentWidgetBrowser=f,it.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=O=>{let F=O.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&rr.focusInput()};if(window.addEventListener("persona:focusInput",f),it.push(()=>{window.removeEventListener("persona:focusInput",f)}),Ie){let O=te=>{let re=te.detail;(!(re!=null&&re.instanceId)||re.instanceId===l)&&rr.showEventStream()},F=te=>{let re=te.detail;(!(re!=null&&re.instanceId)||re.instanceId===l)&&rr.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",F),it.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",F)})}let h=O=>{let F=O.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&rr.showArtifacts()},v=O=>{let F=O.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&rr.hideArtifacts()},W=O=>{let F=O.detail;F!=null&&F.instanceId&&F.instanceId!==l||F!=null&&F.artifact&&rr.upsertArtifact(F.artifact)},D=O=>{let F=O.detail;F!=null&&F.instanceId&&F.instanceId!==l||typeof(F==null?void 0:F.id)=="string"&&rr.selectArtifact(F.id)},$=O=>{let F=O.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&rr.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",$),it.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",$)})}let io=Wv(o.persistState);if(io&&P()){let l=Hv(io.storage),f=`${io.keyPrefix}widget-open`,h=`${io.keyPrefix}widget-voice`,v=`${io.keyPrefix}widget-voice-mode`;if(l){let W=((Gu=io.persist)==null?void 0:Gu.openState)&&l.getItem(f)==="true",D=((Ku=io.persist)==null?void 0:Ku.voiceState)&&l.getItem(h)==="true",$=((Xu=io.persist)==null?void 0:Xu.voiceState)&&l.getItem(v)==="true";if(W&&setTimeout(()=>{rr.open(),setTimeout(()=>{var O;if(D||$)rr.startVoiceRecognition();else if((O=io.persist)!=null&&O.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(Ju=io.persist)!=null&&Ju.openState&&(a.on("widget:opened",()=>{l.setItem(f,"true")}),a.on("widget:closed",()=>{l.setItem(f,"false")})),(Qu=io.persist)!=null&&Qu.voiceState&&(a.on("voice:state",O=>{l.setItem(h,O.active?"true":"false")}),a.on("user:message",O=>{l.setItem(v,O.viaVoice?"true":"false")})),io.clearOnChatClear){let O=()=>{l.removeItem(f),l.removeItem(h),l.removeItem(v)},F=()=>O();window.addEventListener("persona:clear-chat",F),it.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return u&&P()&&setTimeout(()=>{rr.open()},0),ua(),Is||Vs().then(()=>{_&&(ia++,Lo.clear(),Va(Ve,_.getMessages(),he))}).catch(()=>{}),rr};var Bv=(e,t)=>{let r=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(r);return n?Math.max(0,t*parseFloat(n[1])/100):420},Dv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Fv=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Nv=(e,t)=>{let r=e.parentElement;if(!r)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),!(!n||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Jh=(e,t)=>{var o,n;let r=(n=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?n:!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0"},hc=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=""},Qh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",hc(e)},fc=e=>{e.style.transition=""},mc=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},gc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},il=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ov=(e,t,r,o,n)=>{n?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,o),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(o))},_v=(e,t,r,o,n,a)=>{let s=a?t:e;n==="left"?s.firstElementChild!==o&&s.replaceChildren(o,r):s.lastElementChild!==o&&s.replaceChildren(r,o)},Yh=(e,t,r,o,n,a,s)=>{var x,C,R,M,A,L;let i=Zr(a),p=i.reveal==="push";Ov(e,t,r,o,p),_v(e,t,r,o,i.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"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",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let d=e.ownerDocument.defaultView,u=(C=(x=a==null?void 0:a.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,g=(M=(R=a==null?void 0:a.launcher)==null?void 0:R.mobileBreakpoint)!=null?M:640,c=d!=null?d.innerWidth<=g:!1;if(u&&c&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),mc(t),fc(o),Qh(o),gc(r),il(n,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((L=(A=a==null?void 0:a.launcher)==null?void 0:A.zIndex)!=null?L:Sr),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Qh(o),Dv(o,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",mc(t),fc(o),gc(r),il(n,o);let y=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",b=s?"translateX(0)":w;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=y,o.style.transform=b,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",fc(o),hc(o),il(n,o);let y=Bv(i.width,e.clientWidth),w=Math.max(0,e.clientWidth),b=i.animate?"margin-left 180ms ease":"none",T=i.side==="right"?s?-y:0:s?0:-y;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+y}px`,t.style.transition=b,t.style.marginLeft=`${T}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${w}px`,r.style.maxWidth=`${w}px`,r.style.minWidth=`${w}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",mc(t),hc(o),gc(r),il(n,o);let y=i.reveal==="emerge";y?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let w=s?i.width:"0px",b=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",T=!s;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${w}`,o.style.width=w,o.style.maxWidth=w,o.style.minWidth=w,o.style.minHeight="0",Fv(o,i.maxHeight),o.style.overflow=y||T?"hidden":"visible",o.style.transition=b,y&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.boxSizing="border-box")}},Uv=(e,t)=>{let r=e.ownerDocument.createElement("div");return Jh(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){Jh(r,o)},destroy(){r.remove()}}},qv=(e,t)=>{var L,y,w,b;let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),p=r.createElement("div"),d=r.createElement("aside"),u=r.createElement("div"),g=(y=(L=t==null?void 0:t.launcher)==null?void 0:L.enabled)==null||y?(b=(w=t==null?void 0:t.launcher)==null?void 0:w.autoExpand)!=null?b:!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",d.appendChild(u),o.insertBefore(s,e),p.appendChild(e);let c=null,m=()=>{c==null||c.disconnect(),c=null},x=()=>{m(),Zr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(c=new ResizeObserver(()=>{Yh(s,i,p,d,u,t,g)}),c.observe(s))},C=!1,R=()=>{Yh(s,i,p,d,u,t,g),x(),g&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,Nv(s,Zr(t)))},M=s.ownerDocument.defaultView,A=()=>{R()};return M==null||M.addEventListener("resize",A),Zr(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),s.appendChild(i)):(s.appendChild(p),s.appendChild(d)),R(),{mode:"docked",host:u,shell:s,syncWidgetState(T){let I=T.launcherEnabled?T.open:!0;g!==I&&(g=I,R())},updateConfig(T){var I,P;t=T,((P=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)!=null?P:!0)===!1&&(g=!0),R()},destroy(){M==null||M.removeEventListener("resize",A),m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Ps=(e,t)=>nr(t)?qv(e,t):Uv(e,t);var xc={},Vv=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},zv=()=>{try{if(typeof xc!="undefined"&&xc.url)return new URL("../widget.css",xc.url).href}catch{}return null},Zh=(e,t)=>{let r=zv(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let a=n.cloneNode(!0);e.insertBefore(a,e.firstChild)};if(e instanceof ShadowRoot)if(r){let n=t.createElement("link");n.rel="stylesheet",n.href=r,n.setAttribute("data-persona","true"),e.insertBefore(n,e.firstChild)}else o();else if(!t.head.querySelector("link[data-persona]")&&r){let a=t.createElement("link");a.rel="stylesheet",a.href=r,a.setAttribute("data-persona","true"),t.head.appendChild(a)}},ex=e=>{var R;let t=Vv(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Ps(t,n),s,i=[],p=(M,A)=>{var b,T;let y=!((T=(b=A==null?void 0:A.launcher)==null?void 0:b.enabled)!=null?T:!0)||nr(A),w=o.createElement("div");if(w.setAttribute("data-persona-root","true"),y&&(w.style.height="100%",w.style.display="flex",w.style.flexDirection="column",w.style.flex="1",w.style.minHeight="0"),r){let I=M.attachShadow({mode:"open"});I.appendChild(w),Zh(I,o)}else M.appendChild(w),Zh(M,o);return t.id&&w.setAttribute("data-persona-instance",t.id),w},d=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(M=>M()),i=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},g=()=>{let M=p(a.host,n);s=sl(M,n,{debugTools:e.debugTools}),u()},c=()=>{i.forEach(M=>M()),i=[],s.destroy()};g(),(R=e.onChatReady)==null||R.call(e);let m=M=>{c(),a.destroy(),a=Ps(t,M),n=M,g()},x={update(M){var T,I,P,k,N,U;let A={...n,...M,launcher:{...(T=n==null?void 0:n.launcher)!=null?T:{},...(I=M==null?void 0:M.launcher)!=null?I:{},dock:{...(k=(P=n==null?void 0:n.launcher)==null?void 0:P.dock)!=null?k:{},...(U=(N=M==null?void 0:M.launcher)==null?void 0:N.dock)!=null?U:{}}}},L=nr(n),y=nr(A),w=En(n),b=En(A);if(L!==y||w!==b){m(A);return}n=A,a.updateConfig(n),s.update(M),d()},destroy(){c(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},C=new Proxy(x,{get(M,A,L){if(A==="host")return a.host;if(A in M)return Reflect.get(M,A,L);let y=s[A];return typeof y=="function"?y.bind(s):y}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=C),C};var ax=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),$v=new Set(["button","a","input","select","textarea","details","summary"]),jv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),yc=/\b(product|card|item|listing|result)\b/i,vc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Gv=3e3,Kv=100;function sx(e){let t=typeof e.className=="string"?e.className:"";if(yc.test(t)||e.id&&yc.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&yc.test(o.value))return!0}return!1}function ix(e){var t;return vc.test(((t=e.textContent)!=null?t:"").trim())}function lx(e){var r;let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=(r=t[o].getAttribute("href"))!=null?r:"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function Xv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function tx(e){let t=e.match(vc);return t?t[0]:null}function rx(e){var o,n,a;let t=(o=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?o:e.querySelector("a[href]");if(t&&((n=t.textContent)!=null&&n.trim())){let s=t.getAttribute("href");return{title:t.textContent.trim(),href:s&&s!=="#"?s:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return(a=r==null?void 0:r.textContent)!=null&&a.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function Jv(e){let t=[],r=o=>{let n=o.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll("button").forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('[role="button"]').forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{var n;r((n=o.value)!=null?n:"")}),t.slice(0,6)}var Qv="commerce-card",Yv="result-card";function ox(e){return!sx(e)||!ix(e)||!lx(e)&&!Xv(e)?0:5200}function nx(e){var o;return!sx(e)||ix(e)||!lx(e)||((o=e.textContent)!=null?o:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Cc=[{id:Qv,scoreElement(e){return ox(e)},shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if(r.interactivity==="static"){let o=r.text.trim();return!!(o.length===0||vc.test(o)&&o.length<32)}return!0},formatSummary(e,t){var p,d,u;if(ox(e)===0)return null;let{title:r,href:o}=rx(e),n=(u=(d=tx(((p=e.textContent)!=null?p:"").trim()))!=null?d:tx(t.text))!=null?u:"",a=Jv(e);return[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
111
- `)}},{id:Yv,scoreElement(e){return nx(e)},formatSummary(e,t){if(nx(e)===0)return null;let{title:r,href:o}=rx(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
112
- `)}}];function Zv(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function e0(e){var u,g,c,m,x,C,R,M,A,L,y,w,b;let t=(u=e.options)!=null?u:{},r=(c=(g=t.maxElements)!=null?g:e.maxElements)!=null?c:80,o=(x=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",n=(R=(C=t.maxTextLength)!=null?C:e.maxTextLength)!=null?R:200,a=(A=(M=t.visibleOnly)!=null?M:e.visibleOnly)!=null?A:!0,s=(L=t.root)!=null?L:e.root,i=(y=t.mode)!=null?y:"structured",p=(w=t.maxCandidates)!=null?w:Math.max(500,r*10),d=(b=e.rules)!=null?b:Cc;return i==="simple"&&e.rules&&e.rules.length>0?(Zv(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:r,maxCandidates:p,excludeSelector:o,maxTextLength:n,visibleOnly:a,root:s,rules:d}}function bc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var t0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function r0(e){let t=e.tagName.toLowerCase(),r=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||r==="textbox"||r==="combobox"||r==="listbox"||r==="spinbutton"?"input":t==="button"||r==="button"||$v.has(t)||r&&jv.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function dx(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 o0(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let u=e.attributes[d];u.name.startsWith("data-")&&(t[u.name]=u.value)}return t}function wc(e){let t=e.tagName.toLowerCase();if(e.id){let n=`#${bc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}}for(let n of t0){let a=e.getAttribute(n);if(a){let s=`${t}[${n}="${bc(a)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let r=Array.from(e.classList).filter(n=>n&&!n.startsWith("persona-")).slice(0,3);if(r.length>0){let n=`${t}.${r.map(s=>bc(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}let a=e.parentElement;if(a){let i=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${n}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let a=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function n0(e){return e==="static"?Kv:Gv}function px(e,t){var n;let r=e.tagName.toLowerCase(),o=((n=e.textContent)!=null?n:"").trim().substring(0,t);return{selector:wc(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:r0(e),attributes:o0(e)}}function a0(e,t,r,o){let n=n0(t.interactivity),a=null;for(let s of r){let i=s.scoreElement(e,t,o);i>0&&(n+=i,s.formatSummary&&!a&&(a=s))}return{score:n,formattingRule:a}}function s0(e,t){var r;for(let o of e)if(t.el!==o.el&&(r=o.formattingRule)!=null&&r.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function i0(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,u=d.tagName.toLowerCase();if(ax.has(u)){i=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!dx(d)){i=s.nextNode();continue}let g=px(d,e.maxTextLength),c=g.text.length>0,m=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(R=>R==="role");if(!c&&!m){i=s.nextNode();continue}if(o.has(g.selector)){i=s.nextNode();continue}o.add(g.selector);let{score:x,formattingRule:C}=a0(d,g,e.rules,r);n.push({el:d,domIndex:a,enriched:g,score:x,formattingRule:C}),a+=1}i=s.nextNode()}n.sort((d,u)=>{let g=d.enriched.interactivity==="static"?1:0,c=u.enriched.interactivity==="static"?1:0;return g!==c?g-c:u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex});let p=[];for(let d of n){if(p.length>=e.maxElements)break;s0(p,d)||p.push(d)}return p.sort((d,u)=>{let g=d.enriched.interactivity==="static"?1:0,c=u.enriched.interactivity==="static"?1:0;return g!==c?g-c:g===1&&u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex}),p.map(d=>{var c;let u;if((c=d.formattingRule)!=null&&c.formatSummary){let m=d.formattingRule.formatSummary(d.el,d.enriched,r);m&&(u=m)}let g={...d.enriched};return u&&(g.formattedSummary=u),g})}function l0(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let p=a,d=p.tagName.toLowerCase();if(ax.has(d)){a=n.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!dx(p)){a=n.nextNode();continue}let u=px(p,e.maxTextLength),g=u.text.length>0,c=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!g&&!c){a=n.nextNode();continue}o.has(u.selector)||(o.add(u.selector),r.push(u))}a=n.nextNode()}let s=[],i=[];for(let p of r)p.interactivity!=="static"?s.push(p):i.push(p);return[...s,...i].slice(0,e.maxElements)}function cx(e={}){var o;let t=e0(e),r=(o=t.root)!=null?o:document.body;return r?t.mode==="simple"?l0(t,r):i0(t,r):[]}var ll=100;function ux(e,t={}){var a;if(e.length===0)return"No page elements found.";let r=(a=t.mode)!=null?a:"structured",o=[];if(r==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
112
+ `}if(!w&&!d){let Nt="max-height: -moz-available !important; max-height: stretch !important;",Kt=g?"":"padding-top: 1.25em !important;",Ot=g?"":`z-index: ${(Je=(Do=o.launcher)==null?void 0:Do.zIndex)!=null?Je:Tr} !important;`;Ne.style.cssText+=Nt+Kt+Ot}Ge()};Eo(),kn(e,o),Zi(e,o),el(e,o);let pt=[];pt.push(()=>{document.removeEventListener("keydown",cn)});let ir=null,lr=null;pt.push(()=>{ir==null||ir(),ir=null,lr==null||lr(),lr=null}),qr&&pt.push(()=>{qr==null||qr.disconnect(),qr=null}),pt.push(()=>{Rr==null||Rr(),Rr=null,$o(),Ht&&(Ht.remove(),Ht=null),ht==null||ht.element.style.removeProperty("width"),ht==null||ht.element.style.removeProperty("maxWidth")}),le&&pt.push(()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),Se==null||Se.destroy(),Se=null,K==null||K.destroy(),K=null,ze=null});let ko=null,ja=()=>{ko&&(ko(),ko=null),o.colorScheme==="auto"&&(ko=Ri(()=>{kn(e,o)}))};ja(),pt.push(()=>{ko&&(ko(),ko=null)}),pt.push(s);let jo=(qu=o.features)==null?void 0:qu.streamAnimation;if(jo!=null&&jo.type&&jo.type!=="none"){let d=Ss(jo.type,jo.plugins);d&&(Gc(d,e),pt.push(()=>bh(e)))}let Fn=Oh(Xe),Lo=null,q,pa=d=>{var w,P;if(!q)return;let g=d!=null?d:q.getMessages(),h=((P=(w=o.features)==null?void 0:w.suggestReplies)==null?void 0:P.enabled)!==!1?ri(g):null;h?Fn.render(h,q,Ae,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(N=>N.role==="user")?Fn.render([],q,Ae,g):Fn.render(o.suggestionChips,q,Ae,g,o.suggestionChipsConfig)},Po=!1,Ro=ch(),Go=new Map,Io=new Map,go=new Map,ua=0,Fs=Gn()!==null,jr=Wi(),Gr=0,ho=null,xo=!1,Nn=!1,Ko=0,wr=null,Ho=null,fa=!1,On=!1,ma=null,Ns=4,ga=24,Os=80,ha=new Map,dt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ga=(zu=(Vu=o.voiceRecognition)==null?void 0:Vu.autoResume)!=null?zu:!1,ao=d=>{i.emit("voice:state",{active:dt.active,source:d,timestamp:Date.now()})},Or=()=>{b(d=>({...d,voiceState:{active:dt.active,timestamp:Date.now(),manuallyDeactivated:dt.manuallyDeactivated}}))},xa=()=>{var w,P;if(((w=o.voiceRecognition)==null?void 0:w.enabled)===!1)return;let d=gp(p.voiceState),g=!!d.active,h=Number((P=d.timestamp)!=null?P:0);dt.manuallyDeactivated=!!d.manuallyDeactivated,g&&Date.now()-h<Yv&&setTimeout(()=>{var N,$;dt.active||(dt.manuallyDeactivated=!1,(($=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:$.type)==="runtype"?q.toggleVoice().then(()=>{dt.active=q.isVoiceActive(),ao("restore"),q.isVoiceActive()&&va()}):Us("restore"))},1e3)},ot=()=>q?nx(q.getMessages()).filter(d=>!d.__skipPersist):[];function k(d){if(!(l!=null&&l.save))return;let h={messages:d?nx(d):q?ot():[],metadata:p,artifacts:Vr.artifacts,selectedArtifactId:Vr.selectedId};try{let w=l.save(h);w instanceof Promise&&w.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)})}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",w)}}let z=null,V=()=>Ne.querySelector("#persona-scroll-container")||we,X=()=>{z!==null&&(cancelAnimationFrame(z),z=null),xo=!1},ge=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),Nn=!1,X()},De=()=>{Ko>0?(kr.textContent=String(Ko),kr.style.display="",_t.setAttribute("aria-label",`${xt()||"Jump to latest"} (${Ko} new)`)):(kr.textContent="",kr.style.display="none",_t.setAttribute("aria-label",xt()||"Jump to latest"))},ut=()=>{Ko!==0&&(Ko=0,De())},Lt=()=>vt()==="follow"?!jr.isFollowing():!ra(we,ga),Kr=()=>{if(!It()||Y){_t.parentNode&&_t.remove(),_t.style.display="none";return}_t.parentNode!==ye&&ye.appendChild(_t),Lr();let g=tn(we)>0&&Lt();g||ut(),_t.style.display=g?"":"none"},Wo=()=>{jr.pause()&&(ge(),Kr())},gr=()=>{jr.resume(),ut(),Kr()},Zt=(d=!1)=>{vt()==="follow"&&jr.isFollowing()&&(!d&&!Po||(ho!==null&&(cancelAnimationFrame(ho),ho=null),Nn=!0,ho=requestAnimationFrame(()=>{ho=null,Nn=!1,jr.isFollowing()&&mn(V(),d?220:140)})))},fn=(d,g,h,w=()=>!0)=>{let P=d.scrollTop,N=g(),$=N-P;X();let U=performance.now();xo=!0;let _=oe=>1-Math.pow(1-oe,3),re=oe=>{if(!w()){X();return}let Z=g();Z!==N&&(N=Z,$=N-P);let xe=oe-U,Be=Math.min(xe/h,1),be=_(Be),Ze=P+$*be;d.scrollTop=Ze,Gr=d.scrollTop,Be<1?z=requestAnimationFrame(re):(d.scrollTop=N,Gr=d.scrollTop,z=null,xo=!1)};z=requestAnimationFrame(re)},mn=(d,g=500)=>{let h=tn(d)-d.scrollTop;if(Math.abs(h)<1){Gr=d.scrollTop;return}if(Math.abs(h)>=Os){X(),xo=!0,d.scrollTop=tn(d),Gr=d.scrollTop,xo=!1;return}fn(d,()=>tn(d),g,()=>jr.isFollowing())},Ir=()=>{let d=V();xo=!0,d.scrollTop=tn(d),Gr=d.scrollTop,xo=!1,Kr()},Hr=d=>{Cr.style.height=`${Math.max(0,Math.round(d))}px`,wr&&(wr.spacerHeight=Math.max(0,d))},Sr=()=>{Ho!==null&&(cancelAnimationFrame(Ho),Ho=null),X(),wr=null,Cr.style.height="0px"},Vx=d=>{Ho!==null&&cancelAnimationFrame(Ho),Ho=requestAnimationFrame(()=>{var re;Ho=null;let g=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(d):d.replace(/"/g,'\\"'),h=we.querySelector(`[data-message-id="${g}"]`);if(!h)return;let w=0,P=h;for(;P&&P!==we;)w+=P.offsetTop,P=P.offsetParent;let N=(re=wr==null?void 0:wr.spacerHeight)!=null?re:0,$=we.scrollHeight-N,{targetScrollTop:U,spacerHeight:_}=gh({anchorOffsetTop:w,topOffset:mr(),viewportHeight:we.clientHeight,contentHeight:$});wr={initialSpacerHeight:_,contentHeightAtAnchor:$,spacerHeight:_},Hr(_),fn(we,()=>U,220)})},zx=()=>{if(vt()==="follow"){if(!jr.isFollowing()||ra(we,1))return;Zt(!Po);return}if(wr&&wr.initialSpacerHeight>0){let d=we.scrollHeight-wr.spacerHeight,g=hh({initialSpacerHeight:wr.initialSpacerHeight,contentHeightAtAnchor:wr.contentHeightAtAnchor,currentContentHeight:d});g!==wr.spacerHeight&&Hr(g)}Kr()},$x=d=>{let g=vt();g==="follow"?(gr(),Zt(!0)):g==="anchor-top"&&Vx(d)},jx=d=>{let g=new Map;d.forEach(h=>{let w=ha.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!w&&h.role==="assistant"&&(i.emit("assistant:message",h),!On&&vt()!=="anchor-top"&&Lt()&&(Ko+=1,De(),Kr())),h.role==="assistant"&&(w!=null&&w.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(w?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),ha.clear(),g.forEach((h,w)=>{ha.set(w,h)})},Gx=(d,g,h)=>{var et,ke,Te,Ve,Ge,ft;let w=document.createElement("div"),N=(()=>{var Pe;let B=n.find(Le=>Le.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Pe=o.loadingIndicator)!=null&&Pe.render)return o.loadingIndicator.render})(),$=(B,Pe)=>Pe==null?!1:typeof Pe=="string"?(B.textContent=Pe,!0):(B.appendChild(Pe),!0),U=new Set,_=new Set,re=n.some(B=>B.renderAskUserQuestion),oe=[],Z=[],xe=o.enableComponentStreaming!==!1,Be=o.approval!==!1,be=[];if(g.forEach(B=>{var Ke,Tt,ar,lo,Jr,Un,qn,wa,Sa,Jt,Vn,xn,yn,Jo,zn,yo,Do;U.add(B.id);let Pe=re&&Qo(B),Le=Be&&B.variant==="approval"&&!!B.approval,ue=!Pe&&B.role==="assistant"&&!B.variant&&xe&&nl(B);if(!Le&&go.has(B.id)){let Je=d.querySelector(`#wrapper-${B.id}`);Je==null||Je.removeAttribute("data-preserve-runtime"),go.delete(B.id)}if(!ue&&Io.has(B.id)){let Je=d.querySelector(`#wrapper-${B.id}`);Je==null||Je.removeAttribute("data-preserve-runtime"),Io.delete(B.id)}let Ft=Qo(B)?`:${(Ke=B.agentMetadata)!=null&&Ke.askUserQuestionAnswered?"a":"u"}:${(Tt=B.agentMetadata)!=null&&Tt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Wt=dh(B,ua)+Ft,Xt=Pe||Le||ue?null:ph(Ro,B.id,Wt);if(Xt){w.appendChild(Xt.cloneNode(!0)),Qo(B)&&((ar=B.toolCall)!=null&&ar.id)&&((lo=B.agentMetadata)==null?void 0:lo.awaitingLocalTool)===!0&&!((Jr=B.agentMetadata)!=null&&Jr.askUserQuestionAnswered)&&(_.add(B.toolCall.id),Pa(B,o,$e.composerOverlay));return}let mt=null,$t=n.find(Je=>!!(B.variant==="reasoning"&&Je.renderReasoning||B.variant==="tool"&&Je.renderToolCall||!B.variant&&Je.renderMessage)),Xr=(Un=o.layout)==null?void 0:Un.messages;if(Qo(B)&&((qn=B.agentMetadata)==null?void 0:qn.askUserQuestionAnswered)===!0){Go.delete(B.id);let Je=d.querySelector(`#wrapper-${B.id}`);Je==null||Je.removeAttribute("data-preserve-runtime");return}if(cs(B)&&((Sa=(wa=o.features)==null?void 0:wa.suggestReplies)==null?void 0:Sa.enabled)!==!1)return;if(Qo(B)&&((Vn=(Jt=o.features)==null?void 0:Jt.askUserQuestion)==null?void 0:Vn.enabled)!==!1){let Je=n.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(Je&&wt.current){let Nt=Go.get(B.id),Kt=Nt!==Wt,Ot=null;if(Kt){let{payload:Ut,complete:hr}=Yo(B),Qr=B.id,Fo=()=>{var xr;return(xr=wt.current)==null?void 0:xr.getMessages().find(yr=>yr.id===Qr)};Ot=Je.renderAskUserQuestion({message:B,payload:Ut,complete:hr,resolve:xr=>{var co;let yr=Fo();yr&&((co=wt.current)==null||co.resolveAskUserQuestion(yr,xr))},dismiss:()=>{var yr,co,bn;let xr=Fo();(yr=xr==null?void 0:xr.agentMetadata)!=null&&yr.awaitingLocalTool&&((co=wt.current)==null||co.markAskUserQuestionResolved(xr),(bn=wt.current)==null||bn.resolveAskUserQuestion(xr,"(dismissed)"))},config:o})}let Qt=Nt!=null;if(Kt&&Ot===null&&!Qt){((xn=B.agentMetadata)==null?void 0:xn.awaitingLocalTool)===!0&&!((yn=B.agentMetadata)!=null&&yn.askUserQuestionAnswered)&&(_.add(B.toolCall.id),Pa(B,o,$e.composerOverlay));return}let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${B.id}`,Et.setAttribute("data-wrapper-id",B.id),Et.setAttribute("data-ask-plugin-stub","true"),Et.setAttribute("data-preserve-runtime","true"),w.appendChild(Et),oe.push({messageId:B.id,fingerprint:Wt,bubble:Ot});return}else{((Jo=B.agentMetadata)==null?void 0:Jo.awaitingLocalTool)===!0&&!((zn=B.agentMetadata)!=null&&zn.askUserQuestionAnswered)&&(_.add(B.toolCall.id),Pa(B,o,$e.composerOverlay));return}}else if(Le){let Je=(yo=n.find(Qt=>typeof Qt.renderApproval=="function"))!=null?yo:a,Kt=go.get(B.id)!==Wt,Ot=null;if(Kt&&(Je!=null&&Je.renderApproval)){let Qt=B.id,Et=(Ut,hr)=>{var Fo,xr,yr;let Qr=(Fo=wt.current)==null?void 0:Fo.getMessages().find(co=>co.id===Qt);Qr!=null&&Qr.approval&&(Qr.approval.toolType==="webmcp"?(xr=wt.current)==null||xr.resolveWebMcpApproval(Qr.id,Ut):(yr=wt.current)==null||yr.resolveApproval(Qr.approval,Ut,hr))};Ot=Je.renderApproval({message:B,defaultRenderer:()=>Qi(B,o),config:o,approve:Ut=>Et("approved",Ut),deny:Ut=>Et("denied",Ut)})}if(Kt&&Ot===null){let Qt=d.querySelector(`#wrapper-${B.id}`);Qt==null||Qt.removeAttribute("data-preserve-runtime"),go.delete(B.id),mt=Qi(B,o)}else{let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-approval-plugin-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),w.appendChild(Qt),be.push({messageId:B.id,fingerprint:Wt,bubble:Ot});return}}else if($t)if(B.variant==="reasoning"&&B.reasoning&&$t.renderReasoning){if(!Ce)return;mt=$t.renderReasoning({message:B,defaultRenderer:()=>ap(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&$t.renderToolCall){if(!Ie)return;mt=$t.renderToolCall({message:B,defaultRenderer:()=>ip(B,o),config:o})}else $t.renderMessage&&(mt=$t.renderMessage({message:B,defaultRenderer:()=>{let Je=Oa(B,h,Xr,o.messageActions,rt,{loadingIndicatorRenderer:N,widgetConfig:o});return B.role!=="user"&&up(Je,B,o,q),Je},config:o}));if(!mt&&ue){let Je=al(B);if(Je){let Nt=Io.get(B.id),Kt=Nt!==Wt,Ot=o.wrapComponentDirectiveInBubble!==!1,Qt=null;if(Kt){let Et=ol(Je,{config:o,message:B,transform:h});if(Et)if(Ot){let Ut=document.createElement("div");if(Ut.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(" "),Ut.id=`bubble-${B.id}`,Ut.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let hr=document.createElement("div");hr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",hr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Ut.appendChild(hr)}Ut.appendChild(Et),Qt=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${B.id}`,Ut.setAttribute("data-message-id",B.id),Ut.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let hr=document.createElement("div");hr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",hr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Ut.appendChild(hr)}Ut.appendChild(Et),Qt=Ut}}if(Qt||Nt!=null){let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${B.id}`,Et.setAttribute("data-wrapper-id",B.id),Et.setAttribute("data-component-directive-stub","true"),Et.setAttribute("data-preserve-runtime","true"),Ot||Et.classList.add("persona-w-full"),w.appendChild(Et),Z.push({messageId:B.id,fingerprint:Wt,bubble:Qt});return}}}if(!mt)if(B.variant==="reasoning"&&B.reasoning){if(!Ce)return;mt=ap(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!Ie)return;mt=ip(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;mt=Qi(B,o)}else{let Je=(Do=o.layout)==null?void 0:Do.messages;Je!=null&&Je.renderUserMessage&&B.role==="user"?mt=Je.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):Je!=null&&Je.renderAssistantMessage&&B.role==="assistant"?mt=Je.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):mt=Oa(B,h,Je,o.messageActions,rt,{loadingIndicatorRenderer:N,widgetConfig:o}),B.role!=="user"&&mt&&up(mt,B,o,q)}let rr=document.createElement("div");rr.className="persona-flex",rr.id=`wrapper-${B.id}`,rr.setAttribute("data-wrapper-id",B.id),B.role==="user"&&rr.classList.add("persona-justify-end"),(mt==null?void 0:mt.getAttribute("data-persona-component-directive"))==="true"&&rr.classList.add("persona-w-full"),rr.appendChild(mt),uh(Ro,B.id,Wt,rr),w.appendChild(rr)}),$e.composerOverlay&&$e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Pe=>{let Le=Pe.getAttribute("data-persona-ask-sheet-for");Le&&!_.has(Le)&&Sn($e.composerOverlay,Le)}),(ke=(et=o.features)==null?void 0:et.toolCallDisplay)!=null&&ke.grouped){let B=[],Pe=[];g.forEach(Le=>{if(Le.variant==="tool"&&Le.toolCall&&Ie){Pe.push(Le);return}Pe.length>1&&B.push(Pe),Pe=[]}),Pe.length>1&&B.push(Pe),B.forEach((Le,ue)=>{var Ke,Tt;let Ft=Le.map(ar=>Array.from(w.children).find(lo=>lo instanceof HTMLElement&&lo.getAttribute("data-wrapper-id")===ar.id)).filter(ar=>!!ar);if(Ft.length<2)return;let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-tool-group-${ue}-${Le[0].id}`,Wt.setAttribute("data-wrapper-id",`tool-group-${ue}-${Le[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 mt=document.createElement("div");mt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let $t=`Called ${Le.length} tools`,Xr=(Tt=(Ke=o.toolCall)==null?void 0:Ke.renderGroupedSummary)==null?void 0:Tt.call(Ke,{messages:Le,toolCalls:Le.map(ar=>ar.toolCall).filter(ar=>!!ar),defaultSummary:$t,config:o});$(mt,Xr)||(mt.textContent=$t);let rr=document.createElement("div");rr.className="persona-tool-group-stack persona-flex persona-flex-col",Xt.append(mt,rr),Wt.appendChild(Xt),Ft[0].before(Wt),Ft.forEach((ar,lo)=>{let Jr=document.createElement("div");Jr.className="persona-tool-group-item persona-relative",Jr.setAttribute("data-persona-tool-group-item","true"),lo<Ft.length-1&&Jr.setAttribute("data-persona-tool-group-connector","true"),Jr.appendChild(ar),rr.appendChild(Jr)})})}fh(Ro,U);let Ze=g.some(B=>B.role==="assistant"&&B.streaming),qe=g[g.length-1],lt=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(Po&&g.some(B=>B.role==="user")&&!Ze&&!lt){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:aa},Pe=n.find(ue=>ue.renderLoadingIndicator),Le=null;if(Pe!=null&&Pe.renderLoadingIndicator&&(Le=Pe.renderLoadingIndicator(B)),Le===null&&((Te=o.loadingIndicator)!=null&&Te.render)&&(Le=o.loadingIndicator.render(B)),Le===null&&(Le=aa()),Le){let ue=document.createElement("div"),Ft=((Ve=o.loadingIndicator)==null?void 0:Ve.showBubble)!==!1;ue.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(" "),ue.setAttribute("data-typing-indicator","true"),ue.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ue.appendChild(Le);let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id="wrapper-typing-indicator",Wt.setAttribute("data-wrapper-id","typing-indicator"),Wt.appendChild(ue),w.appendChild(Wt)}}if(!Po&&g.length>0){let B=g[g.length-1],Pe={config:o,lastMessage:B,messageCount:g.length},Le=n.find(Ft=>Ft.renderIdleIndicator),ue=null;if(Le!=null&&Le.renderIdleIndicator&&(ue=Le.renderIdleIndicator(Pe)),ue===null&&((Ge=o.loadingIndicator)!=null&&Ge.renderIdle)&&(ue=o.loadingIndicator.renderIdle(Pe)),ue){let Ft=document.createElement("div"),Wt=((ft=o.loadingIndicator)==null?void 0:ft.showBubble)!==!1;Ft.className=Wt?["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(ue);let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id="wrapper-idle-indicator",Xt.setAttribute("data-wrapper-id","idle-indicator"),Xt.appendChild(Ft),w.appendChild(Xt)}}if(Ii(d,w),oe.length>0)for(let{messageId:B,fingerprint:Pe,bubble:Le}of oe){let ue=d.querySelector(`#wrapper-${B}`);ue&&Le!==null&&(ue.replaceChildren(Le),ue.setAttribute("data-bubble-fp",Pe),Go.set(B,Pe))}if(Go.size>0)for(let B of Go.keys())U.has(B)||Go.delete(B);if(Z.length>0)for(let{messageId:B,fingerprint:Pe,bubble:Le}of Z){let ue=d.querySelector(`#wrapper-${B}`);ue&&Le!==null&&(ue.replaceChildren(Le),ue.setAttribute("data-bubble-fp",Pe),Io.set(B,Pe))}if(Io.size>0)for(let B of Io.keys())U.has(B)||Io.delete(B);if(be.length>0)for(let{messageId:B,fingerprint:Pe,bubble:Le}of be){let ue=d.querySelector(`#wrapper-${B}`);ue&&Le!==null&&(ue.replaceChildren(Le),ue.setAttribute("data-bubble-fp",Pe),go.set(B,Pe))}if(go.size>0)for(let B of go.keys())U.has(B)||go.delete(B)},Ka=(d,g,h)=>{Gx(d,g,h),ln()},Xa=null,Kx=()=>{var h;if(Xa)return;let d=w=>{let P=w.composedPath();P.includes(Ne)||je&&P.includes(je)||zt(!1,"user")};Xa=d,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",d,!0)},Ip=()=>{var g;if(!Xa)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Xa,!0),Xa=null};pt.push(()=>Ip());let Ja=null,Xx=()=>{var h;if(Ja)return;let d=w=>{w.key==="Escape"&&(w.isComposing||zt(!1,"user"))};Ja=d,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",d,!0)},Hp=()=>{var g;if(!Ja)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",Ja,!0),Ja=null};pt.push(()=>Hp());let Qa=!1,Wp=new Set,Jx=()=>{var g,h,w,P;let d=(w=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.peek)==null?void 0:w.streamAnimation;return d||((P=o.features)==null?void 0:P.streamAnimation)},ya=()=>{var lt,et,ke,Te;if(!R())return;let d=$e.peekBanner,g=$e.peekTextNode;if(!d||!g)return;if(O){d.classList.remove("persona-pill-peek--visible");return}let h=(lt=q==null?void 0:q.getMessages())!=null?lt:[],w;for(let Ve=h.length-1;Ve>=0;Ve--){let Ge=h[Ve];if(Ge.role==="assistant"&&Ge.content){w=Ge;break}}if(!w){d.classList.remove("persona-pill-peek--visible");return}let P=w.content,N=!!w.streaming,$=Jx(),U=Fi($),_=U.type!=="none"?Ss(U.type,$==null?void 0:$.plugins):null,re=((et=_==null?void 0:_.isAnimating)==null?void 0:et.call(_,w))===!0,oe=_!==null&&(N||re);oe&&_&&!Wp.has(_.name)&&(Gc(_,e),Wp.add(_.name));let Z=oe&&(_!=null&&_.containerClass)?_.containerClass:null,xe=(ke=g.dataset.personaPeekStreamClass)!=null?ke:null;xe&&xe!==Z&&(g.classList.remove(xe),delete g.dataset.personaPeekStreamClass),Z&&xe!==Z&&(g.classList.add(Z),g.dataset.personaPeekStreamClass=Z),oe?(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 Be=oe?Ni(P,U.buffer,_,w,N):P;if(oe&&U.placeholder==="skeleton"&&N&&(!Be||!Be.trim())){let Ve=document.createElement("div"),Ge=Ms();Ge.classList.add("persona-pill-peek__skeleton"),Ve.appendChild(Ge),Ii(g,Ve)}else{let Ve=Math.max(0,Be.length-100),Ge=Be.length>100?Be.slice(-100):Be,ft=No(Ge);if(!oe||!_){let B=Be.length>100?`\u2026${Ge}`:Ge;g.textContent!==B&&(g.textContent=B)}else{let B=ft;(_.wrap==="char"||_.wrap==="word")&&(B=As(ft,_.wrap,`peek-${w.id}`,{skipTags:_.skipTags,startIndex:Ve}));let Pe=document.createElement("div");if(Pe.innerHTML=B,_.useCaret&&Ge.length>0){let Le=Oi(),ue=Pe.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=ue[ue.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(Le,Ft.nextSibling):Pe.appendChild(Le)}Ii(g,Pe),(Te=_.onAfterRender)==null||Te.call(_,{container:g,bubble:d,messageId:w.id,message:w,speed:U.speed,duration:U.duration})}}let qe=Po||Qa;d.classList.toggle("persona-pill-peek--visible",qe)};if(R()){let d=$e.peekBanner;if(d){let w=P=>{P.preventDefault(),P.stopPropagation(),zt(!0,"user")};d.addEventListener("pointerdown",w),pt.push(()=>{d.removeEventListener("pointerdown",w)})}let g=()=>{Qa||(Qa=!0,ya())},h=()=>{Qa&&(Qa=!1,ya())};G.addEventListener("pointerenter",g),G.addEventListener("pointerleave",h),pt.push(()=>{G.removeEventListener("pointerenter",g),G.removeEventListener("pointerleave",h)}),je&&(je.addEventListener("pointerenter",g),je.addEventListener("pointerleave",h),pt.push(()=>{je.removeEventListener("pointerenter",g),je.removeEventListener("pointerleave",h)}))}let Qx=d=>{var xe,Be,be,Ze,qe,lt,et,ke;let g=(Be=(xe=o.launcher)==null?void 0:xe.composerBar)!=null?Be:{},h=(be=g.expandedSize)!=null?be:"anchored",w=(Ze=g.bottomOffset)!=null?Ze:"16px",P=g.collapsedMaxWidth,N=(qe=g.expandedMaxWidth)!=null?qe:"880px",$=(lt=g.expandedTopOffset)!=null?lt:"5vh",U=(et=g.modalMaxWidth)!=null?et:"880px",_=(ke=g.modalMaxHeight)!=null?ke:"min(90vh, 800px)",re="calc(100vw - 32px)",oe="var(--persona-pill-area-height, 80px)",Z=Ne.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",je){let Te=je.style;Te.bottom=w,Te.width=P!=null?P:""}if(d&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=U,Z.maxWidth=re,Z.maxHeight=_,Z.height=_;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${w} + ${oe})`,Z.top=$,Z.width=N,Z.maxWidth=re}},Ya=()=>{var _,re,oe,Z,xe,Be,be,Ze;if(!D())return;if(R()){let lt=(oe=((re=(_=o.launcher)==null?void 0:_.composerBar)!=null?re:{}).expandedSize)!=null?oe:"anchored",et=O?"expanded":"collapsed";Ne.dataset.state=et,Ne.dataset.expandedSize=lt,je&&(je.dataset.state=et,je.dataset.expandedSize=lt),Ne.style.removeProperty("display"),Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Qx(O),ye.style.display=O?"flex":"none",Eo(),O?(Kx(),Xx()):(Ip(),Hp()),ya();return}let d=sr(o),g=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Be=(xe=o.launcher)==null?void 0:xe.mobileBreakpoint)!=null?Be:640,w=(Ze=(be=o.launcher)==null?void 0:be.mobileFullscreen)!=null?Ze:!0,P=g.innerWidth<=h,N=w&&P&&T,$=eo(o).reveal;O?(Ne.style.removeProperty("display"),Ne.style.display=d?"flex":"",Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-95","persona-opacity-0"),G.classList.add("persona-scale-100","persona-opacity-100"),tr?tr.element.style.display="none":dr&&(dr.style.display="none")):(d?d&&($==="overlay"||$==="push")&&!N?(Ne.style.removeProperty("display"),Ne.style.display="flex",Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ne.style.setProperty("display","none","important"),Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ne.style.display="",Ne.classList.add("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100"),G.classList.add("persona-scale-95","persona-opacity-0")),tr?tr.element.style.display=d?"none":"":dr&&(dr.style.display=d?"none":""))},zt=(d,g="user")=>{var N,$;if(!D()||O===d)return;let h=O;O=d,Ya();let w=(()=>{var be,Ze,qe,lt,et,ke,Te,Ve,Ge,ft;let U=(Ze=(be=o.launcher)==null?void 0:be.sidebarMode)!=null?Ze:!1,_=(qe=e.ownerDocument.defaultView)!=null?qe:window,re=(et=(lt=o.launcher)==null?void 0:lt.mobileFullscreen)!=null?et:!0,oe=(Te=(ke=o.launcher)==null?void 0:ke.mobileBreakpoint)!=null?Te:640,Z=_.innerWidth<=oe,xe=sr(o)&&re&&Z,Be=R()&&((ft=(Ge=(Ve=o.launcher)==null?void 0:Ve.composerBar)==null?void 0:Ge.expandedSize)!=null?ft:"fullscreen")==="fullscreen";return U||re&&Z&&T||xe||Be})();if(O&&w){if(!ir){let U=e.getRootNode(),_=U instanceof ShadowRoot?U.host:e.closest(".persona-host");_&&(ir=Kc(_,($=(N=o.launcher)==null?void 0:N.zIndex)!=null?$:Tr))}lr||(lr=Xc(e.ownerDocument))}else O||(ir==null||ir(),ir=null,lr==null||lr(),lr=null);O&&(Za(),vt()==="follow"?Zt(!0):Ir());let P={open:O,source:g,timestamp:Date.now()};O&&!h?i.emit("widget:opened",P):!O&&h&&i.emit("widget:closed",P),i.emit("widget:state",{open:O,launcherEnabled:T,voiceActive:dt.active,streaming:q.isStreaming()})},ul=d=>{Rt(d?"stop":"send"),W&&(W.disabled=d),Fn.buttons.forEach(g=>{g.disabled=d}),Ee.dataset.personaComposerStreaming=d?"true":"false",Ee.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=d)})},fl=()=>{dt.active||Ae&&Ae.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>fl(),200)});let Bp=()=>{var h,w,P,N,$,U,_,re,oe,Z,xe;Uo.textContent=(w=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?w:"Hello \u{1F44B}",F.textContent=(N=(P=o.copy)==null?void 0:P.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",Ae.placeholder=(U=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?U:"How can I help...";let d=we.querySelector("[data-persona-intro-card]");if(d){let Be=((_=o.copy)==null?void 0:_.showWelcomeCard)!==!1;d.style.display=Be?"":"none",Be?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((oe=(re=o.sendButton)==null?void 0:re.useIcon)!=null&&oe)&&!(q!=null&&q.isStreaming())&&(Oe.textContent=(xe=(Z=o.copy)==null?void 0:Z.sendButtonLabel)!=null?xe:"Send"),Ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let d=p.sessionId;return typeof d=="string"?d:null},setStoredSessionId:d=>{b(g=>({...g,sessionId:d}))}});let _n=null,Yx=()=>{_n==null&&(_n=setInterval(()=>{let d=Qe.querySelectorAll("[data-tool-elapsed]");if(d.length===0){clearInterval(_n),_n=null;return}let g=Date.now();d.forEach(h=>{let w=Number(h.getAttribute("data-tool-elapsed"));w&&(h.textContent=ni(g-w))})},100))};q=new Ha(o,{onMessagesChanged(d){var w;Ka(Qe,d,ee),Yx(),pa(d),Zt(!Po),jx(d);let g=[...d].reverse().find(P=>P.role==="user");d.length===0&&Sr(),!fa||On?(fa=!0,ma=(w=g==null?void 0:g.id)!=null?w:null):g&&g.id!==ma&&(ma=g.id,$x(g.id));let h=dt.lastUserMessageId;g&&g.id!==h&&(dt.lastUserMessageId=g.id,i.emit("user:message",g)),dt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),k(d),ya()},onStatusChanged(d){var w;let g=(w=o.statusIndicator)!=null?w:{};Gt(Yt,(P=>{var N,$,U,_;return P==="idle"?(N=g.idleText)!=null?N:Mr.idle:P==="connecting"?($=g.connectingText)!=null?$:Mr.connecting:P==="connected"?(U=g.connectedText)!=null?U:Mr.connected:P==="error"?(_=g.errorText)!=null?_:Mr.error:Mr[P]})(d),g,d)},onStreamingChanged(d){Po=d,ul(d),q&&Ka(Qe,q.getMessages(),ee),d||Zt(!0),ya()},onVoiceStatusChanged(d){var g,h;if(i.emit("voice:status",{status:d,timestamp:Date.now()}),((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype")switch(d){case"listening":Xo(),va();break;case"processing":Xo(),oy();break;case"speaking":Xo(),ny();break;default:d==="idle"&&q.isBargeInActive()?(Xo(),va(),W==null||W.setAttribute("aria-label","End voice session")):(dt.active=!1,Xo(),ao("system"),Or());break}},onArtifactsState(d){Vr=d,Nr(),k()}}),wt.current=q;let ml=null;if(q.onReadAloudChange((d,g)=>{var P;an=d,sn=g,ln();let h=d!=null?d:ml;d&&(ml=d);let w=h&&(P=q.getMessages().find(N=>N.id===h))!=null?P:null;i.emit("message:read-aloud",{messageId:h,message:w,state:g,timestamp:Date.now()}),g==="idle"&&(ml=null)}),fa=!0,((ju=($u=o.voiceRecognition)==null?void 0:$u.provider)==null?void 0:ju.type)==="runtype")try{q.setupVoice()}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",d)}o.clientToken&&q.initClientSession().catch(d=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",d)}),(K||o.onSSEEvent)&&q.setSSEEventCallback((d,g)=>{var h;(h=o.onSSEEvent)==null||h.call(o,d,g),J==null||J.processEvent(d,g),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:d,timestamp:Date.now(),payload:JSON.stringify(g)})}),f&&f.then(d=>{var g,h,w;if(d){if(d.metadata&&(p=gp(d.metadata),A.syncFromMetadata()),(g=d.messages)!=null&&g.length){On=!0;try{q.hydrateMessages(d.messages)}finally{On=!1}}(h=d.artifacts)!=null&&h.length&&q.hydrateArtifacts(d.artifacts,(w=d.selectedArtifactId)!=null?w:null)}}).catch(d=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",d)});let Dp=()=>{var g,h,w;!R()||O||!((w=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.expandOnSubmit)==null||w)||zt(!0,"auto")},Fp=d=>{var P;if(d.preventDefault(),q.isStreaming()){q.cancel(),J==null||J.reset(),Se==null||Se.update();return}let g=Ae.value.trim(),h=(P=Ct==null?void 0:Ct.hasAttachments())!=null?P:!1;if(!g&&!h)return;Dp();let w;h&&(w=[],w.push(...Ct.getContentParts()),g&&w.push(gs(g))),Ae.value="",Ae.style.height="auto",_s(),q.sendMessage(g,{contentParts:w}),h&&Ct.clearAttachments()},Zx=()=>{var d;return((d=o.features)==null?void 0:d.composerHistory)!==!1},gl={...Hi},hl=!1,_s=()=>{gl={...Hi}},ey=()=>q.getMessages().filter(d=>d.role==="user").map(d=>{var g;return(g=d.content)!=null?g:""}).filter(d=>d.length>0),ty=d=>{if(!Ae)return;hl=!0,Ae.value=d,Ae.dispatchEvent(new Event("input",{bubbles:!0})),hl=!1;let g=Ae.value.length;Ae.setSelectionRange(g,g)},Np=()=>{hl||_s()},Op=d=>{if(Ae){if(Zx()&&(d.key==="ArrowUp"||d.key==="ArrowDown")&&!d.shiftKey&&!d.metaKey&&!d.ctrlKey&&!d.altKey&&!d.isComposing){let g=Ae.selectionStart===0&&Ae.selectionEnd===0,h=lh({direction:d.key==="ArrowUp"?"up":"down",history:ey(),currentValue:Ae.value,atStart:g,state:gl});if(gl=h.state,h.handled){d.preventDefault(),h.value!==void 0&&ty(h.value);return}}if(d.key==="Enter"&&!d.shiftKey){if(q.isStreaming()){d.preventDefault();return}_s(),d.preventDefault(),Oe.click()}}},_p=d=>{d.key!=="Escape"||d.isComposing||q.isStreaming()&&d.composedPath().includes(ye)&&(q.cancel(),J==null||J.reset(),Se==null||Se.update(),_s(),d.preventDefault(),d.stopImmediatePropagation())},Up=async d=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!Ct)return;let g=e0(d.clipboardData);g.length!==0&&(d.preventDefault(),await Ct.handleFiles(g))},so=null,Bo=!1,ba=null,it=null,qp=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Us=(d="user")=>{var N,$,U,_,re,oe,Z;if(Bo||q.isStreaming())return;let g=qp();if(!g)return;so=new g;let w=($=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?$:2e3;so.continuous=!0,so.interimResults=!0,so.lang="en-US";let P=Ae.value;so.onresult=xe=>{let Be="",be="";for(let qe=0;qe<xe.results.length;qe++){let lt=xe.results[qe],et=lt[0].transcript;lt.isFinal?Be+=et+" ":be=et}let Ze=P+Be+be;Ae.value=Ze,ba&&clearTimeout(ba),(Be||be)&&(ba=window.setTimeout(()=>{let qe=Ae.value.trim();qe&&so&&Bo&&(gn(),Ae.value="",Ae.style.height="auto",q.sendMessage(qe,{viaVoice:!0}))},w))},so.onerror=xe=>{xe.error!=="no-speech"&&gn()},so.onend=()=>{if(Bo){let xe=Ae.value.trim();xe&&xe!==P.trim()&&(Ae.value="",Ae.style.height="auto",q.sendMessage(xe,{viaVoice:!0})),gn()}};try{if(so.start(),Bo=!0,dt.active=!0,d!=="system"&&(dt.manuallyDeactivated=!1),ao(d),Or(),W){let xe=(U=o.voiceRecognition)!=null?U:{};it={backgroundColor:W.style.backgroundColor,color:W.style.color,borderColor:W.style.borderColor,iconName:(_=xe.iconName)!=null?_:"mic",iconSize:parseFloat((Z=(oe=xe.iconSize)!=null?oe:(re=o.sendButton)==null?void 0:re.size)!=null?Z:"40")||24};let Be=xe.recordingBackgroundColor,be=xe.recordingIconColor,Ze=xe.recordingBorderColor;if(W.classList.add("persona-voice-recording"),W.style.backgroundColor=Be!=null?Be:"var(--persona-voice-recording-bg, #ef4444)",W.style.color=be!=null?be:"var(--persona-voice-recording-indicator, #ffffff)",be){let qe=W.querySelector("svg");qe&&qe.setAttribute("stroke",be)}Ze&&(W.style.borderColor=Ze),W.setAttribute("aria-label","Stop voice recognition")}}catch{gn("system")}},gn=(d="user")=>{if(Bo){if(Bo=!1,ba&&(clearTimeout(ba),ba=null),so){try{so.stop()}catch{}so=null}if(dt.active=!1,ao(d),Or(),W){if(W.classList.remove("persona-voice-recording"),it){W.style.backgroundColor=it.backgroundColor,W.style.color=it.color,W.style.borderColor=it.borderColor;let g=W.querySelector("svg");g&&g.setAttribute("stroke",it.color||"currentColor"),it=null}W.setAttribute("aria-label","Start voice recognition")}}},ry=(d,g)=>{var et,ke,Te,Ve,Ge,ft,B,Pe,Le;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),w=((et=d==null?void 0:d.provider)==null?void 0:et.type)==="runtype",P=((ke=d==null?void 0:d.provider)==null?void 0:ke.type)==="custom";if(!(h||w||P))return null;let $=C("div","persona-send-button-wrapper"),U=C("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let _=(Te=d==null?void 0:d.iconName)!=null?Te:"mic",re=(Ve=g==null?void 0:g.size)!=null?Ve:"40px",oe=(Ge=d==null?void 0:d.iconSize)!=null?Ge:re,Z=parseFloat(oe)||24,xe=(ft=d==null?void 0:d.backgroundColor)!=null?ft:g==null?void 0:g.backgroundColor,Be=(B=d==null?void 0:d.iconColor)!=null?B:g==null?void 0:g.textColor;U.style.width=oe,U.style.height=oe,U.style.minWidth=oe,U.style.minHeight=oe,U.style.fontSize="18px",U.style.lineHeight="1",Be?U.style.color=Be:U.style.color="var(--persona-text, #111827)";let Ze=fe(_,Z,Be||"currentColor",1.5);Ze?U.appendChild(Ze):U.textContent="\u{1F3A4}",xe?U.style.backgroundColor=xe:U.style.backgroundColor="",d!=null&&d.borderWidth&&(U.style.borderWidth=d.borderWidth,U.style.borderStyle="solid"),d!=null&&d.borderColor&&(U.style.borderColor=d.borderColor),d!=null&&d.paddingX&&(U.style.paddingLeft=d.paddingX,U.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(U.style.paddingTop=d.paddingY,U.style.paddingBottom=d.paddingY),$.appendChild(U);let qe=(Pe=d==null?void 0:d.tooltipText)!=null?Pe:"Start voice recognition";if(((Le=d==null?void 0:d.showTooltip)!=null?Le:!1)&&qe){let ue=C("div","persona-send-button-tooltip");ue.textContent=qe,$.appendChild(ue)}return{micButton:U,micButtonWrapper:$}},xl=()=>{var g,h,w,P,N;if(!W||it)return;let d=(g=o.voiceRecognition)!=null?g:{};it={backgroundColor:W.style.backgroundColor,color:W.style.color,borderColor:W.style.borderColor,iconName:(h=d.iconName)!=null?h:"mic",iconSize:parseFloat((N=(P=d.iconSize)!=null?P:(w=o.sendButton)==null?void 0:w.size)!=null?N:"40")||24}},yl=(d,g)=>{var N,$,U,_,re;if(!W)return;let h=W.querySelector("svg");h&&h.remove();let w=(re=it==null?void 0:it.iconSize)!=null?re:parseFloat((_=(U=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?U:($=o.sendButton)==null?void 0:$.size)!=null?_:"40")||24,P=fe(d,w,g,1.5);P&&W.appendChild(P)},qs=()=>{W&&W.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},va=()=>{var P;if(!W)return;xl();let d=(P=o.voiceRecognition)!=null?P:{},g=d.recordingBackgroundColor,h=d.recordingIconColor,w=d.recordingBorderColor;if(qs(),W.classList.add("persona-voice-recording"),W.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",W.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=W.querySelector("svg");N&&N.setAttribute("stroke",h)}w&&(W.style.borderColor=w),W.setAttribute("aria-label","Stop voice recognition")},oy=()=>{var U,_,re,oe,Z,xe,Be,be;if(!W)return;xl();let d=(U=o.voiceRecognition)!=null?U:{},g=q.getVoiceInterruptionMode(),h=(_=d.processingIconName)!=null?_:"loader",w=(oe=(re=d.processingIconColor)!=null?re:it==null?void 0:it.color)!=null?oe:"",P=(xe=(Z=d.processingBackgroundColor)!=null?Z:it==null?void 0:it.backgroundColor)!=null?xe:"",N=(be=(Be=d.processingBorderColor)!=null?Be:it==null?void 0:it.borderColor)!=null?be:"";qs(),W.classList.add("persona-voice-processing"),W.style.backgroundColor=P,W.style.borderColor=N;let $=w||"currentColor";W.style.color=$,yl(h,$),W.setAttribute("aria-label","Processing voice input"),g==="none"&&(W.style.cursor="default")},ny=()=>{var re,oe,Z,xe,Be,be,Ze,qe,lt,et,ke,Te;if(!W)return;xl();let d=(re=o.voiceRecognition)!=null?re:{},g=q.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",w=(oe=d.speakingIconName)!=null?oe:h,P=(be=d.speakingIconColor)!=null?be:g==="barge-in"?(xe=(Z=d.recordingIconColor)!=null?Z:it==null?void 0:it.color)!=null?xe:"":(Be=it==null?void 0:it.color)!=null?Be:"",N=(lt=d.speakingBackgroundColor)!=null?lt:g==="barge-in"?(Ze=d.recordingBackgroundColor)!=null?Ze:"var(--persona-voice-recording-bg, #ef4444)":(qe=it==null?void 0:it.backgroundColor)!=null?qe:"",$=(Te=d.speakingBorderColor)!=null?Te:g==="barge-in"?(et=d.recordingBorderColor)!=null?et:"":(ke=it==null?void 0:it.borderColor)!=null?ke:"";qs(),W.classList.add("persona-voice-speaking"),W.style.backgroundColor=N,W.style.borderColor=$;let U=P||"currentColor";W.style.color=U,yl(w,U);let _=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";W.setAttribute("aria-label",_),g==="none"&&(W.style.cursor="default"),g==="barge-in"&&W.classList.add("persona-voice-recording")},Xo=()=>{var d,g,h;W&&(qs(),it&&(W.style.backgroundColor=(d=it.backgroundColor)!=null?d:"",W.style.color=(g=it.color)!=null?g:"",W.style.borderColor=(h=it.borderColor)!=null?h:"",yl(it.iconName,it.color||"currentColor"),it=null),W.style.cursor="",W.setAttribute("aria-label","Start voice recognition"))},Vs=()=>{var d,g;if(((g=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:g.type)==="runtype"){let h=q.getVoiceStatus(),w=q.getVoiceInterruptionMode();if(w==="none"&&(h==="processing"||h==="speaking"))return;if(w==="cancel"&&(h==="processing"||h==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{dt.active=!1,dt.manuallyDeactivated=!0,Or(),ao("user"),Xo()});return}q.toggleVoice().then(()=>{dt.active=q.isVoiceActive(),dt.manuallyDeactivated=!q.isVoiceActive(),Or(),ao("user"),q.isVoiceActive()?va():Xo()});return}if(Bo){let h=Ae.value.trim();dt.manuallyDeactivated=!0,Or(),gn("user"),h&&(Ae.value="",Ae.style.height="auto",q.sendMessage(h))}else dt.manuallyDeactivated=!1,Or(),Us("user")};Ao=Vs,W&&(W.addEventListener("click",Vs),pt.push(()=>{var d,g;((g=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:g.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Xo()):gn("system"),W&&W.removeEventListener("click",Vs)}));let ay=i.on("assistant:complete",()=>{Ga&&(dt.active||dt.manuallyDeactivated||Ga==="assistant"&&!dt.lastUserMessageWasVoice||setTimeout(()=>{var d,g;!dt.active&&!dt.manuallyDeactivated&&(((g=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{dt.active=q.isVoiceActive(),ao("auto"),q.isVoiceActive()&&va()}):Us("auto"))},600))});pt.push(ay);let sy=i.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});pt.push(sy);let Vp=()=>{zt(!O,"user")},tr=null,dr=null;if(T&&!R()){let{instance:d,element:g}=ep({config:o,plugins:n,onToggle:Vp});tr=d,d||(dr=g)}tr?e.appendChild(tr.element):dr&&e.appendChild(dr),Ya(),pa(),Bp(),ul(q.isStreaming()),vt()==="follow"?Zt(!0):Ir(),xa(),S&&(!T||R()?setTimeout(()=>fl(),0):O&&setTimeout(()=>fl(),200));let Za=()=>{var _,re,oe,Z,xe,Be,be,Ze,qe,lt,et,ke,Te,Ve,Ge,ft,B,Pe,Le,ue,Ft,Wt;if(R()){Lr(),Ya();return}let d=sr(o),g=(re=(_=o.launcher)==null?void 0:_.sidebarMode)!=null?re:!1,h=d||g||((Z=(oe=o.launcher)==null?void 0:oe.fullHeight)!=null?Z:!1),w=(xe=e.ownerDocument.defaultView)!=null?xe:window,P=(be=(Be=o.launcher)==null?void 0:Be.mobileFullscreen)!=null?be:!0,N=(qe=(Ze=o.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?qe:640,$=w.innerWidth<=N,U=P&&$&&T;try{if(U){Eo(),kn(e,o);return}if(H&&(H=!1,Eo(),kn(e,o)),!T&&!d){G.style.height="",G.style.width="";return}if(!g&&!d){let Xt=(et=(lt=o==null?void 0:o.launcher)==null?void 0:lt.width)!=null?et:o==null?void 0:o.launcherWidth,mt=Xt!=null?Xt:Zr;G.style.width=mt,G.style.maxWidth=mt}if(he(),!h){let Xt=w.innerHeight,mt=64,$t=(Te=(ke=o.launcher)==null?void 0:ke.heightOffset)!=null?Te:0,Xr=Math.max(200,Xt-mt),rr=Math.min(640,Xr),Ke=Math.max(200,rr-$t);G.style.height=`${Ke}px`}}finally{if(Lr(),Ya(),O&&T){let mt=((Ve=e.ownerDocument.defaultView)!=null?Ve:window).innerWidth<=((ft=(Ge=o.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?ft:640),$t=(Pe=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Pe:!1,Xr=(ue=(Le=o.launcher)==null?void 0:Le.mobileFullscreen)!=null?ue:!0,rr=sr(o)&&Xr&&mt,Ke=$t||Xr&&mt&&T||rr;if(Ke&&!lr){let Tt=e.getRootNode(),ar=Tt instanceof ShadowRoot?Tt.host:e.closest(".persona-host");ar&&!ir&&(ir=Kc(ar,(Wt=(Ft=o.launcher)==null?void 0:Ft.zIndex)!=null?Wt:Tr)),lr=Xc(e.ownerDocument)}else Ke||(ir==null||ir(),ir=null,lr==null||lr(),lr=null)}}};Za();let zp=(Gu=e.ownerDocument.defaultView)!=null?Gu:window;if(zp.addEventListener("resize",Za),pt.push(()=>zp.removeEventListener("resize",Za)),typeof ResizeObserver!="undefined"){let d=new ResizeObserver(()=>{Lr()});d.observe(Ee),pt.push(()=>d.disconnect())}Gr=we.scrollTop;let $p=tn(we),iy=()=>{let d=we.getRootNode(),g=typeof d.getSelection=="function"?d.getSelection():null;return g!=null?g:we.ownerDocument.getSelection()},bl=()=>mh(iy(),we),jp=()=>{let d=we.scrollTop,g=tn(we),h=g<$p;if($p=g,vt()!=="follow"){Gr=d,Kr();return}let{action:w,nextLastScrollTop:P}=Bi({following:jr.isFollowing(),currentScrollTop:d,lastScrollTop:Gr,nearBottom:ra(we,ga),userScrollThreshold:Ns,isAutoScrolling:xo||Nn||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Gr=P,w==="resume"){bl()||gr();return}w==="pause"&&Wo()};if(we.addEventListener("scroll",jp,{passive:!0}),pt.push(()=>we.removeEventListener("scroll",jp)),typeof ResizeObserver!="undefined"){let d=new ResizeObserver(()=>{zx()});d.observe(Qe),d.observe(we),pt.push(()=>d.disconnect())}let Gp=()=>{vt()==="follow"&&jr.isFollowing()&&bl()&&Wo()},Kp=we.ownerDocument;Kp.addEventListener("selectionchange",Gp),pt.push(()=>{Kp.removeEventListener("selectionchange",Gp)});let Xp=d=>{if(vt()!=="follow")return;let g=Di({following:jr.isFollowing(),deltaY:d.deltaY,nearBottom:ra(we,ga),resumeWhenNearBottom:!0});g==="pause"?Wo():g==="resume"&&!bl()&&gr()};we.addEventListener("wheel",Xp,{passive:!0}),pt.push(()=>we.removeEventListener("wheel",Xp)),_t.addEventListener("click",()=>{Sr(),we.scrollTop=we.scrollHeight,Gr=we.scrollTop,gr(),Zt(!0),Kr()}),pt.push(()=>_t.remove()),pt.push(()=>{ge(),Sr()});let Jp=()=>{j&&(Lo&&(j.removeEventListener("click",Lo),Lo=null),D()?(j.style.display="",Lo=()=>{zt(!1,"user")},j.addEventListener("click",Lo)):j.style.display="none")};Jp(),(()=>{let{clearChatButton:d}=$e;d&&d.addEventListener("click",()=>{q.clearMessages(),Ro.clear(),gr(),Sn($e.composerOverlay);try{localStorage.removeItem(za),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${za}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==za)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),l!=null&&l.clear)try{let h=l.clear();h instanceof Promise&&h.catch(w=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},A.syncFromMetadata(),K==null||K.clear(),J==null||J.reset(),Se==null||Se.update()})})(),Dt&&Dt.addEventListener("submit",Fp),Ae==null||Ae.addEventListener("keydown",Op),Ae==null||Ae.addEventListener("input",Np),Ae==null||Ae.addEventListener("paste",Up);let Qp=(Ku=e.ownerDocument)!=null?Ku:document;Qp.addEventListener("keydown",_p,!0);let Yp="persona-attachment-drop-active",es=0,vl=()=>{es=0,ye.classList.remove(Yp)},Ca=()=>{var d;return((d=o.attachments)==null?void 0:d.enabled)===!0&&Ct!==null},Zp=d=>{!ll(d.dataTransfer)||!Ca()||(es++,es===1&&ye.classList.add(Yp))},eu=d=>{!ll(d.dataTransfer)||!Ca()||(es--,es<=0&&vl())},tu=d=>{!ll(d.dataTransfer)||!Ca()||(d.preventDefault(),d.dataTransfer.dropEffect="copy")},ru=d=>{var h;if(!ll(d.dataTransfer)||!Ca())return;d.preventDefault(),d.stopPropagation(),vl();let g=Array.from((h=d.dataTransfer.files)!=null?h:[]);g.length!==0&&Ct.handleFiles(g)},hn=!0;ye.addEventListener("dragenter",Zp,hn),ye.addEventListener("dragleave",eu,hn),e.addEventListener("dragover",tu,hn),e.addEventListener("drop",ru,hn);let zs=e.ownerDocument,ou=d=>{Ca()&&d.preventDefault()},nu=d=>{Ca()&&d.preventDefault()};zs.addEventListener("dragover",ou),zs.addEventListener("drop",nu),pt.push(()=>{Dt&&Dt.removeEventListener("submit",Fp),Ae==null||Ae.removeEventListener("keydown",Op),Ae==null||Ae.removeEventListener("input",Np),Ae==null||Ae.removeEventListener("paste",Up),Qp.removeEventListener("keydown",_p,!0)}),pt.push(()=>{ye.removeEventListener("dragenter",Zp,hn),ye.removeEventListener("dragleave",eu,hn),e.removeEventListener("dragover",tu,hn),e.removeEventListener("drop",ru,hn),zs.removeEventListener("dragover",ou),zs.removeEventListener("drop",nu),vl()}),pt.push(()=>{q.cancel()}),tr?pt.push(()=>{tr==null||tr.destroy()}):dr&&pt.push(()=>{dr==null||dr.remove()});let nr={update(d){var Ut,hr,Qr,Fo,xr,yr,co,bn,tf,rf,of,nf,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,vf,Cf,wf,Sf,Af,Mf,Tf,Ef,kf,Lf,Pf,Rf,If,Hf,Wf,Bf,Df,Ff,Nf,Of,_f,Uf,qf,Vf,zf,$f,jf,Gf,Kf,Xf,Jf,Qf,Yf,Zf,em,tm,rm,om,nm,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,vm,Cm,wm,Sm,Am,Mm,Tm,Em,km,Lm,Pm,Rm,Im,Hm,Wm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,Vm,zm,$m,jm,Gm,Km,Xm,Jm,Qm,Ym,Zm,eg;let g=o.toolCall,h=o.messageActions,w=(Ut=o.layout)==null?void 0:Ut.messages,P=o.colorScheme,N=o.loadingIndicator,$=o.iterationDisplay,U=(hr=o.features)==null?void 0:hr.showReasoning,_=(Qr=o.features)==null?void 0:Qr.showToolCalls,re=(Fo=o.features)==null?void 0:Fo.toolCallDisplay,oe=(xr=o.features)==null?void 0:xr.reasoningDisplay;o={...o,...d},Eo(),kn(e,o),Zi(e,o),el(e,o),Nr(),o.colorScheme!==P&&ja();let Z=Is.getForInstance(o.plugins);n.length=0,n.push(...Z),T=(co=(yr=o.launcher)==null?void 0:yr.enabled)!=null?co:!0,y=(tf=(bn=o.launcher)==null?void 0:bn.autoExpand)!=null?tf:!1,Ce=(of=(rf=o.features)==null?void 0:rf.showReasoning)!=null?of:!0,Ie=(af=(nf=o.features)==null?void 0:nf.showToolCalls)!=null?af:!0,ve=(lf=(sf=o.features)==null?void 0:sf.scrollToBottom)!=null?lf:{};let xe=vt();ae=(cf=(df=o.features)==null?void 0:df.scrollBehavior)!=null?cf:{},xe!==vt()&&(Sr(),gr()),fo(),Kr();let Be=le;if(le=(uf=(pf=o.features)==null?void 0:pf.showEventStreamToggle)!=null?uf:!1,le&&!Be){if(K||(ze=new Ps(pe),K=new Ls(_e,ze),J=J!=null?J:new Rs,ze.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),q.setSSEEventCallback((te,St)=>{var jt;(jt=o.onSSEEvent)==null||jt.call(o,te,St),J==null||J.processEvent(te,St),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(St)})})),!ct&&We){let te=(mf=(ff=o.features)==null?void 0:ff.eventStream)==null?void 0:mf.classNames,St="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"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");ct=C("button",St),ct.style.width="28px",ct.style.height="28px",ct.style.color=Dr.actionIconColor,ct.type="button",ct.setAttribute("aria-label","Event Stream"),ct.title="Event Stream";let jt=fe("activity","18px","currentColor",1.5);jt&&ct.appendChild(jt);let tt=$e.clearChatButtonWrapper,kt=$e.closeButtonWrapper,cr=tt||kt;cr&&cr.parentNode===We?We.insertBefore(ct,cr):We.appendChild(ct),ct.addEventListener("click",()=>{Y?mo():qo()})}}else!le&&Be&&(mo(),ct&&(ct.remove(),ct=null),K==null||K.clear(),ze==null||ze.destroy(),K=null,ze=null,J==null||J.reset(),J=null);if(((gf=o.launcher)==null?void 0:gf.enabled)===!1&&tr&&(tr.destroy(),tr=null),((hf=o.launcher)==null?void 0:hf.enabled)===!1&&dr&&(dr.remove(),dr=null),((xf=o.launcher)==null?void 0:xf.enabled)!==!1&&!tr&&!dr){let{instance:te,element:St}=ep({config:o,plugins:n,onToggle:Vp});tr=te,te||(dr=St),e.appendChild(St)}tr&&tr.update(o),He&&((yf=o.launcher)==null?void 0:yf.title)!==void 0&&(He.textContent=o.launcher.title),Ue&&((bf=o.launcher)==null?void 0:bf.subtitle)!==void 0&&(Ue.textContent=o.launcher.subtitle);let be=(vf=o.layout)==null?void 0:vf.header;if((be==null?void 0:be.layout)!==I&&We){let te=be?Fa(o,be,{showClose:D(),onClose:()=>zt(!1,"user")}):rn({config:o,showClose:D(),onClose:()=>zt(!1,"user")});at.replaceHeader(te),We=at.header.element,de=at.header.iconHolder,He=at.header.headerTitle,Ue=at.header.headerSubtitle,j=at.header.closeButton,I=be==null?void 0:be.layout}else if(be&&(de&&(de.style.display=be.showIcon===!1?"none":""),He&&(He.style.display=be.showTitle===!1?"none":""),Ue&&(Ue.style.display=be.showSubtitle===!1?"none":""),j&&(j.style.display=be.showCloseButton===!1?"none":""),$e.clearChatButtonWrapper)){let te=be.showClearChat;if(te!==void 0){$e.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:St}=$e;St&&!St.classList.contains("persona-absolute")&&(te?St.classList.remove("persona-ml-auto"):St.classList.add("persona-ml-auto"))}}let qe=((Cf=o.layout)==null?void 0:Cf.showHeader)!==!1;We&&(We.style.display=qe?"":"none");let lt=((wf=o.layout)==null?void 0:wf.showFooter)!==!1;Ee&&(Ee.style.display=lt?"":"none"),Lr(),Kr(),T!==M?T?zt(y,"auto"):(O=!0,Ya()):y!==v&&zt(y,"auto"),v=y,M=T,Za(),Jp();let Te=JSON.stringify(d.toolCall)!==JSON.stringify(g),Ve=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ge=JSON.stringify((Sf=o.layout)==null?void 0:Sf.messages)!==JSON.stringify(w),ft=((Af=o.loadingIndicator)==null?void 0:Af.render)!==(N==null?void 0:N.render)||((Mf=o.loadingIndicator)==null?void 0:Mf.renderIdle)!==(N==null?void 0:N.renderIdle)||((Tf=o.loadingIndicator)==null?void 0:Tf.showBubble)!==(N==null?void 0:N.showBubble),B=o.iterationDisplay!==$,Pe=((kf=(Ef=o.features)==null?void 0:Ef.showReasoning)!=null?kf:!0)!==(U!=null?U:!0)||((Pf=(Lf=o.features)==null?void 0:Lf.showToolCalls)!=null?Pf:!0)!==(_!=null?_:!0)||JSON.stringify((Rf=o.features)==null?void 0:Rf.toolCallDisplay)!==JSON.stringify(re)||JSON.stringify((If=o.features)==null?void 0:If.reasoningDisplay)!==JSON.stringify(oe);(Te||Ve||Ge||ft||B||Pe)&&q&&(ua++,Ka(Qe,q.getMessages(),ee));let ue=(Hf=o.launcher)!=null?Hf:{},Ft=(Wf=ue.headerIconHidden)!=null?Wf:!1,Wt=(Df=(Bf=o.layout)==null?void 0:Bf.header)==null?void 0:Df.showIcon,Xt=Ft||Wt===!1,mt=ue.headerIconName,$t=(Ff=ue.headerIconSize)!=null?Ff:"48px";if(de){let te=ye.querySelector(".persona-border-b-persona-divider"),St=te==null?void 0:te.querySelector(".persona-flex-col");if(Xt)de.style.display="none",te&&St&&!te.contains(St)&&te.insertBefore(St,te.firstChild);else{if(de.style.display="",de.style.height=$t,de.style.width=$t,te&&St&&(te.contains(de)?de.nextSibling!==St&&(de.remove(),te.insertBefore(de,St)):te.insertBefore(de,St)),mt){let tt=parseFloat($t)||24,kt=fe(mt,tt*.6,"currentColor",1);kt?de.replaceChildren(kt):de.textContent=(Nf=ue.agentIconText)!=null?Nf:"\u{1F4AC}"}else if(ue.iconUrl){let tt=de.querySelector("img");if(tt)tt.src=ue.iconUrl,tt.style.height=$t,tt.style.width=$t;else{let kt=document.createElement("img");kt.src=ue.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=$t,kt.style.width=$t,de.replaceChildren(kt)}}else{let tt=de.querySelector("svg"),kt=de.querySelector("img");(tt||kt)&&de.replaceChildren(),de.textContent=(Of=ue.agentIconText)!=null?Of:"\u{1F4AC}"}let jt=de.querySelector("img");jt&&(jt.style.height=$t,jt.style.width=$t)}}let Xr=(Uf=(_f=o.layout)==null?void 0:_f.header)==null?void 0:Uf.showTitle,rr=(Vf=(qf=o.layout)==null?void 0:qf.header)==null?void 0:Vf.showSubtitle;if(He&&(He.style.display=Xr===!1?"none":""),Ue&&(Ue.style.display=rr===!1?"none":""),j){(($f=(zf=o.layout)==null?void 0:zf.header)==null?void 0:$f.showCloseButton)===!1?j.style.display="none":j.style.display="";let St=(jf=ue.closeButtonSize)!=null?jf:"32px",jt=(Gf=ue.closeButtonPlacement)!=null?Gf:"inline";j.style.height=St,j.style.width=St;let{closeButtonWrapper:tt}=$e,kt=jt==="top-right",cr=tt==null?void 0:tt.classList.contains("persona-absolute");if(tt&&kt!==cr)if(tt.remove(),kt)tt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ye.style.position="relative",ye.appendChild(tt);else{let nt=(Xf=(Kf=ue.clearChat)==null?void 0:Kf.placement)!=null?Xf:"inline",pr=(Qf=(Jf=ue.clearChat)==null?void 0:Jf.enabled)!=null?Qf:!0;tt.className=pr&&nt==="inline"?"":"persona-ml-auto";let _r=ye.querySelector(".persona-border-b-persona-divider");_r&&_r.appendChild(tt)}if(j.style.color=ue.closeButtonColor||Dr.actionIconColor,ue.closeButtonBackgroundColor?(j.style.backgroundColor=ue.closeButtonBackgroundColor,j.classList.remove("hover:persona-bg-gray-100")):(j.style.backgroundColor="",j.classList.add("hover:persona-bg-gray-100")),ue.closeButtonBorderWidth||ue.closeButtonBorderColor){let nt=ue.closeButtonBorderWidth||"0px",pr=ue.closeButtonBorderColor||"transparent";j.style.border=`${nt} solid ${pr}`,j.classList.remove("persona-border-none")}else j.style.border="",j.classList.add("persona-border-none");ue.closeButtonBorderRadius?(j.style.borderRadius=ue.closeButtonBorderRadius,j.classList.remove("persona-rounded-full")):(j.style.borderRadius="",j.classList.add("persona-rounded-full")),ue.closeButtonPaddingX?(j.style.paddingLeft=ue.closeButtonPaddingX,j.style.paddingRight=ue.closeButtonPaddingX):(j.style.paddingLeft="",j.style.paddingRight=""),ue.closeButtonPaddingY?(j.style.paddingTop=ue.closeButtonPaddingY,j.style.paddingBottom=ue.closeButtonPaddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Ar=(Yf=ue.closeButtonIconName)!=null?Yf:"x",bo=(Zf=ue.closeButtonIconText)!=null?Zf:"\xD7";j.innerHTML="";let Wr=fe(Ar,"28px","currentColor",1);Wr?j.appendChild(Wr):j.textContent=bo;let er=(em=ue.closeButtonTooltipText)!=null?em:"Close chat",Yr=(tm=ue.closeButtonShowTooltip)!=null?tm:!0;if(j.setAttribute("aria-label",er),tt&&(tt._cleanupTooltip&&(tt._cleanupTooltip(),delete tt._cleanupTooltip),Yr&&er)){let nt=null,pr=()=>{if(nt||!j)return;let $n=j.ownerDocument,ts=$n.body;if(!ts)return;nt=Oo($n,"div","persona-clear-chat-tooltip"),nt.textContent=er;let rs=Oo($n,"div");rs.className="persona-clear-chat-tooltip-arrow",nt.appendChild(rs);let jn=j.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Ln),nt.style.left=`${jn.left+jn.width/2}px`,nt.style.top=`${jn.top-8}px`,nt.style.transform="translate(-50%, -100%)",ts.appendChild(nt)},_r=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};tt.addEventListener("mouseenter",pr),tt.addEventListener("mouseleave",_r),j.addEventListener("focus",pr),j.addEventListener("blur",_r),tt._cleanupTooltip=()=>{_r(),tt&&(tt.removeEventListener("mouseenter",pr),tt.removeEventListener("mouseleave",_r)),j&&(j.removeEventListener("focus",pr),j.removeEventListener("blur",_r))}}}let{clearChatButton:Ke,clearChatButtonWrapper:Tt}=$e;if(Ke){let te=(rm=ue.clearChat)!=null?rm:{},St=(om=te.enabled)!=null?om:!0,jt=(am=(nm=o.layout)==null?void 0:nm.header)==null?void 0:am.showClearChat,tt=jt!==void 0?jt:St,kt=(sm=te.placement)!=null?sm:"inline";if(Tt){Tt.style.display=tt?"":"none";let{closeButtonWrapper:cr}=$e;!R()&&cr&&!cr.classList.contains("persona-absolute")&&(tt?cr.classList.remove("persona-ml-auto"):cr.classList.add("persona-ml-auto"));let Ar=kt==="top-right",bo=Tt.classList.contains("persona-absolute");if(!R()&&Ar!==bo&&tt){if(Tt.remove(),Ar)Tt.className="persona-absolute persona-top-4 persona-z-50",Tt.style.right="48px",ye.style.position="relative",ye.appendChild(Tt);else{Tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Tt.style.right="";let er=ye.querySelector(".persona-border-b-persona-divider"),Yr=$e.closeButtonWrapper;er&&Yr&&Yr.parentElement===er?er.insertBefore(Tt,Yr):er&&er.appendChild(Tt)}let Wr=$e.closeButtonWrapper;Wr&&!Wr.classList.contains("persona-absolute")&&(Ar?Wr.classList.add("persona-ml-auto"):Wr.classList.remove("persona-ml-auto"))}}if(tt){if(!R()){let nt=(im=te.size)!=null?im:"32px";Ke.style.height=nt,Ke.style.width=nt}let cr=(lm=te.iconName)!=null?lm:"refresh-cw",Ar=(dm=te.iconColor)!=null?dm:"";Ke.style.color=Ar||Dr.actionIconColor,Ke.innerHTML="";let bo=R()?"14px":"20px",Wr=fe(cr,bo,"currentColor",2);if(Wr&&Ke.appendChild(Wr),te.backgroundColor?(Ke.style.backgroundColor=te.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let nt=te.borderWidth||"0px",pr=te.borderColor||"transparent";Ke.style.border=`${nt} solid ${pr}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");te.borderRadius?(Ke.style.borderRadius=te.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),te.paddingX?(Ke.style.paddingLeft=te.paddingX,Ke.style.paddingRight=te.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),te.paddingY?(Ke.style.paddingTop=te.paddingY,Ke.style.paddingBottom=te.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let er=(cm=te.tooltipText)!=null?cm:"Clear chat",Yr=(pm=te.showTooltip)!=null?pm:!0;if(Ke.setAttribute("aria-label",er),Tt&&(Tt._cleanupTooltip&&(Tt._cleanupTooltip(),delete Tt._cleanupTooltip),Yr&&er)){let nt=null,pr=()=>{if(nt||!Ke)return;let $n=Ke.ownerDocument,ts=$n.body;if(!ts)return;nt=Oo($n,"div","persona-clear-chat-tooltip"),nt.textContent=er;let rs=Oo($n,"div");rs.className="persona-clear-chat-tooltip-arrow",nt.appendChild(rs);let jn=Ke.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Ln),nt.style.left=`${jn.left+jn.width/2}px`,nt.style.top=`${jn.top-8}px`,nt.style.transform="translate(-50%, -100%)",ts.appendChild(nt)},_r=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Tt.addEventListener("mouseenter",pr),Tt.addEventListener("mouseleave",_r),Ke.addEventListener("focus",pr),Ke.addEventListener("blur",_r),Tt._cleanupTooltip=()=>{_r(),Tt&&(Tt.removeEventListener("mouseenter",pr),Tt.removeEventListener("mouseleave",_r)),Ke&&(Ke.removeEventListener("focus",pr),Ke.removeEventListener("blur",_r))}}}}let ar=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Hs],lo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[da.message,da.messageAndClick];A=Ws({parsers:ar,handlers:lo,getSessionMetadata:x,updateSessionMetadata:b,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),ee=ax(o,A,ce),q.updateConfig(o),Ka(Qe,q.getMessages(),ee),pa(),Bp(),ul(q.isStreaming());let Jr=((um=o.voiceRecognition)==null?void 0:um.enabled)===!0,Un=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),qn=((mm=(fm=o.voiceRecognition)==null?void 0:fm.provider)==null?void 0:mm.type)==="runtype";if(Jr&&(Un||qn))if(!W||!ne){let te=ry(o.voiceRecognition,o.sendButton);te&&(W=te.micButton,ne=te.micButtonWrapper,gt.insertBefore(ne,fr),W.addEventListener("click",Vs),W.disabled=q.isStreaming())}else{let te=(gm=o.voiceRecognition)!=null?gm:{},St=(hm=o.sendButton)!=null?hm:{},jt=(xm=te.iconName)!=null?xm:"mic",tt=(ym=St.size)!=null?ym:"40px",kt=(bm=te.iconSize)!=null?bm:tt,cr=parseFloat(kt)||24;W.style.width=kt,W.style.height=kt,W.style.minWidth=kt,W.style.minHeight=kt;let Ar=(Cm=(vm=te.iconColor)!=null?vm:St.textColor)!=null?Cm:"currentColor";W.innerHTML="";let bo=fe(jt,cr,Ar,2);bo?W.appendChild(bo):W.textContent="\u{1F3A4}";let Wr=(wm=te.backgroundColor)!=null?wm:St.backgroundColor;Wr?W.style.backgroundColor=Wr:W.style.backgroundColor="",Ar?W.style.color=Ar:W.style.color="var(--persona-text, #111827)",te.borderWidth?(W.style.borderWidth=te.borderWidth,W.style.borderStyle="solid"):(W.style.borderWidth="",W.style.borderStyle=""),te.borderColor?W.style.borderColor=te.borderColor:W.style.borderColor="",te.paddingX?(W.style.paddingLeft=te.paddingX,W.style.paddingRight=te.paddingX):(W.style.paddingLeft="",W.style.paddingRight=""),te.paddingY?(W.style.paddingTop=te.paddingY,W.style.paddingBottom=te.paddingY):(W.style.paddingTop="",W.style.paddingBottom="");let er=ne==null?void 0:ne.querySelector(".persona-send-button-tooltip"),Yr=(Sm=te.tooltipText)!=null?Sm:"Start voice recognition";if(((Am=te.showTooltip)!=null?Am:!1)&&Yr)if(er)er.textContent=Yr,er.style.display="";else{let pr=document.createElement("div");pr.className="persona-send-button-tooltip",pr.textContent=Yr,ne==null||ne.insertBefore(pr,W)}else er&&(er.style.display="none");ne.style.display="",W.disabled=q.isStreaming()}else W&&ne&&(ne.style.display="none",((Tm=(Mm=o.voiceRecognition)==null?void 0:Mm.provider)==null?void 0:Tm.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():Bo&&gn());if(((Em=o.attachments)==null?void 0:Em.enabled)===!0)if(!Mt||!Me){let te=(km=o.attachments)!=null?km:{},jt=(Pm=((Lm=o.sendButton)!=null?Lm:{}).size)!=null?Pm:"40px";Vt||(Vt=C("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Vt.style.display="none",Dt.insertBefore(Vt,Ae)),Ye||(Ye=document.createElement("input"),Ye.type="file",Ye.accept=((Rm=te.allowedTypes)!=null?Rm:en).join(","),Ye.multiple=((Im=te.maxFiles)!=null?Im:4)>1,Ye.style.display="none",Ye.setAttribute("aria-label","Attach files"),Dt.insertBefore(Ye,Ae)),Mt=C("div","persona-send-button-wrapper"),Me=C("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Me.type="button",Me.setAttribute("aria-label",(Hm=te.buttonTooltipText)!=null?Hm:"Attach file");let tt=(Wm=te.buttonIconName)!=null?Wm:"paperclip",kt=jt,cr=parseFloat(kt)||40,Ar=Math.round(cr*.6);Me.style.width=kt,Me.style.height=kt,Me.style.minWidth=kt,Me.style.minHeight=kt,Me.style.fontSize="18px",Me.style.lineHeight="1",Me.style.backgroundColor="transparent",Me.style.color="var(--persona-primary, #111827)",Me.style.border="none",Me.style.borderRadius="6px",Me.style.transition="background-color 0.15s ease",Me.addEventListener("mouseenter",()=>{Me.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Me.addEventListener("mouseleave",()=>{Me.style.backgroundColor="transparent"});let bo=fe(tt,Ar,"currentColor",1.5);bo?Me.appendChild(bo):Me.textContent="\u{1F4CE}",Me.addEventListener("click",Yr=>{Yr.preventDefault(),Ye==null||Ye.click()}),Mt.appendChild(Me);let Wr=(Bm=te.buttonTooltipText)!=null?Bm:"Attach file",er=C("div","persona-send-button-tooltip");er.textContent=Wr,Mt.appendChild(er),Pt.append(Mt),!Ct&&Ye&&Vt&&(Ct=ta.fromConfig(te),Ct.setPreviewsContainer(Vt),Ye.addEventListener("change",async()=>{Ct&&(Ye!=null&&Ye.files)&&(await Ct.handleFileSelect(Ye.files),Ye.value="")})),ye.querySelector(".persona-attachment-drop-overlay")||ye.appendChild(sx(te.dropOverlay))}else{Mt.style.display="";let te=(Dm=o.attachments)!=null?Dm:{};Ye&&(Ye.accept=((Fm=te.allowedTypes)!=null?Fm:en).join(","),Ye.multiple=((Nm=te.maxFiles)!=null?Nm:4)>1),Ct&&Ct.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else Mt&&(Mt.style.display="none"),Ct&&Ct.clearAttachments(),(Om=ye.querySelector(".persona-attachment-drop-overlay"))==null||Om.remove();let Jt=(_m=o.sendButton)!=null?_m:{},Vn=(Um=Jt.useIcon)!=null?Um:!1,xn=(qm=Jt.iconText)!=null?qm:"\u2191",yn=Jt.iconName,Jo=(Vm=Jt.tooltipText)!=null?Vm:"Send message",zn=(zm=Jt.showTooltip)!=null?zm:!1,yo=($m=Jt.size)!=null?$m:"40px",Do=Jt.backgroundColor,Je=Jt.textColor;if(Vn){if(Oe.style.width=yo,Oe.style.height=yo,Oe.style.minWidth=yo,Oe.style.minHeight=yo,Oe.style.fontSize="18px",Oe.style.lineHeight="1",Oe.innerHTML="",Je?Oe.style.color=Je:Oe.style.color="var(--persona-button-primary-fg, #ffffff)",yn){let te=parseFloat(yo)||24,St=(Je==null?void 0:Je.trim())||"currentColor",jt=fe(yn,te,St,2);jt?Oe.appendChild(jt):Oe.textContent=xn}else Oe.textContent=xn;Oe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Do?(Oe.style.backgroundColor=Do,Oe.classList.remove("persona-bg-persona-primary")):(Oe.style.backgroundColor="",Oe.classList.add("persona-bg-persona-primary"))}else Oe.textContent=(Gm=(jm=o.copy)==null?void 0:jm.sendButtonLabel)!=null?Gm:"Send",Oe.style.width="",Oe.style.height="",Oe.style.minWidth="",Oe.style.minHeight="",Oe.style.fontSize="",Oe.style.lineHeight="",Oe.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",Do?(Oe.style.backgroundColor=Do,Oe.classList.remove("persona-bg-persona-accent")):Oe.classList.add("persona-bg-persona-accent"),Je?Oe.style.color=Je:Oe.classList.add("persona-text-white");Jt.borderWidth?(Oe.style.borderWidth=Jt.borderWidth,Oe.style.borderStyle="solid"):(Oe.style.borderWidth="",Oe.style.borderStyle=""),Jt.borderColor?Oe.style.borderColor=Jt.borderColor:Oe.style.borderColor="",Jt.paddingX?(Oe.style.paddingLeft=Jt.paddingX,Oe.style.paddingRight=Jt.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),Jt.paddingY?(Oe.style.paddingTop=Jt.paddingY,Oe.style.paddingBottom=Jt.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let Nt=fr==null?void 0:fr.querySelector(".persona-send-button-tooltip");if(zn&&Jo)if(Nt)Nt.textContent=Jo,Nt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=Jo,fr==null||fr.insertBefore(te,Oe)}else Nt&&(Nt.style.display="none");let Kt=(Ym=(Km=o.layout)==null?void 0:Km.contentMaxWidth)!=null?Ym:R()?(Qm=(Jm=(Xm=o.launcher)==null?void 0:Xm.composerBar)==null?void 0:Jm.contentMaxWidth)!=null?Qm:"720px":void 0;Kt?(Qe.style.maxWidth=Kt,Qe.style.marginLeft="auto",Qe.style.marginRight="auto",Qe.style.width="100%",Dt&&(Dt.style.maxWidth=Kt,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),Xe&&(Xe.style.maxWidth=Kt,Xe.style.marginLeft="auto",Xe.style.marginRight="auto")):(Qe.style.maxWidth="",Qe.style.marginLeft="",Qe.style.marginRight="",Qe.style.width="",Dt&&(Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight=""),Xe&&(Xe.style.maxWidth="",Xe.style.marginLeft="",Xe.style.marginRight=""));let Ot=(Zm=o.statusIndicator)!=null?Zm:{},Qt=(eg=Ot.visible)!=null?eg:!0;if(Yt.style.display=Qt?"":"none",q){let te=q.getStatus();Gt(Yt,(jt=>{var tt,kt,cr,Ar;return jt==="idle"?(tt=Ot.idleText)!=null?tt:Mr.idle:jt==="connecting"?(kt=Ot.connectingText)!=null?kt:Mr.connecting:jt==="connected"?(cr=Ot.connectedText)!=null?cr:Mr.connected:jt==="error"?(Ar=Ot.errorText)!=null?Ar:Mr.error:Mr[jt]})(te),Ot,te)}Yt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Et=Ot.align==="left"?"persona-text-left":Ot.align==="center"?"persona-text-center":"persona-text-right";Yt.classList.add(Et)},open(){D()&&zt(!0,"api")},close(){D()&&zt(!1,"api")},toggle(){D()&&zt(!O,"api")},clearChat(){Pr=!1,q.clearMessages(),Ro.clear(),gr();try{localStorage.removeItem(za),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${za}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==za)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let d=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(d),l!=null&&l.clear)try{let g=l.clear();g instanceof Promise&&g.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}p={},A.syncFromMetadata(),K==null||K.clear(),J==null||J.reset(),Se==null||Se.update()},setMessage(d){return!Ae||q.isStreaming()?!1:(!O&&D()&&zt(!0,"system"),Ae.value=d,Ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(d){if(q.isStreaming())return!1;let g=(d==null?void 0:d.trim())||Ae.value.trim();return g?(!O&&D()&&zt(!0,"system"),Ae.value="",Ae.style.height="auto",q.sendMessage(g),!0):!1},startVoiceRecognition(){var g,h;return q.isStreaming()?!1:((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype"?(q.isVoiceActive()||(!O&&D()&&zt(!0,"system"),dt.manuallyDeactivated=!1,Or(),q.toggleVoice().then(()=>{dt.active=q.isVoiceActive(),ao("user"),q.isVoiceActive()&&va()})),!0):Bo?!0:qp()?(!O&&D()&&zt(!0,"system"),dt.manuallyDeactivated=!1,Or(),Us("user"),!0):!1},stopVoiceRecognition(){var d,g;return((g=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:g.type)==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{dt.active=!1,dt.manuallyDeactivated=!0,Or(),ao("user"),Xo()}),!0):!1:Bo?(dt.manuallyDeactivated=!0,Or(),gn("user"),!0):!1},injectMessage(d){return!O&&D()&&zt(!0,"system"),q.injectMessage(d)},injectAssistantMessage(d){!O&&D()&&zt(!0,"system");let g=q.injectAssistantMessage(d);return Q&&(Q=!1,me&&(clearTimeout(me),me=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(d){return!O&&D()&&zt(!0,"system"),q.injectUserMessage(d)},injectSystemMessage(d){return!O&&D()&&zt(!0,"system"),q.injectSystemMessage(d)},injectMessageBatch(d){return!O&&D()&&zt(!0,"system"),q.injectMessageBatch(d)},injectComponentDirective(d){return!O&&D()&&zt(!0,"system"),q.injectComponentDirective(d)},injectTestMessage(d){!O&&D()&&zt(!0,"system"),q.injectTestEvent(d)},async connectStream(d,g){return q.connectStream(d,g)},__pushEventStreamEvent(d){K&&(J==null||J.processEvent(d.type,d.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:d.type,timestamp:Date.now(),payload:JSON.stringify(d.payload)}))},showEventStream(){!le||!K||qo()},hideEventStream(){Y&&mo()},isEventStreamVisible(){return Y},showArtifacts(){uo(o)&&(Pr=!1,Nr(),ht==null||ht.setMobileOpen(!0))},hideArtifacts(){uo(o)&&(Pr=!0,Nr())},upsertArtifact(d){return uo(o)?(Pr=!1,q.upsertArtifact(d)):null},selectArtifact(d){uo(o)&&q.selectArtifact(d)},clearArtifacts(){uo(o)&&q.clearArtifacts()},getArtifacts(){var d;return(d=q==null?void 0:q.getArtifacts())!=null?d:[]},getSelectedArtifactId(){var d;return(d=q==null?void 0:q.getSelectedArtifactId())!=null?d:null},focusInput(){return T&&!O&&!R()||!Ae?!1:(Ae.focus(),!0)},async resolveApproval(d,g,h){let P=q.getMessages().find(N=>{var $;return N.variant==="approval"&&(($=N.approval)==null?void 0:$.id)===d});if(!(P!=null&&P.approval))throw new Error(`Approval not found: ${d}`);if(P.approval.toolType==="webmcp"){q.resolveWebMcpApproval(P.id,g);return}return q.resolveApproval(P.approval,g,h)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(d){b(d)},on(d,g){return i.on(d,g)},off(d,g){i.off(d,g)},isOpen(){return D()&&O},isVoiceActive(){return dt.active},toggleReadAloud(d){q.toggleReadAloud(d)},stopReadAloud(){q.stopSpeaking()},getReadAloudState(d){return q.getReadAloudState(d)},onReadAloudChange(d){return q.onReadAloudChange(d)},getState(){return{open:D()&&O,launcherEnabled:T,voiceActive:dt.active,streaming:q.isStreaming()}},showCSATFeedback(d){!O&&D()&&zt(!0,"system");let g=Qe.querySelector(".persona-feedback-container");g&&g.remove();let h=sl({onSubmit:async(w,P)=>{var N;q.isClientTokenMode()&&await q.submitCSATFeedback(w,P),(N=d==null?void 0:d.onSubmit)==null||N.call(d,w,P)},onDismiss:d==null?void 0:d.onDismiss,...d});Qe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(d){!O&&D()&&zt(!0,"system");let g=Qe.querySelector(".persona-feedback-container");g&&g.remove();let h=il({onSubmit:async(w,P)=>{var N;q.isClientTokenMode()&&await q.submitNPSFeedback(w,P),(N=d==null?void 0:d.onSubmit)==null||N.call(d,w,P)},onDismiss:d==null?void 0:d.onDismiss,...d});Qe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(d,g){return q.submitCSATFeedback(d,g)},async submitNPSFeedback(d,g){return q.submitNPSFeedback(d,g)},destroy(){_n!=null&&(clearInterval(_n),_n=null),pt.forEach(d=>d()),Ne.remove(),je==null||je.remove(),tr==null||tr.destroy(),dr==null||dr.remove(),Lo&&j.removeEventListener("click",Lo)}};if((((Xu=r==null?void 0:r.debugTools)!=null?Xu:!1)||!!o.debug)&&typeof window!="undefined"){let d=window.AgentWidgetBrowser,g={controller:nr,getMessages:nr.getMessages,getStatus:nr.getStatus,getMetadata:nr.getPersistentMetadata,updateMetadata:nr.updatePersistentMetadata,clearHistory:()=>nr.clearChat(),setVoiceActive:h=>h?nr.startVoiceRecognition():nr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,pt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=d)})}if(typeof window!="undefined"){let d=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&nr.focusInput()};if(window.addEventListener("persona:focusInput",g),pt.push(()=>{window.removeEventListener("persona:focusInput",g)}),le){let U=re=>{let oe=re.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===d)&&nr.showEventStream()},_=re=>{let oe=re.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===d)&&nr.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",_),pt.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",_)})}let h=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&nr.showArtifacts()},w=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&nr.hideArtifacts()},P=U=>{let _=U.detail;_!=null&&_.instanceId&&_.instanceId!==d||_!=null&&_.artifact&&nr.upsertArtifact(_.artifact)},N=U=>{let _=U.detail;_!=null&&_.instanceId&&_.instanceId!==d||typeof(_==null?void 0:_.id)=="string"&&nr.selectArtifact(_.id)},$=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&nr.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",$),pt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",$)})}let io=t0(o.persistState);if(io&&D()){let d=r0(io.storage),g=`${io.keyPrefix}widget-open`,h=`${io.keyPrefix}widget-voice`,w=`${io.keyPrefix}widget-voice-mode`;if(d){let P=((Ju=io.persist)==null?void 0:Ju.openState)&&d.getItem(g)==="true",N=((Qu=io.persist)==null?void 0:Qu.voiceState)&&d.getItem(h)==="true",$=((Yu=io.persist)==null?void 0:Yu.voiceState)&&d.getItem(w)==="true";if(P&&setTimeout(()=>{nr.open(),setTimeout(()=>{var U;if(N||$)nr.startVoiceRecognition();else if((U=io.persist)!=null&&U.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),(Zu=io.persist)!=null&&Zu.openState&&(i.on("widget:opened",()=>{d.setItem(g,"true")}),i.on("widget:closed",()=>{d.setItem(g,"false")})),(ef=io.persist)!=null&&ef.voiceState&&(i.on("voice:state",U=>{d.setItem(h,U.active?"true":"false")}),i.on("user:message",U=>{d.setItem(w,U.viaVoice?"true":"false")})),io.clearOnChatClear){let U=()=>{d.removeItem(g),d.removeItem(h),d.removeItem(w)},_=()=>U();window.addEventListener("persona:clear-chat",_),pt.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return u&&D()&&setTimeout(()=>{nr.open()},0),ya(),Fs||js().then(()=>{q&&(ua++,Ro.clear(),Ka(Qe,q.getMessages(),ee))}).catch(()=>{}),nr};var o0=(e,t)=>{let r=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(r);return n?Math.max(0,t*parseFloat(n[1])/100):420},n0=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},a0=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},s0=(e,t)=>{let r=e.parentElement;if(!r)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),!(!n||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},ix=(e,t)=>{var o,n;let r=(n=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?n:!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0"},bp=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=""},lx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",bp(e)},hp=e=>{e.style.transition=""},xp=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},yp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},cl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},i0=(e,t,r,o,n)=>{n?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,o),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(o))},l0=(e,t,r,o,n,a)=>{let s=a?t:e;n==="left"?s.firstElementChild!==o&&s.replaceChildren(o,r):s.lastElementChild!==o&&s.replaceChildren(r,o)},dx=(e,t,r,o,n,a,s)=>{var x,b,L,E,A,T;let i=eo(a),c=i.reveal==="push";i0(e,t,r,o,c),l0(e,t,r,o,i.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"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",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(b=(x=a==null?void 0:a.launcher)==null?void 0:x.mobileFullscreen)!=null?b:!0,f=(E=(L=a==null?void 0:a.launcher)==null?void 0:L.mobileBreakpoint)!=null?E:640,u=l!=null?l.innerWidth<=f:!1;if(p&&u&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),xp(t),hp(o),lx(o),yp(r),cl(n,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((T=(A=a==null?void 0:a.launcher)==null?void 0:A.zIndex)!=null?T:Tr),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),lx(o),n0(o,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",xp(t),hp(o),yp(r),cl(n,o);let y=i.animate?"transform 180ms ease":"none",S=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=s?"translateX(0)":S;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=y,o.style.transform=v,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",hp(o),bp(o),cl(n,o);let y=o0(i.width,e.clientWidth),S=Math.max(0,e.clientWidth),v=i.animate?"margin-left 180ms ease":"none",M=i.side==="right"?s?-y:0:s?0:-y;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=`${S+y}px`,t.style.transition=v,t.style.marginLeft=`${M}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${S}px`,r.style.maxWidth=`${S}px`,r.style.minWidth=`${S}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",xp(t),bp(o),yp(r),cl(n,o);let y=i.reveal==="emerge";y?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=s?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",M=!s;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",a0(o,i.maxHeight),o.style.overflow=y||M?"hidden":"visible",o.style.transition=v,y&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.boxSizing="border-box")}},d0=(e,t)=>{let r=e.ownerDocument.createElement("div");return ix(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){ix(r,o)},destroy(){r.remove()}}},c0=(e,t)=>{var T,y,S,v;let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),c=r.createElement("div"),l=r.createElement("aside"),p=r.createElement("div"),f=(y=(T=t==null?void 0:t.launcher)==null?void 0:T.enabled)==null||y?(v=(S=t==null?void 0:t.launcher)==null?void 0:S.autoExpand)!=null?v:!1:!0;i.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),o.insertBefore(s,e),c.appendChild(e);let u=null,m=()=>{u==null||u.disconnect(),u=null},x=()=>{m(),eo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{dx(s,i,c,l,p,t,f)}),u.observe(s))},b=!1,L=()=>{dx(s,i,c,l,p,t,f),x(),f&&!b&&s.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,s0(s,eo(t)))},E=s.ownerDocument.defaultView,A=()=>{L()};return E==null||E.addEventListener("resize",A),eo(t).reveal==="push"?(i.appendChild(c),i.appendChild(l),s.appendChild(i)):(s.appendChild(c),s.appendChild(l)),L(),{mode:"docked",host:p,shell:s,syncWidgetState(M){let I=M.launcherEnabled?M.open:!0;f!==I&&(f=I,L())},updateConfig(M){var I,H;t=M,((H=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)!=null?H:!0)===!1&&(f=!0),L()},destroy(){E==null||E.removeEventListener("resize",A),m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Bs=(e,t)=>sr(t)?c0(e,t):d0(e,t);var vp={},p0=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},u0=()=>{try{if(typeof vp!="undefined"&&vp.url)return new URL("../widget.css",vp.url).href}catch{}return null},cx=(e,t)=>{let r=u0(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let a=n.cloneNode(!0);e.insertBefore(a,e.firstChild)};if(e instanceof ShadowRoot)if(r){let n=t.createElement("link");n.rel="stylesheet",n.href=r,n.setAttribute("data-persona","true"),e.insertBefore(n,e.firstChild)}else o();else if(!t.head.querySelector("link[data-persona]")&&r){let a=t.createElement("link");a.rel="stylesheet",a.href=r,a.setAttribute("data-persona","true"),t.head.appendChild(a)}},px=e=>{var L;let t=p0(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Bs(t,n),s,i=[],c=(E,A)=>{var v,M;let y=!((M=(v=A==null?void 0:A.launcher)==null?void 0:v.enabled)!=null?M:!0)||sr(A),S=o.createElement("div");if(S.setAttribute("data-persona-root","true"),y&&(S.style.height="100%",S.style.display="flex",S.style.flexDirection="column",S.style.flex="1",S.style.minHeight="0"),r){let I=E.attachShadow({mode:"open"});I.appendChild(S),cx(I,o)}else E.appendChild(S),cx(E,o);return t.id&&S.setAttribute("data-persona-instance",t.id),S},l=()=>{a.syncWidgetState(s.getState())},p=()=>{i.forEach(E=>E()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},f=()=>{let E=c(a.host,n);s=dl(E,n,{debugTools:e.debugTools}),p()},u=()=>{i.forEach(E=>E()),i=[],s.destroy()};f(),(L=e.onChatReady)==null||L.call(e);let m=E=>{u(),a.destroy(),a=Bs(t,E),n=E,f()},x={update(E){var M,I,H,R,D,O;let A={...n,...E,launcher:{...(M=n==null?void 0:n.launcher)!=null?M:{},...(I=E==null?void 0:E.launcher)!=null?I:{},dock:{...(R=(H=n==null?void 0:n.launcher)==null?void 0:H.dock)!=null?R:{},...(O=(D=E==null?void 0:E.launcher)==null?void 0:D.dock)!=null?O:{}}}},T=sr(n),y=sr(A),S=Rn(n),v=Rn(A);if(T!==y||S!==v){m(A);return}n=A,a.updateConfig(n),s.update(E),l()},destroy(){u(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},b=new Proxy(x,{get(E,A,T){if(A==="host")return a.host;if(A in E)return Reflect.get(E,A,T);let y=s[A];return typeof y=="function"?y.bind(s):y}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=b),b};var hx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),f0=new Set(["button","a","input","select","textarea","details","summary"]),m0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Cp=/\b(product|card|item|listing|result)\b/i,Sp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,g0=3e3,h0=100;function xx(e){let t=typeof e.className=="string"?e.className:"";if(Cp.test(t)||e.id&&Cp.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&Cp.test(o.value))return!0}return!1}function yx(e){var t;return Sp.test(((t=e.textContent)!=null?t:"").trim())}function bx(e){var r;let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=(r=t[o].getAttribute("href"))!=null?r:"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function x0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ux(e){let t=e.match(Sp);return t?t[0]:null}function fx(e){var o,n,a;let t=(o=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?o:e.querySelector("a[href]");if(t&&((n=t.textContent)!=null&&n.trim())){let s=t.getAttribute("href");return{title:t.textContent.trim(),href:s&&s!=="#"?s:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return(a=r==null?void 0:r.textContent)!=null&&a.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function y0(e){let t=[],r=o=>{let n=o.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll("button").forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('[role="button"]').forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{var n;r((n=o.value)!=null?n:"")}),t.slice(0,6)}var b0="commerce-card",v0="result-card";function mx(e){return!xx(e)||!yx(e)||!bx(e)&&!x0(e)?0:5200}function gx(e){var o;return!xx(e)||yx(e)||!bx(e)||((o=e.textContent)!=null?o:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Ap=[{id:b0,scoreElement(e){return mx(e)},shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if(r.interactivity==="static"){let o=r.text.trim();return!!(o.length===0||Sp.test(o)&&o.length<32)}return!0},formatSummary(e,t){var c,l,p;if(mx(e)===0)return null;let{title:r,href:o}=fx(e),n=(p=(l=ux(((c=e.textContent)!=null?c:"").trim()))!=null?l:ux(t.text))!=null?p:"",a=y0(e);return[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
113
+ `)}},{id:v0,scoreElement(e){return gx(e)},formatSummary(e,t){if(gx(e)===0)return null;let{title:r,href:o}=fx(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
114
+ `)}}];function C0(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function w0(e){var p,f,u,m,x,b,L,E,A,T,y,S,v;let t=(p=e.options)!=null?p:{},r=(u=(f=t.maxElements)!=null?f:e.maxElements)!=null?u:80,o=(x=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",n=(L=(b=t.maxTextLength)!=null?b:e.maxTextLength)!=null?L:200,a=(A=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?A:!0,s=(T=t.root)!=null?T:e.root,i=(y=t.mode)!=null?y:"structured",c=(S=t.maxCandidates)!=null?S:Math.max(500,r*10),l=(v=e.rules)!=null?v:Ap;return i==="simple"&&e.rules&&e.rules.length>0?(C0(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:r,maxCandidates:c,excludeSelector:o,maxTextLength:n,visibleOnly:a,root:s,rules:l}}function wp(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var S0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function A0(e){let t=e.tagName.toLowerCase(),r=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||r==="textbox"||r==="combobox"||r==="listbox"||r==="spinbutton"?"input":t==="button"||r==="button"||f0.has(t)||r&&m0.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function vx(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 M0(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let c=e.getAttribute("role");c&&(t.role=c);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 Mp(e){let t=e.tagName.toLowerCase();if(e.id){let n=`#${wp(e.id)}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}}for(let n of S0){let a=e.getAttribute(n);if(a){let s=`${t}[${n}="${wp(a)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let r=Array.from(e.classList).filter(n=>n&&!n.startsWith("persona-")).slice(0,3);if(r.length>0){let n=`${t}.${r.map(s=>wp(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}let a=e.parentElement;if(a){let i=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let c=`${n}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let o=e.parentElement;if(o){let a=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function T0(e){return e==="static"?h0:g0}function Cx(e,t){var n;let r=e.tagName.toLowerCase(),o=((n=e.textContent)!=null?n:"").trim().substring(0,t);return{selector:Mp(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:A0(e),attributes:M0(e)}}function E0(e,t,r,o){let n=T0(t.interactivity),a=null;for(let s of r){let i=s.scoreElement(e,t,o);i>0&&(n+=i,s.formatSummary&&!a&&(a=s))}return{score:n,formattingRule:a}}function k0(e,t){var r;for(let o of e)if(t.el!==o.el&&(r=o.formattingRule)!=null&&r.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function L0(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(hx.has(p)){i=s.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!vx(l)){i=s.nextNode();continue}let f=Cx(l,e.maxTextLength),u=f.text.length>0,m=Object.keys(f.attributes).length>0&&!Object.keys(f.attributes).every(L=>L==="role");if(!u&&!m){i=s.nextNode();continue}if(o.has(f.selector)){i=s.nextNode();continue}o.add(f.selector);let{score:x,formattingRule:b}=E0(l,f,e.rules,r);n.push({el:l,domIndex:a,enriched:f,score:x,formattingRule:b}),a+=1}i=s.nextNode()}n.sort((l,p)=>{let f=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return f!==u?f-u:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let c=[];for(let l of n){if(c.length>=e.maxElements)break;k0(c,l)||c.push(l)}return c.sort((l,p)=>{let f=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return f!==u?f-u:f===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),c.map(l=>{var u;let p;if((u=l.formattingRule)!=null&&u.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,r);m&&(p=m)}let f={...l.enriched};return p&&(f.formattedSummary=p),f})}function P0(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,l=c.tagName.toLowerCase();if(hx.has(l)){a=n.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!vx(c)){a=n.nextNode();continue}let p=Cx(c,e.maxTextLength),f=p.text.length>0,u=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!f&&!u){a=n.nextNode();continue}o.has(p.selector)||(o.add(p.selector),r.push(p))}a=n.nextNode()}let s=[],i=[];for(let c of r)c.interactivity!=="static"?s.push(c):i.push(c);return[...s,...i].slice(0,e.maxElements)}function wx(e={}){var o;let t=w0(e),r=(o=t.root)!=null?o:document.body;return r?t.mode==="simple"?P0(t,r):L0(t,r):[]}var pl=100;function Sx(e,t={}){var a;if(e.length===0)return"No page elements found.";let r=(a=t.mode)!=null?a:"structured",o=[];if(r==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
113
115
  ${s.map(i=>`- ${i.split(`
114
116
  `).join(`
115
117
  `)}`).join(`
116
- `)}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let s of e)r==="structured"&&s.formattedSummary||n[s.interactivity].push(s);if(n.clickable.length>0){let s=n.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,ll)}" (clickable)`);o.push(`Interactive elements:
118
+ `)}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let s of e)r==="structured"&&s.formattedSummary||n[s.interactivity].push(s);if(n.clickable.length>0){let s=n.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,pl)}" (clickable)`);o.push(`Interactive elements:
117
119
  ${s.join(`
118
- `)}`)}if(n.navigable.length>0){let s=n.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,ll)}" (navigable)`);o.push(`Navigation links:
120
+ `)}`)}if(n.navigable.length>0){let s=n.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,pl)}" (navigable)`);o.push(`Navigation links:
119
121
  ${s.join(`
120
- `)}`)}if(n.input.length>0){let s=n.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,ll)}" (input)`);o.push(`Form inputs:
122
+ `)}`)}if(n.input.length>0){let s=n.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,pl)}" (input)`);o.push(`Form inputs:
121
123
  ${s.join(`
122
- `)}`)}if(n.static.length>0){let s=n.static.map(i=>`- ${i.selector}: "${i.text.substring(0,ll)}"`);o.push(`Content:
124
+ `)}`)}if(n.static.length>0){let s=n.static.map(i=>`- ${i.selector}: "${i.text.substring(0,pl)}"`);o.push(`Content:
123
125
  ${s.join(`
124
126
  `)}`)}return o.join(`
125
127
 
126
- `)}function fx(){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 mx(){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 gx(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var o;let r={...t.palette};return(o=e.colors)!=null&&o.primary&&(r.colors={...r.colors,primary:{50:Do(e.colors.primary,.95),100:Do(e.colors.primary,.9),200:Do(e.colors.primary,.8),300:Do(e.colors.primary,.7),400:Do(e.colors.primary,.6),500:e.colors.primary,600:Do(e.colors.primary,.8),700:Do(e.colors.primary,.7),800:Do(e.colors.primary,.6),900:Do(e.colors.primary,.5),950:Do(e.colors.primary,.45)}}),{...t,palette:r}}}}function hx(){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 xx(){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 Do(e,t){let r=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),n=parseInt(e.slice(5,7),16),a=Math.round(r+(255-r)*(1-t)),s=Math.round(o+(255-o)*(1-t)),i=Math.round(n+(255-n)*(1-t));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function yx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var d0={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"}}},bx={components:{panel:{borderRadius:"0",shadow:"none"}}},Sc={id:"shop",label:"Shopping Assistant",config:{theme:d0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Yr},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:bx}},Mc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:bx}},Tc={shop:Sc,minimal:Ac,fullscreen:Mc};function vx(e){return Tc[e]}var p0=`
128
+ `)}function Ax(){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 Mx(){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 Tx(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var o;let r={...t.palette};return(o=e.colors)!=null&&o.primary&&(r.colors={...r.colors,primary:{50:_o(e.colors.primary,.95),100:_o(e.colors.primary,.9),200:_o(e.colors.primary,.8),300:_o(e.colors.primary,.7),400:_o(e.colors.primary,.6),500:e.colors.primary,600:_o(e.colors.primary,.8),700:_o(e.colors.primary,.7),800:_o(e.colors.primary,.6),900:_o(e.colors.primary,.5),950:_o(e.colors.primary,.45)}}),{...t,palette:r}}}}function Ex(){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 kx(){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 _o(e,t){let r=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),n=parseInt(e.slice(5,7),16),a=Math.round(r+(255-r)*(1-t)),s=Math.round(o+(255-o)*(1-t)),i=Math.round(n+(255-n)*(1-t));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Lx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var R0={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"}}},Px={components:{panel:{borderRadius:"0",shadow:"none"}}},Tp={id:"shop",label:"Shopping Assistant",config:{theme:R0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Zr},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?"]}},Ep={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Px}},kp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Px}},Lp={shop:Tp,minimal:Ep,fullscreen:kp};function Rx(e){return Lp[e]}var I0=`
127
129
  @keyframes persona-stream-wipe {
128
130
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
129
131
  to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
@@ -159,7 +161,7 @@ ${s.join(`
159
161
  mask-image: none !important;
160
162
  }
161
163
  }
162
- `.trim(),c0={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:p0};ea(c0);var u0=`
164
+ `.trim(),H0={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:I0};oa(H0);var W0=`
163
165
  [data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
164
166
  animation: persona-stream-glyph-cycle-fade
165
167
  calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
@@ -177,7 +179,7 @@ ${s.join(`
177
179
  opacity: 1 !important;
178
180
  }
179
181
  }
180
- `.trim(),Rs="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",f0=10,m0=120,Ec=120,g0=.4,h0=50,x0=e=>{var o;if(!e)return Ec;let r=((o=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:o.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Ec},kx=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=x0(t);return m0*r/Ec},kc=e=>{let t=Rs[Math.floor(Math.random()*Rs.length)];return e&&t===e&&(t=Rs[(Rs.indexOf(t)+1)%Rs.length]),t},y0=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let r=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let n of Array.from(r)){if(n===e){o=!0;continue}o&&Math.random()<g0&&(n.textContent=kc())}},Cx=new WeakMap,wx=25,Sx=.5,b0=6,Ax=.25,Mx=new WeakMap,Tx=new WeakMap,v0=(e,t)=>{var n;if(!e)return wx*Sx;let r=Mx.get(e);Mx.set(e,t);let o=(n=Tx.get(e))!=null?n:wx;if(r!==void 0){let a=t-r;a>1&&(o=o*(1-Ax)+a*Ax,Tx.set(e,o))}return Math.max(b0,o*Sx)},_a=new Map,C0=e=>{var r;let t=e.closest("[data-message-id]");return(r=t==null?void 0:t.dataset.messageId)!=null?r:null},w0=e=>{var t;e&&_a.set(e,((t=_a.get(e))!=null?t:0)+1)},S0=e=>{var r;if(!e)return;let t=(r=_a.get(e))!=null?r:0;t<=1?_a.delete(e):_a.set(e,t-1)},Lx=e=>{var d;if(e.dataset.glyphCycleScheduled==="true")return;let t=(d=e.textContent)!=null?d:"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=kc();let r=C0(e);r&&(e.dataset.glyphCycleMessageId=r),w0(r);let o=e.closest(".persona-stream-glyph-cycle"),n=Date.now(),a=v0(o,n),s=kx(e),i=f0*s,p=n+i;if(o){let u=Cx.get(o);u!==void 0&&(p=Math.max(p,u)),Cx.set(o,p+a)}A0(e,t,p)},A0=(e,t,r)=>{var s;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=kx(e),n=(s=e.textContent)!=null?s:void 0,a=()=>{var p;if(!e.isConnected)return;if(Date.now()>=r){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,S0((p=e.dataset.glyphCycleMessageId)!=null?p:null),delete e.dataset.glyphCycleMessageId;return}let i=kc(n);e.textContent=i,n=i,y0(e),setTimeout(a,o)};setTimeout(a,o)},Ex=e=>{var r;let t=(r=e.querySelectorAll)==null?void 0:r.call(e,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let o of Array.from(t))Lx(o)},M0=e=>e.nodeType===1,T0={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:u0,bufferContent(e){if(e.length<h0)return"";let t=0,r=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(r=o),o+=1}return r<0?"":e.slice(0,r)},isAnimating(e){var t;return((t=_a.get(e.id))!=null?t:0)>0},onAttach(e){Ex(e);let t=new MutationObserver(r=>{for(let o of r)for(let n of Array.from(o.addedNodes))M0(n)&&(n.classList.contains("persona-stream-char")&&n.closest(".persona-stream-glyph-cycle")?Lx(n):Ex(n))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};ea(T0);var Px,Rx,Yt=typeof document!="undefined"&&(Rx=(Px=document.currentScript)==null?void 0:Px.src)!=null?Rx:null;lg(()=>{let e=Yt==null?void 0:Yt.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===Yt?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${Yt!=null?Yt:"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});eg(()=>{let e=Yt==null?void 0:Yt.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===Yt?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${Yt!=null?Yt:"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});Vs().catch(e=>{typeof console!="undefined"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});zg(()=>{let e=Yt==null?void 0:Yt.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===Yt?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${Yt!=null?Yt:"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});return ty(E0);})();
182
+ `.trim(),Ds="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",B0=10,D0=120,Pp=120,F0=.4,N0=50,O0=e=>{var o;if(!e)return Pp;let r=((o=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:o.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Pp},Ox=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=O0(t);return D0*r/Pp},Rp=e=>{let t=Ds[Math.floor(Math.random()*Ds.length)];return e&&t===e&&(t=Ds[(Ds.indexOf(t)+1)%Ds.length]),t},_0=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let r=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let n of Array.from(r)){if(n===e){o=!0;continue}o&&Math.random()<F0&&(n.textContent=Rp())}},Ix=new WeakMap,Hx=25,Wx=.5,U0=6,Bx=.25,Dx=new WeakMap,Fx=new WeakMap,q0=(e,t)=>{var n;if(!e)return Hx*Wx;let r=Dx.get(e);Dx.set(e,t);let o=(n=Fx.get(e))!=null?n:Hx;if(r!==void 0){let a=t-r;a>1&&(o=o*(1-Bx)+a*Bx,Fx.set(e,o))}return Math.max(U0,o*Wx)},$a=new Map,V0=e=>{var r;let t=e.closest("[data-message-id]");return(r=t==null?void 0:t.dataset.messageId)!=null?r:null},z0=e=>{var t;e&&$a.set(e,((t=$a.get(e))!=null?t:0)+1)},$0=e=>{var r;if(!e)return;let t=(r=$a.get(e))!=null?r:0;t<=1?$a.delete(e):$a.set(e,t-1)},_x=e=>{var l;if(e.dataset.glyphCycleScheduled==="true")return;let t=(l=e.textContent)!=null?l:"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Rp();let r=V0(e);r&&(e.dataset.glyphCycleMessageId=r),z0(r);let o=e.closest(".persona-stream-glyph-cycle"),n=Date.now(),a=q0(o,n),s=Ox(e),i=B0*s,c=n+i;if(o){let p=Ix.get(o);p!==void 0&&(c=Math.max(c,p)),Ix.set(o,c+a)}j0(e,t,c)},j0=(e,t,r)=>{var s;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=Ox(e),n=(s=e.textContent)!=null?s:void 0,a=()=>{var c;if(!e.isConnected)return;if(Date.now()>=r){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,$0((c=e.dataset.glyphCycleMessageId)!=null?c:null),delete e.dataset.glyphCycleMessageId;return}let i=Rp(n);e.textContent=i,n=i,_0(e),setTimeout(a,o)};setTimeout(a,o)},Nx=e=>{var r;let t=(r=e.querySelectorAll)==null?void 0:r.call(e,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let o of Array.from(t))_x(o)},G0=e=>e.nodeType===1,K0={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:W0,bufferContent(e){if(e.length<N0)return"";let t=0,r=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(r=o),o+=1}return r<0?"":e.slice(0,r)},isAnimating(e){var t;return((t=$a.get(e.id))!=null?t:0)>0},onAttach(e){Nx(e);let t=new MutationObserver(r=>{for(let o of r)for(let n of Array.from(o.addedNodes))G0(n)&&(n.classList.contains("persona-stream-char")&&n.closest(".persona-stream-glyph-cycle")?_x(n):Nx(n))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};oa(K0);var Ux,qx,or=typeof document!="undefined"&&(qx=(Ux=document.currentScript)==null?void 0:Ux.src)!=null?qx:null;gg(()=>{let e=or==null?void 0:or.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===or?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${or!=null?or:"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});og(()=>{let e=or==null?void 0:or.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===or?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${or!=null?or:"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});js().catch(e=>{typeof console!="undefined"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});Qg(()=>{let e=or==null?void 0:or.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===or?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${or!=null?or:"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});return my(X0);})();
181
183
  /*! Bundled license information:
182
184
 
183
185
  lucide/dist/esm/icons/activity.mjs: