@runtypelabs/persona 3.36.0 → 3.37.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,21 @@
1
- "use strict";var AgentWidget=(()=>{var Xx=Object.create;var fi=Object.defineProperty;var Qx=Object.getOwnPropertyDescriptor;var Jx=Object.getOwnPropertyNames;var Yx=Object.getPrototypeOf,Zx=Object.prototype.hasOwnProperty;var Ol=(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 dg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ey=(e,t)=>{for(var r in t)fi(e,r,{get:t[r],enumerable:!0})},cg=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Jx(t))!Zx.call(e,n)&&n!==r&&fi(e,n,{get:()=>t[n],enumerable:!(o=Qx(t,n))||o.enumerable});return e};var Pa=(e,t,r)=>(r=e!=null?Xx(Yx(e)):{},cg(t||!e||!e.__esModule?fi(r,"default",{value:e,enumerable:!0}):r,e)),ty=e=>cg(fi({},"__esModule",{value:!0}),e);var jl=dg(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 bi=dg(Ar=>{"use strict";var my=Ar&&Ar.__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=Ar&&Ar.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&my(t,e,r)};Object.defineProperty(Ar,"__esModule",{value:!0});Ar.Allow=Ar.MalformedJSON=Ar.PartialJSON=Ar.parseJSON=Ar.parse=void 0;var Or=jl();Object.defineProperty(Ar,"Allow",{enumerable:!0,get:function(){return Or.Allow}});gy(jl(),Ar);var xi=class extends Error{};Ar.PartialJSON=xi;var yi=class extends Error{};Ar.MalformedJSON=yi;function Cg(e,t=Or.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)}Ar.parseJSON=Cg;var hy=(e,t)=>{let r=e.length,o=0,n=p=>{throw new xi(`${p} at position ${o}`)},a=p=>{throw new yi(`${p} at position ${o}`)},s=()=>(g(),o>=r&&n("Unexpected end of input"),e[o]==='"'?i():e[o]==="{"?c():e[o]==="["?d():e.substring(o,o+4)==="null"||Or.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Or.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Or.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Or.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Or.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Or.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):u()),i=()=>{let p=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(p,++o-Number(m)))}catch(x){a(String(x))}else if(Or.Allow.STR&t)try{return JSON.parse(e.substring(p,o-Number(m))+'"')}catch{return JSON.parse(e.substring(p,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{o++,g();let p={};try{for(;e[o]!=="}";){if(g(),o>=r&&Or.Allow.OBJ&t)return p;let m=i();g(),o++;try{let x=s();p[m]=x}catch(x){if(Or.Allow.OBJ&t)return p;throw x}g(),e[o]===","&&o++}}catch{if(Or.Allow.OBJ&t)return p;n("Expected '}' at end of object")}return o++,p},d=()=>{o++;let p=[];try{for(;e[o]!=="]";)p.push(s()),g(),e[o]===","&&o++}catch{if(Or.Allow.ARR&t)return p;n("Expected ']' at end of array")}return o++,p},u=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Or.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let p=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==r&&!(Or.Allow.NUM&t)&&n("Unterminated number literal");try{return JSON.parse(e.substring(p,o))}catch{e.substring(p,o)==="-"&&n("Not sure what '-' is");try{return JSON.parse(e.substring(p,e.lastIndexOf("e")))}catch(x){a(String(x))}}},g=()=>{for(;o<r&&`
2
- \r `.includes(e[o]);)o++};return s()},xy=Cg;Ar.parse=xy});var E0={};ey(E0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>rd,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>td,ASK_USER_QUESTION_TOOL_NAME:()=>ws,AgentWidgetClient:()=>na,AgentWidgetSession:()=>Ua,AttachmentManager:()=>la,BrowserSpeechEngine:()=>In,DEFAULT_COMPONENTS:()=>ap,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Qi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>oo,DEFAULT_PALETTE:()=>op,DEFAULT_SEMANTIC:()=>np,DEFAULT_WIDGET_CONFIG:()=>_t,PRESETS:()=>jp,PRESET_FULLSCREEN:()=>zp,PRESET_MINIMAL:()=>$p,PRESET_SHOP:()=>Vp,ReadAloudController:()=>ia,SUGGEST_REPLIES_CLIENT_TOOL:()=>Si,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Yl,SUGGEST_REPLIES_TOOL_NAME:()=>Mo,THEME_ZONES:()=>lh,VERSION:()=>oa,WEBMCP_TOOL_PREFIX:()=>tn,WebMcpBridge:()=>Ha,accessibilityPlugin:()=>Ax,animationsPlugin:()=>Mx,applyThemeVariables:()=>Wn,attachHeaderToContainer:()=>pa,brandPlugin:()=>Tx,buildComposer:()=>ja,buildDefaultHeader:()=>gp,buildHeader:()=>ln,buildHeaderWithLayout:()=>za,buildMinimalHeader:()=>hp,builtInClientToolsForDispatch:()=>Ms,collectEnrichedPageContext:()=>wx,componentRegistry:()=>dn,createActionManager:()=>Gs,createAgentExperience:()=>Il,createAskUserQuestionBubble:()=>Hg,createBestAvailableVoiceProvider:()=>Ni,createBubbleWithLayout:()=>Rh,createCSATFeedback:()=>Ll,createComboButton:()=>pl,createComponentMiddleware:()=>tx,createComponentStreamParser:()=>Ml,createDefaultSanitizer:()=>ql,createDirectivePostprocessor:()=>gg,createDropdownMenu:()=>Fn,createFlexibleJsonStreamParser:()=>Ng,createIconButton:()=>yr,createImagePart:()=>jg,createJsonStreamParser:()=>Ri,createLabelButton:()=>Us,createLocalStorageAdapter:()=>Al,createMarkdownProcessor:()=>bs,createMarkdownProcessorFromConfig:()=>Zn,createMessageActions:()=>Sp,createNPSFeedback:()=>Pl,createPlainTextParser:()=>Li,createPlugin:()=>Lx,createRegexJsonParser:()=>Pi,createStandardBubble:()=>Ga,createTextPart:()=>ks,createTheme:()=>Va,createThemeObserver:()=>el,createToggleGroup:()=>Sh,createTypingIndicator:()=>ua,createVoiceProvider:()=>Rn,createWidgetHostLayout:()=>Ks,createXmlParser:()=>Ii,defaultActionHandlers:()=>ma,defaultJsonActionParser:()=>js,defaultParseRules:()=>Up,detectColorScheme:()=>Ws,directivePostprocessor:()=>hg,ensureAskUserQuestionSheet:()=>Fa,escapeHtml:()=>qo,extractComponentDirectiveFromMessage:()=>kl,fileToImagePart:()=>Gg,formatEnrichedContext:()=>Sx,generateAssistantMessageId:()=>aa,generateMessageId:()=>Ug,generateStableSelector:()=>qp,generateUserMessageId:()=>Oa,getActiveTheme:()=>$a,getColorScheme:()=>ip,getDisplayText:()=>Vg,getHeaderLayout:()=>xp,getImageParts:()=>zg,getPreset:()=>Rx,hasComponentDirective:()=>El,hasImages:()=>$g,headerLayouts:()=>ul,highContrastPlugin:()=>kx,initAgentWidget:()=>px,isAskUserQuestionMessage:()=>rn,isComponentDirectiveType:()=>ex,isDockedMountMode:()=>pr,isSuggestRepliesMessage:()=>As,isVoiceSupported:()=>Ps,isWebMcpToolName:()=>ea,latestAgentSuggestions:()=>Ai,listRegisteredStreamAnimations:()=>pp,markdownPostprocessor:()=>Ul,mergeWithDefaults:()=>Ji,normalizeContent:()=>qg,parseAskUserQuestionPayload:()=>on,parseSuggestRepliesPayload:()=>ed,pickBestVoice:()=>_a,pluginRegistry:()=>zs,reducedMotionPlugin:()=>Ex,registerStreamAnimationPlugin:()=>ca,removeAskUserQuestionSheet:()=>Ln,renderComponentDirective:()=>Tl,renderLoadingIndicatorWithFallback:()=>wp,renderLucideIcon:()=>ve,resolveDockConfig:()=>no,resolveSanitizer:()=>Wa,resolveTokens:()=>Yi,stripWebMcpPrefix:()=>hi,themeToCssVariables:()=>Zi,unregisterStreamAnimationPlugin:()=>cp,validateImageFile:()=>Kg,validateTheme:()=>sp});var _l=null,ys=null,Ra=null,pg=e=>{_l=e};var mi=()=>ys?Promise.resolve(ys):Ra||(_l?(Ra=_l().then(e=>(ys=e,e)),Ra):(Ra=import("./markdown-parsers-entry").then(e=>(ys=e,e)),Ra)),Ia=()=>ys;var ry=e=>{if(e)return e},bs=e=>{let t=null;return r=>{var n,a;let o=Ia();if(!o)return qo(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=ry(e==null?void 0:e.renderer);c&&t.use({renderer:c})}return t.parse(r)}},Zn=e=>e?bs({markedOptions:e.options,renderer:e.renderer}):bs(),oy=bs(),Ul=e=>oy(e),qo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),fg=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),ug=e=>`%%FORM_PLACEHOLDER_${e}%%`,mg=(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=ug(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=ug(t.length);return t.push({token:a,type:n}),a}),r},gg=e=>{let t=Zn(e);return r=>{let o=[],n=mg(r,o),a=t(n);return o.forEach(({token:s,type:i})=>{let c=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${fg(i)}"></div>`;a=a.replace(c,u)}),a}},hg=e=>{let t=[],r=mg(e,t),o=Ul(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="${fg(a)}"></div>`;o=o.replace(s,c)}),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,ql=()=>{let e=null;return t=>{let r=Ia();if(!r)return qo(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)}},Wa=e=>e===!1?null:typeof e=="function"?e:ql();var tn="webmcp:",Vl=new Map,xg=e=>{var t;Vl.clear();for(let r of e){let o=(t=r.title)==null?void 0:t.trim();o&&Vl.set(r.name,o)}},zl=e=>Vl.get(hi(e)),gi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},$l=null,bg=e=>{$l=e};function vg(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 yg(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=yg(e,0).toString(36),r=yg(e,2654435761).toString(36);return`${t}.${r}`}var Ha=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 gi.warn("getTools() threw: shipping an empty WebMCP snapshot.",n),[]}xg(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 Ao("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let x=typeof document!="undefined"&&!!document.modelContext;return Ao(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=hi(t),s;try{s=await n.getTools()}catch(x){let C=x instanceof Error?x.message:String(x);return Ao(`Failed to read WebMCP registry: ${C}`)}xg(s);let i=s.find(x=>x.name===a);if(!i)return Ao(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Ao(`WebMCP tool not allowed by client allowlist: ${a}`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let c=zl(a),d={toolName:a,args:r,description:i.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(d))return Ao("User declined the tool call.");if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let u=new AbortController,g=!1,p=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 Ao(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let C=x instanceof Error?x.message:String(x);return Ao(C)}finally{clearTimeout(p),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}($l?await $l():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){gi.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,gi.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:cy;try{return await r(t)}catch(n){return gi.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))}},hi=e=>e.startsWith(tn)?e.slice(tn.length):e,ea=e=>e.startsWith(tn),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)}]}},Ao=e=>({isError:!0,content:[{type:"text",text:e}]}),cy=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=py(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var AgentWidget=(()=>{var Yx=Object.create;var mi=Object.defineProperty;var Zx=Object.getOwnPropertyDescriptor;var ey=Object.getOwnPropertyNames;var ty=Object.getPrototypeOf,ry=Object.prototype.hasOwnProperty;var Ul=(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 cg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),oy=(e,t)=>{for(var r in t)mi(e,r,{get:t[r],enumerable:!0})},pg=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ey(t))!ry.call(e,n)&&n!==r&&mi(e,n,{get:()=>t[n],enumerable:!(o=Zx(t,n))||o.enumerable});return e};var La=(e,t,r)=>(r=e!=null?Yx(ty(e)):{},pg(t||!e||!e.__esModule?mi(r,"default",{value:e,enumerable:!0}):r,e)),ny=e=>pg(mi({},"__esModule",{value:!0}),e);var Kl=cg(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.Allow=_e.ALL=_e.COLLECTION=_e.ATOM=_e.SPECIAL=_e.INF=_e._INFINITY=_e.INFINITY=_e.NAN=_e.BOOL=_e.NULL=_e.OBJ=_e.ARR=_e.NUM=_e.STR=void 0;_e.STR=1;_e.NUM=2;_e.ARR=4;_e.OBJ=8;_e.NULL=16;_e.BOOL=32;_e.NAN=64;_e.INFINITY=128;_e._INFINITY=256;_e.INF=_e.INFINITY|_e._INFINITY;_e.SPECIAL=_e.NULL|_e.BOOL|_e.INF|_e.NAN;_e.ATOM=_e.STR|_e.NUM|_e.SPECIAL;_e.COLLECTION=_e.ARR|_e.OBJ;_e.ALL=_e.ATOM|_e.COLLECTION;_e.Allow={STR:_e.STR,NUM:_e.NUM,ARR:_e.ARR,OBJ:_e.OBJ,NULL:_e.NULL,BOOL:_e.BOOL,NAN:_e.NAN,INFINITY:_e.INFINITY,_INFINITY:_e._INFINITY,INF:_e.INF,SPECIAL:_e.SPECIAL,ATOM:_e.ATOM,COLLECTION:_e.COLLECTION,ALL:_e.ALL};_e.default=_e.Allow});var vi=cg(Mr=>{"use strict";var xy=Mr&&Mr.__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]})),yy=Mr&&Mr.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&xy(t,e,r)};Object.defineProperty(Mr,"__esModule",{value:!0});Mr.Allow=Mr.MalformedJSON=Mr.PartialJSON=Mr.parseJSON=Mr.parse=void 0;var _r=Kl();Object.defineProperty(Mr,"Allow",{enumerable:!0,get:function(){return _r.Allow}});yy(Kl(),Mr);var yi=class extends Error{};Mr.PartialJSON=yi;var bi=class extends Error{};Mr.MalformedJSON=bi;function wg(e,t=_r.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return by(e.trim(),t)}Mr.parseJSON=wg;var by=(e,t)=>{let r=e.length,o=0,n=p=>{throw new yi(`${p} at position ${o}`)},a=p=>{throw new bi(`${p} at position ${o}`)},s=()=>(g(),o>=r&&n("Unexpected end of input"),e[o]==='"'?i():e[o]==="{"?c():e[o]==="["?d():e.substring(o,o+4)==="null"||_r.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||_r.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||_r.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||_r.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||_r.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||_r.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):u()),i=()=>{let p=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(p,++o-Number(m)))}catch(x){a(String(x))}else if(_r.Allow.STR&t)try{return JSON.parse(e.substring(p,o-Number(m))+'"')}catch{return JSON.parse(e.substring(p,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{o++,g();let p={};try{for(;e[o]!=="}";){if(g(),o>=r&&_r.Allow.OBJ&t)return p;let m=i();g(),o++;try{let x=s();p[m]=x}catch(x){if(_r.Allow.OBJ&t)return p;throw x}g(),e[o]===","&&o++}}catch{if(_r.Allow.OBJ&t)return p;n("Expected '}' at end of object")}return o++,p},d=()=>{o++;let p=[];try{for(;e[o]!=="]";)p.push(s()),g(),e[o]===","&&o++}catch{if(_r.Allow.ARR&t)return p;n("Expected ']' at end of array")}return o++,p},u=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(_r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let p=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==r&&!(_r.Allow.NUM&t)&&n("Unterminated number literal");try{return JSON.parse(e.substring(p,o))}catch{e.substring(p,o)==="-"&&n("Not sure what '-' is");try{return JSON.parse(e.substring(p,e.lastIndexOf("e")))}catch(x){a(String(x))}}},g=()=>{for(;o<r&&`
2
+ \r `.includes(e[o]);)o++};return s()},vy=wg;Mr.parse=vy});var P0={};oy(P0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>nd,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>od,ASK_USER_QUESTION_TOOL_NAME:()=>Cs,AgentWidgetClient:()=>na,AgentWidgetSession:()=>_a,AttachmentManager:()=>la,BrowserSpeechEngine:()=>Rn,DEFAULT_COMPONENTS:()=>ip,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Yi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>no,DEFAULT_PALETTE:()=>ap,DEFAULT_SEMANTIC:()=>sp,DEFAULT_WIDGET_CONFIG:()=>$t,PRESETS:()=>Kp,PRESET_FULLSCREEN:()=>Gp,PRESET_MINIMAL:()=>jp,PRESET_SHOP:()=>zp,ReadAloudController:()=>ia,SUGGEST_REPLIES_CLIENT_TOOL:()=>Ai,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>ed,SUGGEST_REPLIES_TOOL_NAME:()=>Ao,THEME_ZONES:()=>ph,VERSION:()=>oa,WEBMCP_TOOL_PREFIX:()=>tn,WebMcpBridge:()=>Wa,accessibilityPlugin:()=>Ex,animationsPlugin:()=>kx,applyThemeVariables:()=>Wn,attachHeaderToContainer:()=>pa,brandPlugin:()=>Lx,buildComposer:()=>za,buildDefaultHeader:()=>xp,buildHeader:()=>ln,buildHeaderWithLayout:()=>$a,buildMinimalHeader:()=>yp,builtInClientToolsForDispatch:()=>As,collectEnrichedPageContext:()=>Mx,componentRegistry:()=>dn,createActionManager:()=>js,createAgentExperience:()=>Hl,createAskUserQuestionBubble:()=>Bg,createBestAvailableVoiceProvider:()=>_i,createBubbleWithLayout:()=>Hh,createCSATFeedback:()=>Il,createComboButton:()=>fl,createComponentMiddleware:()=>nx,createComponentStreamParser:()=>El,createDefaultSanitizer:()=>$l,createDirectivePostprocessor:()=>hg,createDropdownMenu:()=>Fn,createFlexibleJsonStreamParser:()=>Og,createIconButton:()=>br,createImagePart:()=>Xg,createJsonStreamParser:()=>Ri,createLabelButton:()=>_s,createLocalStorageAdapter:()=>Tl,createMarkdownProcessor:()=>ys,createMarkdownProcessorFromConfig:()=>Zn,createMessageActions:()=>Mp,createNPSFeedback:()=>Rl,createPlainTextParser:()=>Pi,createPlugin:()=>Rx,createRegexJsonParser:()=>Ii,createStandardBubble:()=>ja,createTextPart:()=>Es,createTheme:()=>qa,createThemeObserver:()=>rl,createToggleGroup:()=>Th,createTypingIndicator:()=>ua,createVoiceProvider:()=>In,createWidgetHostLayout:()=>Gs,createXmlParser:()=>Wi,defaultActionHandlers:()=>ma,defaultJsonActionParser:()=>zs,defaultParseRules:()=>Vp,detectColorScheme:()=>Rs,directivePostprocessor:()=>xg,ensureAskUserQuestionSheet:()=>Da,escapeHtml:()=>Uo,extractComponentDirectiveFromMessage:()=>Pl,fileToImagePart:()=>Qg,formatEnrichedContext:()=>Tx,generateAssistantMessageId:()=>aa,generateMessageId:()=>$g,generateStableSelector:()=>$p,generateUserMessageId:()=>Na,getActiveTheme:()=>Va,getColorScheme:()=>dp,getDisplayText:()=>jg,getHeaderLayout:()=>bp,getImageParts:()=>Kg,getPreset:()=>Hx,hasComponentDirective:()=>Ll,hasImages:()=>Gg,headerLayouts:()=>ml,highContrastPlugin:()=>Ix,initAgentWidget:()=>mx,isAskUserQuestionMessage:()=>rn,isComponentDirectiveType:()=>ox,isDockedMountMode:()=>ur,isSuggestRepliesMessage:()=>Ss,isVoiceSupported:()=>Ls,isWebMcpToolName:()=>ea,latestAgentSuggestions:()=>Mi,listRegisteredStreamAnimations:()=>fp,markdownPostprocessor:()=>Vl,mergeWithDefaults:()=>Zi,normalizeContent:()=>zg,parseAskUserQuestionPayload:()=>on,parseSuggestRepliesPayload:()=>rd,pickBestVoice:()=>Oa,pluginRegistry:()=>$s,reducedMotionPlugin:()=>Px,registerStreamAnimationPlugin:()=>ca,removeAskUserQuestionSheet:()=>Ln,renderComponentDirective:()=>kl,renderLoadingIndicatorWithFallback:()=>Ap,renderLucideIcon:()=>ve,resolveDockConfig:()=>ao,resolveSanitizer:()=>Ra,resolveTokens:()=>el,stripWebMcpPrefix:()=>xi,themeToCssVariables:()=>tl,unregisterStreamAnimationPlugin:()=>up,validateImageFile:()=>Jg,validateTheme:()=>lp});var ql=null,xs=null,Pa=null,ug=e=>{ql=e};var gi=()=>xs?Promise.resolve(xs):Pa||(ql?(Pa=ql().then(e=>(xs=e,e)),Pa):(Pa=import("./markdown-parsers-entry").then(e=>(xs=e,e)),Pa)),Ia=()=>xs;var ay=e=>{if(e)return e},ys=e=>{let t=null;return r=>{var n,a;let o=Ia();if(!o)return Uo(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=ay(e==null?void 0:e.renderer);c&&t.use({renderer:c})}return t.parse(r)}},Zn=e=>e?ys({markedOptions:e.options,renderer:e.renderer}):ys(),sy=ys(),Vl=e=>sy(e),Uo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),mg=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),fg=e=>`%%FORM_PLACEHOLDER_${e}%%`,gg=(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=fg(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=fg(t.length);return t.push({token:a,type:n}),a}),r},hg=e=>{let t=Zn(e);return r=>{let o=[],n=gg(r,o),a=t(n);return o.forEach(({token:s,type:i})=>{let c=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${mg(i)}"></div>`;a=a.replace(c,u)}),a}},xg=e=>{let t=[],r=gg(e,t),o=Vl(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="${mg(a)}"></div>`;o=o.replace(s,c)}),o};var iy={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"]},ly=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,$l=()=>{let e=null;return t=>{let r=Ia();if(!r)return Uo(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:")&&!ly.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,iy)}},Ra=e=>e===!1?null:typeof e=="function"?e:$l();var tn="webmcp:",zl=new Map,yg=e=>{var t;zl.clear();for(let r of e){let o=(t=r.title)==null?void 0:t.trim();o&&zl.set(r.name,o)}},Gl=e=>zl.get(xi(e)),hi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},jl=null,vg=e=>{jl=e};function Cg(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}:${dy(t.join(""))}`}function bg(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 dy(e){let t=bg(e,0).toString(36),r=bg(e,2654435761).toString(36);return`${t}.${r}`}var Wa=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 hi.warn("getTools() threw: shipping an empty WebMCP snapshot.",n),[]}yg(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=py(n.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,r,o){if(await this.ensureReady(),this.config.enabled!==!0)return So("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let x=typeof document!="undefined"&&!!document.modelContext;return So(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=xi(t),s;try{s=await n.getTools()}catch(x){let C=x instanceof Error?x.message:String(x);return So(`Failed to read WebMCP registry: ${C}`)}yg(s);let i=s.find(x=>x.name===a);if(!i)return So(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return So(`WebMCP tool not allowed by client allowlist: ${a}`);if(o!=null&&o.aborted)return So("Aborted by cancel()");let c=Gl(a),d={toolName:a,args:r,description:i.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(d))return So("User declined the tool call.");if(o!=null&&o.aborted)return So("Aborted by cancel()");let u=new AbortController,g=!1,p=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,gy(r),{signal:u.signal});return uy(x)}catch(x){if(g)return So(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return So("Aborted by cancel()");let C=x instanceof Error?x.message:String(x);return So(C)}finally{clearTimeout(p),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}(jl?await jl():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){hi.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,hi.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:fy;try{return await r(t)}catch(n){return hi.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=>cy(t,o))}},xi=e=>e.startsWith(tn)?e.slice(tn.length):e,ea=e=>e.startsWith(tn),cy=(e,t)=>{if(t==="*")return!0;let r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)},py=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},uy=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:hy(t)}]}},So=e=>({isError:!0,content:[{type:"text",text:e}]}),fy=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=my(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
3
3
 
4
4
  Arguments:
5
5
  ${t}`:"")+(e.description?`
6
6
 
7
- ${e.description}`:"");return window.confirm(r)},py=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 En=Pa(bi(),1);var S=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},Vo=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var kt=(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},vs=(...e)=>e.filter(Boolean).join(" ");var ws="ask_user_question",Cs=8,Ba="data-persona-ask-sheet-for",yy="Other",by="Other\u2026",Sg="Type your own answer here",Ag="Send",vy="Next",Cy="Back",wy="Submit all",Sy="Skip",Ay=3,Gl="data-ask-current-index",Kl="data-ask-question-count",Mg="data-ask-answers",Xl="data-ask-grouped",Tg="data-ask-layout",My=e=>e.layout==="pills"?"pills":"rows",Ty=e=>e.getAttribute(Tg)==="pills"?"pills":"rows",wg=!1,Eg=e=>e.replace(/["\\]/g,"\\$&"),rn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ws,vi=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},on=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,En.parse)(n,En.STR|En.OBJ|En.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},Ss=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Cs&&!wg&&(wg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cs}.`)),t.slice(0,Cs)},Ey=e=>{var t;return(t=Ss(e)[0])!=null?t:null},ky=(e,t)=>{var r;return(r=Ss(e)[t])!=null?r:null},kg=(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))},Lg=(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 c=Lg(r,o,t);c&&a.appendChild(c)}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,p;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),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<Ay;m++)a.appendChild(Py(o));return a}if(c.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(c.length)),x.setAttribute("data-ask-other-row","true");let C=S("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=t.freeTextPlaceholder)!=null?u:Sg,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),C.appendChild(T),x.appendChild(C);let E=Lg(o,s,c.length);E&&x.appendChild(E),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=(p=t.freeTextLabel)!=null?p:m,a.appendChild(x)}}return a},Pg=(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:Sg,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:Ag,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:Ag,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Wy=(e,t,r)=>{var d,u,g,p;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 c=e===t-1;return i.textContent=c?(g=r.submitAllLabel)!=null?g:wy:(p=r.nextLabel)!=null?p:vy,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},ta=e=>{let t=e.getAttribute(Mg);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Rg=(e,t)=>{e.setAttribute(Mg,JSON.stringify(t))},ho=e=>{var r;let t=Number((r=e.getAttribute(Gl))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Hy=(e,t)=>{e.setAttribute(Gl,String(Math.max(0,Math.floor(t))))},Da=e=>{var r;let t=Number((r=e.getAttribute(Kl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},kn=e=>e.getAttribute(Xl)==="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 c=r[i];(typeof c=="string"||Array.isArray(c))&&(o[s]=c)}}),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)))},Ci=(e,t)=>{let{payload:r}=on(t),o=Ss(r),n=ta(e),a={},s=new Set;return o.forEach((i,c)=>{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,c)&&(a[d]=n[c]))}),a},Ig=e=>{let t=ta(e),r=ho(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 g;let d=(g=c.getAttribute("data-option-label"))!=null?g:"",u=n.has(d);c.setAttribute("aria-pressed",u?"true":"false"),c.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(a).map(c=>{var d;return(d=c.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 c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},Wg=e=>{if(!kn(e))return;let t=ta(e),r=ho(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}},Ql=(e,t,r)=>{let o=vi(r),n=Ty(e),{payload:a,complete:s}=on(t),i=kn(e),c=ho(e),d=Da(e),u=i?ky(a,c):Ey(a),g=!!(u!=null&&u.multiSelect),p=e.querySelector('[data-ask-step-inline="true"]');p&&(p.textContent=i?`${c+1}/${d}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let M=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=M,x.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let M=Ry(u,o,s,n);C.replaceWith(M)}if(n!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(Pg(o,n))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!T?e.appendChild(Iy(o)):(!g||i)&&T&&T.remove(),e.setAttribute("data-multi-select",g?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let M=Wy(c,d,o);E?E.replaceWith(M):e.appendChild(M)}else E&&E.remove();Ig(e),Wg(e)},Fy=(e,t,r)=>{let o=vi(t),n=My(o),a=e.toolCall.id,s=Ss(r),i=Math.max(1,s.length),c=i>1,d=By(e,s),u=c?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(Ba,a),g.setAttribute("data-tool-call-id",a),g.setAttribute("data-message-id",e.id),g.setAttribute(Kl,String(i)),g.setAttribute(Gl,String(u)),g.setAttribute(Xl,c?"true":"false"),g.setAttribute(Tg,n),Rg(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`),kg(g,o);let p=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="",p.appendChild(m);let x=S("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",p.appendChild(x),g.appendChild(p);let T=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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),n!=="rows"&&g.appendChild(Pg(o,n)),Ql(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Ny=(e,t,r)=>{let{payload:o}=on(t),n=Math.max(1,Ss(o).length);n>Da(e)&&(e.setAttribute(Kl,String(n)),n>1&&!kn(e)&&e.setAttribute(Xl,"true")),Ql(e,t,r)},Hg=(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=vi(t);kg(r,o);let n=S("span","persona-ask-stub-label"),{complete:a}=on(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Fa=(e,t,r)=>{if(!r||!rn(e)||vi(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Ba}]`).forEach(d=>{d.getAttribute(Ba)!==n&&d.remove()});let s=r.querySelector(`[${Ba}="${Eg(n)}"]`);if(s){Ny(s,e,t);return}let{payload:i}=on(e),c=Fy(e,t,i);r.appendChild(c)},Ln=(e,t)=>{if(!e)return;let r=t?`[${Ba}="${Eg(t)}"]`:`[${Ba}]`;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)})},Jl=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),Pn=(e,t)=>{let r=ta(e),o=ho(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,Rg(e,r),Ig(e),Wg(e)},wi=(e,t,r,o)=>{let n=Da(e),a=Math.max(0,Math.min(n-1,o));Hy(e,a),Ql(e,t,r)};var Mo="suggest_replies";var Yl={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},Si={name:Mo,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:Yl,origin:"sdk",annotations:{readOnlyHint:!0}},Zl=()=>({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)===Mo},ed=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},Ai=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=ed((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},Bg=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 td={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Cs,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},rd={name:ws,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:td,origin:"sdk",annotations:{readOnlyHint:!0}},Ms=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(rd),Bg(e)&&t.push(Si),t};var nn=Pa(bi(),1),Mi=e=>e.replace(/\\n/g,`
8
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Na=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`},Dg=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 Fg=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`},Es=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)},Ei=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)},od=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=Es(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},ki=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&Ts(o,r.slice(a,s.index),[]),s[1]!==void 0?Ts(o,s[1],["bold"]):s[2]!==void 0?Ts(o,s[2],["italic"]):s[3]!==void 0&&Ts(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&Ts(o,r.slice(a),[]),o},Ts=(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,`
7
+ ${e.description}`:"");return window.confirm(r)},my=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)}},gy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},hy=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var En=La(vi(),1);var A=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},qo=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var Lt=(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},bs=(...e)=>e.filter(Boolean).join(" ");var Cs="ask_user_question",vs=8,Ha="data-persona-ask-sheet-for",Cy="Other",wy="Other\u2026",Ag="Type your own answer here",Mg="Send",Sy="Next",Ay="Back",My="Submit all",Ty="Skip",Ey=3,Xl="data-ask-current-index",Ql="data-ask-question-count",Tg="data-ask-answers",Jl="data-ask-grouped",Eg="data-ask-layout",ky=e=>e.layout==="pills"?"pills":"rows",Ly=e=>e.getAttribute(Eg)==="pills"?"pills":"rows",Sg=!1,kg=e=>e.replace(/["\\]/g,"\\$&"),rn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Cs,Ci=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},on=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,En.parse)(n,En.STR|En.OBJ|En.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},ws=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>vs&&!Sg&&(Sg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${vs}.`)),t.slice(0,vs)},Py=e=>{var t;return(t=ws(e)[0])!=null?t:null},Iy=(e,t)=>{var r;return(r=ws(e)[t])!=null?r:null},Lg=(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))},Pg=(e,t,r)=>{if(e!=="rows")return null;let o=A("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=A("span","persona-ask-row-check");o.appendChild(n)}else{let n=A("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Ry=(e,t,r,o)=>{let a=A("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=A("span","persona-ask-row-content"),i=A("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let d=A("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let c=Pg(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Wy=e=>{let r=A("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},Hy=(e,t,r,o)=>{var u,g,p;let a=A("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<Ey;m++)a.appendChild(Wy(o));return a}if(c.forEach((m,x)=>{a.appendChild(Ry(m,x,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Cy:wy;if(o==="rows"){let x=A("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 C=A("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=t.freeTextPlaceholder)!=null?u:Ag,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),C.appendChild(T),x.appendChild(C);let E=Pg(o,s,c.length);E&&x.appendChild(E),a.appendChild(x)}else{let x=A("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=(p=t.freeTextLabel)!=null?p:m,a.appendChild(x)}}return a},Ig=(e,t)=>{var a,s;let o=A("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:Ag,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=A("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Mg,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},By=e=>{var o;let t=A("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=A("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:Mg,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Dy=(e,t,r)=>{var d,u,g,p;let o=A("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=A("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(d=r.backLabel)!=null?d:Ay,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=A("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=A("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=r.skipLabel)!=null?u:Ty,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=A("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(g=r.submitAllLabel)!=null?g:My:(p=r.nextLabel)!=null?p:Sy,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},ta=e=>{let t=e.getAttribute(Tg);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Rg=(e,t)=>{e.setAttribute(Tg,JSON.stringify(t))},go=e=>{var r;let t=Number((r=e.getAttribute(Xl))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Fy=(e,t)=>{e.setAttribute(Xl,String(Math.max(0,Math.floor(t))))},Ba=e=>{var r;let t=Number((r=e.getAttribute(Ql))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},kn=e=>e.getAttribute(Jl)==="true",Ny=(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},Oy=(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)))},wi=(e,t)=>{let{payload:r}=on(t),o=ws(r),n=ta(e),a={},s=new Set;return o.forEach((i,c)=>{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,c)&&(a[d]=n[c]))}),a},Wg=e=>{let t=ta(e),r=go(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 g;let d=(g=c.getAttribute("data-option-label"))!=null?g:"",u=n.has(d);c.setAttribute("aria-pressed",u?"true":"false"),c.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(a).map(c=>{var d;return(d=c.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 c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},Hg=e=>{if(!kn(e))return;let t=ta(e),r=go(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}},Yl=(e,t,r)=>{let o=Ci(r),n=Ly(e),{payload:a,complete:s}=on(t),i=kn(e),c=go(e),d=Ba(e),u=i?Iy(a,c):Py(a),g=!!(u!=null&&u.multiSelect),p=e.querySelector('[data-ask-step-inline="true"]');p&&(p.textContent=i?`${c+1}/${d}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let w=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=w,x.classList.toggle("persona-ask-question-skeleton",!w&&!s)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let w=Hy(u,o,s,n);C.replaceWith(w)}if(n!=="rows"){let w=e.querySelector('[data-ask-free-text-row="true"]');w&&w.replaceWith(Ig(o,n))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!T?e.appendChild(By(o)):(!g||i)&&T&&T.remove(),e.setAttribute("data-multi-select",g?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let w=Dy(c,d,o);E?E.replaceWith(w):e.appendChild(w)}else E&&E.remove();Wg(e),Hg(e)},_y=(e,t,r)=>{let o=Ci(t),n=ky(o),a=e.toolCall.id,s=ws(r),i=Math.max(1,s.length),c=i>1,d=Ny(e,s),u=c?Oy(e,i):0,g=A("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Ha,a),g.setAttribute("data-tool-call-id",a),g.setAttribute("data-message-id",e.id),g.setAttribute(Ql,String(i)),g.setAttribute(Xl,String(u)),g.setAttribute(Jl,c?"true":"false"),g.setAttribute(Eg,n),Rg(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`),Lg(g,o);let p=A("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=A("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",p.appendChild(m);let x=A("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",p.appendChild(x),g.appendChild(p);let T=A("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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),n!=="rows"&&g.appendChild(Ig(o,n)),Yl(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Uy=(e,t,r)=>{let{payload:o}=on(t),n=Math.max(1,ws(o).length);n>Ba(e)&&(e.setAttribute(Ql,String(n)),n>1&&!kn(e)&&e.setAttribute(Jl,"true")),Yl(e,t,r)},Bg=(e,t)=>{let r=A("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=Ci(t);Lg(r,o);let n=A("span","persona-ask-stub-label"),{complete:a}=on(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Da=(e,t,r)=>{if(!r||!rn(e)||Ci(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Ha}]`).forEach(d=>{d.getAttribute(Ha)!==n&&d.remove()});let s=r.querySelector(`[${Ha}="${kg(n)}"]`);if(s){Uy(s,e,t);return}let{payload:i}=on(e),c=_y(e,t,i);r.appendChild(c)},Ln=(e,t)=>{if(!e)return;let r=t?`[${Ha}="${kg(t)}"]`:`[${Ha}]`;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)})},Zl=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),Pn=(e,t)=>{let r=ta(e),o=go(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,Rg(e,r),Wg(e),Hg(e)},Si=(e,t,r,o)=>{let n=Ba(e),a=Math.max(0,Math.min(n-1,o));Fy(e,a),Yl(e,t,r)};var Ao="suggest_replies";var ed={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},Ai={name:Ao,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:ed,origin:"sdk",annotations:{readOnlyHint:!0}},td=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ss=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Ao},rd=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},Mi=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!Ss(o))continue;let n=rd((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},Dg=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 od={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:vs,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},nd={name:Cs,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:od,origin:"sdk",annotations:{readOnlyHint:!0}},As=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(nd),Dg(e)&&t.push(Ai),t};var nn=La(vi(),1),Ti=e=>e.replace(/\\n/g,`
8
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Fa=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)}},qy=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`},Fg=e=>e.status==="complete"?qy(e):e.status==="pending"?"Waiting":"",Vy=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 Ng=e=>e.status==="complete"?Vy(e):"Using tool...",Ei=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ts=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 Ei(t)},ki=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 Ei(t)},ad=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=Ts(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},Li=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&Ms(o,r.slice(a,s.index),[]),s[1]!==void 0?Ms(o,s[1],["bold"]):s[2]!==void 0?Ms(o,s[2],["italic"]):s[3]!==void 0&&Ms(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&Ms(o,r.slice(a),[]),o},Ms=(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})},$y=()=>{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
9
  `).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()=>{}}},ra=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Pi=()=>{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)}},Ri=()=>{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,nn.parse)(r,nn.STR|nn.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?Mi(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=Mi(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Ng=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?Mi(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Mi(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,nn.parse)(a,nn.STR|nn.OBJ),c=n(i);c!==null&&(t=c)}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 Wi=class{constructor(t,r=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=r}push(t,r){var a,s,i;let o=(i=(a=r==null?void 0:r.seq)!=null?a:r==null?void 0:r.sequenceIndex)!=null?i:(s=r==null?void 0:r.agentContext)==null?void 0:s.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,r);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,r),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,r);return}let n=this.buffer.get(o);n!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${n.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(n.payloadType,n.payload)),this.buffer.set(o,{payloadType:t,payload:r,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((r,o)=>r[0]-o[0]);for(let[r,o]of t)this.buffer.delete(r),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Og="3.36.0";var oa=Og;var Vy="https://api.runtype.com/v1/dispatch",Hi="https://api.runtype.com";function $y(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 nd=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 zy(e){switch(e){case"json":return Ri;case"regex-json":return Pi;case"xml":return Ii;default:return Li}}var _g=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=_g(r);if(!_g(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ra(e);return ra(t)!==null&&s===null?t:e}var na=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":oa,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:zy(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 Ha(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$/,""))||Hi}/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":oa},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$/,""))||Hi}/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":oa},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 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:c.sessionId,messages:t.messages.filter(nd).map(y=>{var w,b,A;return{id:y.id,role:y.role,content:(A=(b=(w=y.contentParts)!=null?w:y.llmContent)!=null?b:y.rawContent)!=null?A: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}},p=d.clientTools,m=!!(p&&p.length>0),x=m?vg(p):void 0,C=this.clientToolsFingerprintSessionId===c.sessionId,T=m&&C&&this.lastSentClientToolsFingerprint===x,E=!1,M=null,P;for(let y=0;;y++){let b={...g,...m&&(E||!T)&&p?{clientTools:p}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",b),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":oa},body:JSON.stringify(b),signal:o.signal}),P.status===409&&y===0&&m){let A=await P.json().catch(()=>null);if((A==null?void 0:A.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}M=A!=null?A:{error:"Chat request failed"}}break}if(!P.ok){let y=M!=null?M:await P.json().catch(()=>({error:"Chat request failed"}));if(P.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(P.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(!P.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(P.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let d=c instanceof Error?c:new Error(String(c));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 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$/,""))||Hi}/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(/\/+$/,""))||Hi}/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:(u=o==null?void 0:o.streamResponse)!=null?u:!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(nd).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,c)=>{let d=new Date(i.createdAt).getTime(),u=new Date(c.createdAt).getTime();return d-u}).map(i=>{var c,d,u;return{role:i.role,content:(u=(d=(c=i.contentParts)!=null?c: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=[...Ms(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 d=await c({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(nd).sort((i,c)=>{let d=new Date(i.createdAt).getTime(),u=new Date(c.createdAt).getTime();return d-u}).map(i=>{var c,d,u;return{role:i.role,content:(u=(d=(c=i.contentParts)!=null?c:i.llmContent)!=null?d:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},n=[...Ms(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 d=await c({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 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=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:c(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)),c(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 Cr,Wt,ur,Eo;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,d=()=>i+c++,u=V=>{let j=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,he=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,Xe=V.tools?V.tools.map(et=>({...et,chunks:et.chunks?[...et.chunks]:void 0})):void 0;return{...V,reasoning:j,toolCall:he,tools:Xe}},g=V=>{if(V.role!=="assistant"||V.variant)return!0;let j=Array.isArray(V.contentParts)&&V.contentParts.length>0,he=typeof V.rawContent=="string"&&V.rawContent.trim()!=="";return typeof V.content=="string"&&V.content.trim()!==""||j||he||!!V.stopReason},p=V=>{g(V)&&r({type:"message",message:u(V)})},m=null,x=null,C={current:null},T={current:null},E=!1,M=new Map,P=new Map,y=new Map,w=new Map,b={lastId:null,byStep:new Map},A={lastId:null,byCall:new Map},H=(V,j,he="")=>`${V}::${j}::${he}`,W=(V,j)=>`${V}::${j}::`,k=(V,j,he,Xe)=>{let et=H(V,j,he),qe=y.get(et);if(qe)return qe;let Ne=he?`-${he}`:"",Pt={id:`nested-${V}-${j}${Ne}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...he?{partId:he}:{},agentMetadata:{executionId:Xe,parentToolId:V,parentStepId:j}};return y.set(et,Pt),p(Pt),Pt},N=V=>{if(V==null)return null;try{return String(V)}catch{return null}},q=V=>{var j,he,Xe,et,qe;return N((qe=(et=(Xe=(he=(j=V.stepId)!=null?j:V.step_id)!=null?he:V.step)!=null?Xe:V.parentId)!=null?et:V.flowStepId)!=null?qe:V.flow_step_id)},Z=V=>{var j,he,Xe,et,qe,Ne,Pt;return N((Pt=(Ne=(qe=(et=(Xe=(he=(j=V.callId)!=null?j:V.call_id)!=null?he:V.requestId)!=null?Xe:V.request_id)!=null?et:V.toolCallId)!=null?qe:V.tool_call_id)!=null?Ne:V.stepId)!=null?Pt:V.step_id)},me=o,Ke=!1,Ce=()=>{if(m)return m;let V;return!Ke&&me?(V=me,Ke=!0):me&&T.current?V=`${me}_${T.current}`:V=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:V,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d()},p(m),m},Ie=(V,j)=>{b.lastId=j,V&&b.byStep.set(V,j)},Ue=(V,j)=>{var qe;let he=(qe=V.reasoningId)!=null?qe:V.id,Xe=q(V);if(he){let Ne=String(he);return Ie(Xe,Ne),Ne}if(Xe){let Ne=b.byStep.get(Xe);if(Ne)return b.lastId=Ne,Ne}if(b.lastId&&!j)return b.lastId;if(!j)return null;let et=`reason-${d()}`;return Ie(Xe,et),et},Te=V=>{let j=M.get(V);if(j)return j;let he={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:V,status:"streaming",chunks:[]}};return M.set(V,he),p(he),he},We=(V,j)=>{A.lastId=j,V&&A.byCall.set(V,j)},de=new Set,J=new Map,le=new Set,ge=new Map,ue=V=>{if(!V)return!1;let j=V.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},G=(V,j)=>{var qe;let he=(qe=V.toolId)!=null?qe:V.id,Xe=Z(V);if(he){let Ne=String(he);return We(Xe,Ne),Ne}if(Xe){let Ne=A.byCall.get(Xe);if(Ne)return A.lastId=Ne,Ne}if(A.lastId&&!j)return A.lastId;if(!j)return null;let et=`tool-${d()}`;return We(Xe,et),et},ce=V=>{let j=P.get(V);if(j)return j;let he={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:V,status:"pending"}};return P.set(V,he),p(he),he},Be=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let j=Number(V);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let he=Date.parse(V);if(!Number.isNaN(he))return he}return Date.now()},ne=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},ee=new Map,ie=new Map,vt=new Map,Lt=new Map,gt=null,_e=(V,j,he)=>{var Pt;let Xe=vt.get(V);Xe||(Xe=[],vt.set(V,Xe));let et=0,qe=Xe.length;for(;et<qe;){let Gt=et+qe>>>1;Xe[Gt].seq<j?et=Gt+1:qe=Gt}((Pt=Xe[et])==null?void 0:Pt.seq)===j?Xe[et]={seq:j,text:he}:Xe.splice(et,0,{seq:j,text:he});let Ne="";for(let Gt=0;Gt<Xe.length;Gt++)Ne+=Xe[Gt].text;return Ne},be=(V,j)=>{let he=ne(j),Xe=ie.get(V.id),et=jy(Xe,he);V.rawContent=et;let qe=ee.get(V.id),Ne=z=>{var oe;let Ht=(oe=V.content)!=null?oe:"";z.trim()!==""&&(Ht.trim().length===0||z.startsWith(Ht)||z.trimStart().startsWith(Ht.trim()))&&(V.content=z)},Pt=()=>{var z;if(qe){let Ht=(z=qe.close)==null?void 0:z.call(qe);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(V.id),ie.delete(V.id),V.streaming=!1,p(V)};if(!qe){Ne(he),Pt();return}let Gt=ra(et);if(Gt!==null&&Gt.trim()!==""){Ne(Gt),Pt();return}let Jt=z=>{var we;let Ht=typeof z=="string"?z:(we=z==null?void 0:z.text)!=null?we:null;if(Ht!==null&&Ht.trim()!=="")return Ht;let oe=qe.getExtractedText();return oe!==null&&oe.trim()!==""?oe:he},Pr;try{Pr=qe.processChunk(et)}catch{Ne(he),Pt();return}if(Pr instanceof Promise){Pr.then(z=>{Ne(Jt(z)),Pt()}).catch(()=>{Ne(he),Pt()});return}Ne(Jt(Pr)),Pt()},Ze=[],Y=!1,pe,Me=()=>{Y||(Y=!0,queueMicrotask(()=>{Y=!1,pe()}))},Je=new Wi((V,j)=>{Ze.push({payloadType:V,payload:j}),Me()}),Ge=null,ke=new Map,je=(Cr=this.config.iterationDisplay)!=null?Cr:"separate";for(pe=()=>{var V,j,he,Xe,et,qe,Ne,Pt,Gt,Jt,Pr,z,Ht,oe,we,De,At,ar,sr,wr,Ft,ot,Dt,lt,Yt,so,Rr,ir,Ur,ko,yt,jr,Lo,zo,yo,ht,Nn,Po,On,qr,ga,cn,jo,pn,un,_n,Un,fn,Ct,Gr,Kr,Ir,Mt,io,lo,Xr,mn,Go,gn,Qr,Nt,Wr,co,hn,Ko,xn,Ro,Jr,xe,dt,tr,fr,Io,es,Xo,qn,Wo,_,ha,Ho,Bo,Qo,Do,bo,xa,Qs,Yr,Zr,vo,Co,Vn,Jo,Mr,Fo,ya,$n,ba,Js,va,Ys,Ca,mt,ts,po,Vr,Zs,ei,wa,Yo,rs,yn,os,ns,as,ss,$r,Sa,No,Oo,is,ti,ls,ds,zn,ri,oi,ni,ai,si,bn,vn,ii,cs,Cn,li,ps,wn,us;for(let Aa=0;Aa<Ze.length;Aa++){let Ve=Ze[Aa].payloadType,L=Ze[Aa].payload;if(Ve==="reason_start"){let U=(V=Ue(L,!0))!=null?V:`reason-${d()}`,I=Te(U);I.reasoning=(j=I.reasoning)!=null?j:{id:U,status:"streaming",chunks:[]},I.reasoning.startedAt=(Xe=I.reasoning.startedAt)!=null?Xe:Be((he=L.startedAt)!=null?he:L.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let U=(qe=(et=Ue(L,!1))!=null?et:Ue(L,!0))!=null?qe:`reason-${d()}`,I=Te(U);I.reasoning=(Ne=I.reasoning)!=null?Ne:{id:U,status:"streaming",chunks:[]},I.reasoning.startedAt=(Gt=I.reasoning.startedAt)!=null?Gt:Be((Pt=L.startedAt)!=null?Pt:L.timestamp);let X=(z=(Pr=(Jt=L.reasoningText)!=null?Jt:L.text)!=null?Pr:L.delta)!=null?z:"";if(X&&L.hidden!==!0){let re=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(re!==void 0){let K=_e(U,re,String(X));I.reasoning.chunks=[K]}else I.reasoning.chunks.push(String(X))}if(I.reasoning.status=L.done?"complete":"streaming",L.done){I.reasoning.completedAt=Be((Ht=L.completedAt)!=null?Ht:L.timestamp);let re=(oe=I.reasoning.startedAt)!=null?oe:Date.now();I.reasoning.durationMs=Math.max(0,((we=I.reasoning.completedAt)!=null?we:Date.now())-re)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(Ve==="reason_complete"){let U=(At=(De=Ue(L,!1))!=null?De:Ue(L,!0))!=null?At:`reason-${d()}`,I=M.get(U);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=Be((ar=L.completedAt)!=null?ar:L.timestamp);let re=(sr=I.reasoning.startedAt)!=null?sr:Date.now();I.reasoning.durationMs=Math.max(0,((wr=I.reasoning.completedAt)!=null?wr:Date.now())-re),I.streaming=!1,p(I)}let X=q(L);X&&b.byStep.delete(X)}else if(Ve==="tool_start"){let U=(Ft=G(L,!0))!=null?Ft:`tool-${d()}`,I=(ot=L.toolName)!=null?ot:L.name;if(ue(I)){de.add(U);continue}let X=ce(U),re=(Dt=X.toolCall)!=null?Dt:{id:U,status:"pending"};re.name=I!=null?I:re.name,re.status="running",L.args!==void 0?re.args=L.args:L.parameters!==void 0&&(re.args=L.parameters),re.startedAt=(Yt=re.startedAt)!=null?Yt:Be((lt=L.startedAt)!=null?lt:L.timestamp),re.completedAt=void 0,re.durationMs=void 0,X.toolCall=re,X.streaming=!0;let K=L.agentContext;(K||L.executionId)&&(X.agentMetadata={executionId:(so=K==null?void 0:K.executionId)!=null?so:L.executionId,iteration:(Rr=K==null?void 0:K.iteration)!=null?Rr:L.iteration}),p(X)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let U=(Ur=(ir=G(L,!1))!=null?ir:G(L,!0))!=null?Ur:`tool-${d()}`;if(de.has(U))continue;let I=ce(U),X=(ko=I.toolCall)!=null?ko:{id:U,status:"running"};X.startedAt=(jr=X.startedAt)!=null?jr:Be((yt=L.startedAt)!=null?yt:L.timestamp);let re=(yo=(zo=(Lo=L.text)!=null?Lo:L.delta)!=null?zo:L.message)!=null?yo:"";re&&(X.chunks=(ht=X.chunks)!=null?ht:[],X.chunks.push(String(re))),X.status="running",I.toolCall=X,I.streaming=!0;let K=L.agentContext;(K||L.executionId)&&(I.agentMetadata=(On=I.agentMetadata)!=null?On:{executionId:(Nn=K==null?void 0:K.executionId)!=null?Nn:L.executionId,iteration:(Po=K==null?void 0:K.iteration)!=null?Po:L.iteration}),p(I)}else if(Ve==="tool_complete"){let U=(ga=(qr=G(L,!1))!=null?qr:G(L,!0))!=null?ga:`tool-${d()}`;if(de.has(U)){de.delete(U);continue}let I=ce(U),X=(cn=I.toolCall)!=null?cn:{id:U,status:"running"};X.status="complete",L.result!==void 0&&(X.result=L.result),typeof L.duration=="number"&&(X.duration=L.duration),X.completedAt=Be((jo=L.completedAt)!=null?jo:L.timestamp);let re=(pn=L.duration)!=null?pn:L.executionTime;if(typeof re=="number")X.durationMs=re;else{let Oe=(un=X.startedAt)!=null?un:Date.now();X.durationMs=Math.max(0,((_n=X.completedAt)!=null?_n:Date.now())-Oe)}I.toolCall=X,I.streaming=!1;let K=L.agentContext;(K||L.executionId)&&(I.agentMetadata=(Ct=I.agentMetadata)!=null?Ct:{executionId:(Un=K==null?void 0:K.executionId)!=null?Un:L.executionId,iteration:(fn=K==null?void 0:K.iteration)!=null?fn:L.iteration}),p(I);let Ae=Z(L);Ae&&A.byCall.delete(Ae)}else if(Ve==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let U=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,I=(Gr=U!=null?U:L.toolId)!=null?Gr:`local-${d()}`,X=ce(I),re=L.toolName,K=ea(re),Ae=(Kr=X.toolCall)!=null?Kr:{id:I,status:"pending"};Ae.name=re,Ae.args=L.parameters,Ae.status=K?"running":"complete",Ae.chunks=(Ir=Ae.chunks)!=null?Ir:[],Ae.startedAt=(io=Ae.startedAt)!=null?io:Be((Mt=L.startedAt)!=null?Mt:L.timestamp),K?(Ae.completedAt=void 0,Ae.duration=void 0,Ae.durationMs=void 0):Ae.completedAt=(lo=Ae.completedAt)!=null?lo:Ae.startedAt,X.toolCall=Ae,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(mn=L.executionId)!=null?mn:(Xr=X.agentMetadata)==null?void 0:Xr.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},p(X)}else if(Ve==="text_start"){if((Go=L.toolContext)!=null&&Go.toolId)continue;let U=L.partId;if(U!==void 0&&T.current!==null&&U!==T.current){let I=m;I&&(I.streaming=!1,p(I),gt=I,m=null,E=!0)}U!==void 0&&(T.current=U)}else if(Ve==="text_end"){if((gn=L.toolContext)!=null&&gn.toolId)continue;let U=m;U&&(U.streaming=!1,p(U),gt=U,m=null,E=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let U=L.stepType,I=L.executionType;if(U==="tool"||I==="context")continue;let X=L.toolContext;if(X!=null&&X.toolId){let Oe=String((Nt=(Qr=L.id)!=null?Qr:X.stepId)!=null?Nt:`step-${d()}`),at=L.partId!==void 0&&L.partId!==null?String(L.partId):"",tt=`${X.toolId}::${Oe}`,Bt=w.get(tt);if(at!==""&&Bt!==void 0&&Bt!==""&&Bt!==at){let wt=y.get(H(X.toolId,Oe,Bt));wt&&wt.streaming!==!1&&(wt.streaming=!1,p(wt))}at!==""&&w.set(tt,at);let $t=k(X.toolId,Oe,at,X.executionId),lr=(Ko=(hn=(co=(Wr=L.text)!=null?Wr:L.delta)!=null?co:L.content)!=null?hn:L.chunk)!=null?Ko:"";lr&&($t.content+=String(lr),$t.streaming=!0,p($t)),L.isComplete&&($t.streaming=!1,p($t));continue}let re=L.partId;if(re!==void 0&&T.current!==null&&re!==T.current){let Oe=m;Oe&&(Oe.streaming=!1,p(Oe),gt=Oe,m=null,E=!0)}re!==void 0&&(T.current=re);let K=re!==void 0&&(xn=Lt.get(re))!=null?xn:Ce();re!==void 0&&(K.partId||(K.partId=re),Lt.set(re,K));let Ae=(dt=(xe=(Jr=(Ro=L.text)!=null?Ro:L.delta)!=null?Jr:L.content)!=null?xe:L.chunk)!=null?dt:"";if(Ae){let Oe=typeof L.seq=="number"?L.seq:void 0,at=re!=null?re:K.id,tt=Oe!==void 0?_e(at,Oe,String(Ae)):((tr=ie.get(K.id))!=null?tr:"")+Ae;K.rawContent=tt,ee.has(K.id)||ee.set(K.id,this.createStreamParser());let Bt=ee.get(K.id),$t=tt.trim().startsWith("{")||tt.trim().startsWith("[");if($t&&ie.set(K.id,tt),Bt.__isPlainTextParser===!0){K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K);continue}let wt=Bt.processChunk(tt);if(wt instanceof Promise)wt.then(Tt=>{var Hr;let br=typeof Tt=="string"?Tt:(Hr=Tt==null?void 0:Tt.text)!=null?Hr:null;if(br!==null&&br.trim()!=="")K.content=br,p(K);else if(!$t&&!tt.trim().startsWith("<")){let Sr=m,Zt=Sr&&Sr.id===K.id?Sr:K;Zt.id===K.id&&(Zt.content=Oe!==void 0?tt:Zt.content+Ae,ie.delete(Zt.id),ee.delete(Zt.id),Zt.rawContent=void 0,p(Zt))}}).catch(()=>{K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K)});else{let Tt=typeof wt=="string"?wt:(fr=wt==null?void 0:wt.text)!=null?fr:null;Tt!==null&&Tt.trim()!==""?(K.content=Tt,p(K)):!$t&&!tt.trim().startsWith("<")&&(K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K))}}if(L.isComplete){let Oe=(es=(Io=L.result)==null?void 0:Io.response)!=null?es:K.content;if(Oe){let at=ie.get(K.id),tt=at!=null?at:ne(Oe);K.rawContent=tt;let Bt=ee.get(K.id),$t=null,lr=!1;if(Bt&&($t=Bt.getExtractedText(),$t===null&&($t=ra(tt)),$t===null)){let wt=Bt.processChunk(tt);wt instanceof Promise?(lr=!0,wt.then(Tt=>{var Hr;let br=typeof Tt=="string"?Tt:(Hr=Tt==null?void 0:Tt.text)!=null?Hr:null;if(br!==null){let Sr=m;Sr&&Sr.id===K.id&&(Sr.content=br,Sr.streaming=!1,ee.delete(Sr.id),ie.delete(Sr.id),p(Sr))}})):$t=typeof wt=="string"?wt:(Xo=wt==null?void 0:wt.text)!=null?Xo:null}if(!lr){$t!==null&&$t.trim()!==""?K.content=$t:ie.has(K.id)||(K.content=ne(Oe));let wt=ee.get(K.id);if(wt){let Tt=(qn=wt.close)==null?void 0:qn.call(wt);Tt instanceof Promise&&Tt.catch(()=>{}),ee.delete(K.id)}ie.delete(K.id),K.streaming=!1,p(K)}}}}else if(Ve==="step_complete"){let U=L.stepType,I=L.executionType;if(U==="tool"||I==="context")continue;let X=L.toolContext;if(X!=null&&X.toolId){let Oe=String((_=(Wo=L.id)!=null?Wo:X.stepId)!=null?_:"");if(Oe){let at=W(X.toolId,Oe);for(let[tt,Bt]of y)tt.startsWith(at)&&Bt.streaming!==!1&&(Bt.streaming=!1,p(Bt));w.delete(`${X.toolId}::${Oe}`)}continue}let re=L.stopReason;if(E){if(m!==null){let tt=m;re&&(tt.stopReason=re),ee.delete(tt.id),ie.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,p(tt))}let Oe=(ha=L.result)==null?void 0:ha.response,at=gt;at&&(re&&(at.stopReason=re),Oe!=null?be(at,Oe):(ee.delete(at.id),ie.delete(at.id))),gt=null;continue}let K=(Ho=L.result)==null?void 0:Ho.response,Ae=Ce();if(re&&(Ae.stopReason=re),K!=null){let Oe=ee.get(Ae.id),at=!1,tt=!1;if(Oe){let Bt=Oe.getExtractedText(),$t=ie.get(Ae.id),lr=$t!=null?$t:ne(K);if(Ae.rawContent=lr,Bt!==null&&Bt.trim()!=="")Ae.content=Bt,at=!0;else{let wt=ra(lr);if(wt!==null)Ae.content=wt,at=!0;else{let Tt=Oe.processChunk(lr);if(Tt instanceof Promise)tt=!0,Tt.then(br=>{var Sr;let Hr=typeof br=="string"?br:(Sr=br==null?void 0:br.text)!=null?Sr:null;if(Hr!==null&&Hr.trim()!==""){let Zt=m;Zt&&Zt.id===Ae.id&&(Zt.content=Hr,Zt.streaming=!1,ee.delete(Zt.id),ie.delete(Zt.id),p(Zt))}else{let Zt=Oe.getExtractedText(),uo=m;uo&&uo.id===Ae.id&&(Zt!==null&&Zt.trim()!==""?uo.content=Zt:ie.has(uo.id)||(uo.content=ne(K)),uo.streaming=!1,ee.delete(uo.id),ie.delete(uo.id),p(uo))}});else{let br=typeof Tt=="string"?Tt:(Bo=Tt==null?void 0:Tt.text)!=null?Bo:null;if(br!==null&&br.trim()!=="")Ae.content=br,at=!0;else{let Hr=Oe.getExtractedText();Hr!==null&&Hr.trim()!==""&&(Ae.content=Hr,at=!0)}}}}}if(!tt){if(!Ae.rawContent){let Bt=ie.get(Ae.id);Ae.rawContent=Bt!=null?Bt:ne(K)}if(!at&&!ie.has(Ae.id)&&(Ae.content=ne(K)),Oe){let Bt=(Qo=Oe.close)==null?void 0:Qo.call(Oe);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Ae.id),ie.delete(Ae.id),Ae.streaming=!1,p(Ae)}}else ee.delete(Ae.id),ie.delete(Ae.id),Ae.streaming=!1,p(Ae)}else if(Ve==="flow_complete"){let U=(Do=L.result)==null?void 0:Do.response;if(E){if(m!==null){let I=m;ee.delete(I.id),ie.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}}else if(U!=null){let I=Ce(),X=ie.get(I.id),re=X!=null?X:ne(U);I.rawContent=re;let K=ne(U),Ae=ee.get(I.id);if(Ae){let tt=ra(re);if(tt!==null)K=tt;else{let Bt=Ae.processChunk(re);Bt instanceof Promise&&Bt.then(lr=>{var Tt;let wt=typeof lr=="string"?lr:(Tt=lr==null?void 0:lr.text)!=null?Tt:null;wt!==null&&(I.content=wt,I.streaming=!1,p(I))});let $t=Ae.getExtractedText();$t!==null&&(K=$t)}}ee.delete(I.id),ie.delete(I.id);let Oe=K!==I.content,at=I.streaming!==!1;Oe&&(I.content=K),I.streaming=!1,(Oe||at)&&p(I)}else if(m!==null){let I=m;ee.delete(I.id),ie.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}r({type:"status",status:"idle"})}else if(Ve==="agent_start")Ge={executionId:L.executionId,agentId:(bo=L.agentId)!=null?bo:"virtual",agentName:(xa=L.agentName)!=null?xa:"",status:"running",currentIteration:0,maxTurns:(Qs=L.maxTurns)!=null?Qs:1,startedAt:Be(L.startedAt)};else if(Ve==="agent_iteration_start"){if(Ge&&(Ge.currentIteration=L.iteration),je==="separate"&&L.iteration>1){let U=m;U&&(U.streaming=!1,p(U),ke.set(L.iteration-1,U),m=null)}}else if(Ve==="agent_turn_start")x=null;else if(Ve==="agent_turn_delta"){if(L.contentType==="text"){let U=Ce();U.content+=(Yr=L.delta)!=null?Yr:"",U.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:Ge==null?void 0:Ge.agentName},x=U,p(U)}else if(L.contentType==="thinking"){let U=(Zr=L.turnId)!=null?Zr:`agent-think-${L.iteration}`,I=Te(U);I.reasoning=(vo=I.reasoning)!=null?vo:{id:U,status:"streaming",chunks:[]},I.reasoning.chunks.push((Co=L.delta)!=null?Co:""),I.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},p(I)}else if(L.contentType==="tool_input"){let U=(Vn=L.toolCallId)!=null?Vn:A.lastId;if(U){let I=P.get(U);I!=null&&I.toolCall&&(I.toolCall.chunks=(Jo=I.toolCall.chunks)!=null?Jo:[],I.toolCall.chunks.push((Mr=L.delta)!=null?Mr:""),p(I))}}}else if(Ve==="agent_turn_complete"){let U=L.turnId;if(U){let re=M.get(U);if(re!=null&&re.reasoning){re.reasoning.status="complete",re.reasoning.completedAt=Be(L.completedAt);let K=(Fo=re.reasoning.startedAt)!=null?Fo:Date.now();re.reasoning.durationMs=Math.max(0,((ya=re.reasoning.completedAt)!=null?ya:Date.now())-K),re.streaming=!1,p(re)}}let I=L.stopReason,X=m!=null?m:x;if(I&&X!==null){let re=L.turnId;(!re||(($n=X.agentMetadata)==null?void 0:$n.turnId)===re)&&(X.stopReason=I,p(X))}}else if(Ve==="agent_tool_start"){m&&(m.streaming=!1,p(m),m=null);let U=(ba=L.toolCallId)!=null?ba:`agent-tool-${d()}`;We(Z(L),U);let I=ce(U),X=(Js=I.toolCall)!=null?Js:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};X.name=(Ys=(va=L.toolName)!=null?va:L.name)!=null?Ys:X.name,X.status="running",L.parameters!==void 0&&(X.args=L.parameters),X.startedAt=Be((Ca=L.startedAt)!=null?Ca:L.timestamp),I.toolCall=X,I.streaming=!0,I.agentMetadata={executionId:L.executionId,iteration:L.iteration},p(I)}else if(Ve==="agent_tool_delta"){let U=(mt=L.toolCallId)!=null?mt:A.lastId;if(U){let I=(ts=P.get(U))!=null?ts:ce(U);I.toolCall&&(I.toolCall.chunks=(po=I.toolCall.chunks)!=null?po:[],I.toolCall.chunks.push((Vr=L.delta)!=null?Vr:""),I.toolCall.status="running",I.streaming=!0,p(I))}}else if(Ve==="agent_tool_complete"){let U=(Zs=L.toolCallId)!=null?Zs:A.lastId;if(U){let I=(ei=P.get(U))!=null?ei:ce(U);if(I.toolCall){I.toolCall.status="complete",L.result!==void 0&&(I.toolCall.result=L.result),typeof L.executionTime=="number"&&(I.toolCall.durationMs=L.executionTime),I.toolCall.completedAt=Be((wa=L.completedAt)!=null?wa:L.timestamp),I.streaming=!1,p(I);let X=Z(L);X&&A.byCall.delete(X)}}}else if(Ve==="agent_media"){let U=Array.isArray(L.media)?L.media:[],I=[];for(let X of U){if(!X||typeof X!="object")continue;let re=X,K=typeof re.type=="string"?re.type:void 0,Ae=typeof re.mediaType=="string"?re.mediaType.toLowerCase():"",Oe=null,at="";if(K==="media"){let tt=typeof re.data=="string"?re.data:void 0;if(!tt)continue;at=Ae.length>0?Ae:"application/octet-stream",Oe=`data:${at};base64,${tt}`}else if(K==="image-url"){let tt=typeof re.url=="string"?re.url:void 0;if(!tt)continue;at=Ae,Oe=tt}else if(K==="file-url"){let tt=typeof re.url=="string"?re.url:void 0;if(!tt)continue;at=Ae,Oe=tt}else continue;if(Oe)if(K==="image-url"||at.startsWith("image/"))I.push({type:"image",image:Oe,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))I.push({type:"audio",audio:Oe,mimeType:at});else if(at.startsWith("video/"))I.push({type:"video",video:Oe,mimeType:at});else{let tt=at||"application/octet-stream";I.push({type:"file",data:Oe,mimeType:tt,filename:$y(tt)})}}if(I.length>0){let X=d(),re=L.toolCallId,Ae={id:`agent-media-${typeof re=="string"&&re.length>0?`${re}-${X}`:String(X)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:X,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};p(Ae);let Oe=m;Oe&&(Oe.streaming=!1,p(Oe)),m=null,C.current=null}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let U=`agent-reflection-${L.executionId}-${L.iteration}`,I={id:U,role:"assistant",content:(Yo=L.reflection)!=null?Yo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:d(),reasoning:{id:U,status:"complete",chunks:[(rs=L.reflection)!=null?rs:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};p(I)}else if(Ve==="agent_complete"){Ge&&(Ge.status=L.success?"complete":"error",Ge.completedAt=Be(L.completedAt),Ge.stopReason=L.stopReason);let U=m;U&&(U.streaming=!1,p(U)),r({type:"status",status:"idle"})}else if(Ve==="agent_error"){let U=typeof L.error=="string"?L.error:(os=(yn=L.error)==null?void 0:yn.message)!=null?os:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):r({type:"error",error:new Error(U)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let U=(ns=L.approvalId)!=null?ns:`approval-${d()}`,I={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:"pending",agentId:(as=Ge==null?void 0:Ge.agentId)!=null?as:"virtual",executionId:($r=(ss=L.executionId)!=null?ss:Ge==null?void 0:Ge.executionId)!=null?$r:"",toolName:(Sa=L.toolName)!=null?Sa:"",toolType:L.toolType,description:(Oo=L.description)!=null?Oo:`Execute ${(No=L.toolName)!=null?No:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};p(I)}else if(Ve==="step_await"&&L.awaitReason==="approval_required"){let U=(is=L.approvalId)!=null?is:`approval-${d()}`,I={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:"pending",agentId:(ti=Ge==null?void 0:Ge.agentId)!=null?ti:"virtual",executionId:(ds=(ls=L.executionId)!=null?ls:Ge==null?void 0:Ge.executionId)!=null?ds:"",toolName:(zn=L.toolName)!=null?zn:"",toolType:L.toolType,description:(oi=L.description)!=null?oi:`Execute ${(ri=L.toolName)!=null?ri:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};p(I)}else if(Ve==="agent_approval_complete"){let U=L.approvalId;if(U){let X={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:(ni=L.decision)!=null?ni:"approved",agentId:(ai=Ge==null?void 0:Ge.agentId)!=null?ai:"virtual",executionId:(bn=(si=L.executionId)!=null?si:Ge==null?void 0:Ge.executionId)!=null?bn:"",toolName:(vn=L.toolName)!=null?vn:"",description:(ii=L.description)!=null?ii:"",resolvedAt:Date.now()}};p(X)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let U=L.artifactType,I=String(L.id),X=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:I,artifactType:U,title:X,component:typeof L.component=="string"?L.component:void 0}),ge.set(I,{markdown:"",title:X}),!le.has(I)){le.add(I);let re={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:X,artifactType:U,status:"streaming"}})};J.set(I,re),p(re)}}else if(Ve==="artifact_delta"){let U=String(L.id),I=typeof L.delta=="string"?L.delta:String((cs=L.delta)!=null?cs:"");r({type:"artifact_delta",id:U,artDelta:I});let X=ge.get(U);X&&(X.markdown+=I)}else if(Ve==="artifact_update"){let U=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:U,component:typeof L.component=="string"?L.component:void 0})}else if(Ve==="artifact_complete"){let U=String(L.id);r({type:"artifact_complete",id:U});let I=J.get(U);if(I){I.streaming=!1;try{let X=JSON.parse((Cn=I.rawContent)!=null?Cn:"{}");if(X.props){X.props.status="complete";let re=ge.get(U);re!=null&&re.markdown&&(X.props.markdown=re.markdown)}I.rawContent=JSON.stringify(X)}catch{}ge.delete(U),p(I),J.delete(U)}}}else if(Ve==="transcript_insert"){let U=L.message;if(!U||typeof U!="object")continue;let I=String((li=U.id)!=null?li:`msg-${d()}`),X=U.role,K={id:I,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:d()};if(p(K),K.rawContent)try{let Ae=JSON.parse(K.rawContent),Oe=(ps=Ae==null?void 0:Ae.props)==null?void 0:ps.artifactId;typeof Oe=="string"&&le.add(Oe)}catch{}m=null,C.current=null,ee.delete(I),ie.delete(I)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let U=null;if(L.error instanceof Error)U=L.error;else if(Ve==="dispatch_error"){let I=(wn=L.message)!=null?wn:L.error;I!=null&&I!==""&&(U=new Error(String(I)))}else if(Ve==="step_error"||Ve==="flow_error"){let I=L.error;typeof I=="string"&&I!==""?U=new Error(I):I!=null&&typeof I=="object"&&"message"in I&&(U=new Error(String((us=I.message)!=null?us:I)))}else Ve==="error"&&L.error!=null&&L.error!==""&&(U=new Error(String(L.error)));if(U){r({type:"error",error:U});let I=m;I&&I.streaming&&(I.streaming=!1,p(I)),r({type:"status",status:"idle"})}}}}}Ze.length=0};;){let{done:V,value:j}=await n.read();if(V)break;s+=a.decode(j,{stream:!0});let he=s.split(`
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()=>{}}},ra=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Pi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ii=()=>{var t;let e=$y();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)}},Ri=()=>{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,nn.parse)(r,nn.STR|nn.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?Ti(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=Ti(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Og=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?Ti(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Ti(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,nn.parse)(a,nn.STR|nn.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},Wi=()=>{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 Hi=class{constructor(t,r=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=r}push(t,r){var a,s,i;let o=(i=(a=r==null?void 0:r.seq)!=null?a:r==null?void 0:r.sequenceIndex)!=null?i:(s=r==null?void 0:r.agentContext)==null?void 0:s.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,r);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,r),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,r);return}let n=this.buffer.get(o);n!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${n.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(n.payloadType,n.payload)),this.buffer.set(o,{payloadType:t,payload:r,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((r,o)=>r[0]-o[0]);for(let[r,o]of t)this.buffer.delete(r),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var _g="webmcp:";function Ug(e){return e==="execution_start"}var Bi=class{constructor(t){this.kind="agent";this.iteration=1;this.openTurnId=null;this.openStepId=null;this.openTextBlockId=null;this.openReasoningId=null;this.mediaBuffers=new Map;var r;this.executionId=(r=t==null?void 0:t.executionId)!=null?r:""}push(t,r){var o,n,a,s,i,c,d,u,g,p,m,x,C,T,E;switch(typeof r.executionId=="string"&&r.executionId&&(this.executionId=r.executionId),typeof r.iteration=="number"&&(this.iteration=r.iteration),t){case"execution_start":return this.kind=r.kind==="flow"?"flow":"agent",this.kind!=="agent"?[]:[this.out("agent_start",{executionId:this.executionId,agentId:r.agentId,agentName:r.agentName,maxTurns:r.maxTurns,startedAt:r.startedAt})];case"turn_start":return this.openTurnId=typeof r.id=="string"?r.id:null,this.kind!=="agent"?[]:[this.out("agent_turn_start",{turnId:r.id,iteration:r.iteration})];case"turn_complete":{let w=this.kind==="agent"?[this.out("agent_turn_complete",{turnId:r.id,iteration:r.iteration,stopReason:r.stopReason,completedAt:r.completedAt})]:[];return this.openTurnId===r.id&&(this.openTurnId=null),w}case"execution_complete":return((o=r.kind)!=null?o:this.kind)==="agent"?[this.out("agent_complete",{executionId:this.executionId,success:r.success,completedAt:r.completedAt,stopReason:r.stopReason})]:[this.out("flow_complete",{success:r.success,completedAt:r.completedAt,duration:r.durationMs,finalOutput:r.finalOutput,totalSteps:r.totalSteps,successfulSteps:r.successfulSteps,failedSteps:r.failedSteps})];case"execution_error":return((n=r.kind)!=null?n:this.kind)==="agent"?[this.out("agent_error",{recoverable:!1,error:r.error})]:[this.out("flow_error",{error:r.error,code:r.code,upgradeUrl:r.upgradeUrl})];case"error":return[this.out("agent_error",{recoverable:!0,error:r.error})];case"ping":return[this.out("agent_ping",{timestamp:r.timestamp})];case"text_start":return this.openTextBlockId=typeof r.id=="string"?r.id:null,[];case"text_delta":{let w=String((a=r.delta)!=null?a:"");return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"text",delta:w,turnId:(s=this.openTurnId)!=null?s:r.id,iteration:this.iteration,executionId:this.executionId})]:[this.out("step_delta",{id:(i=this.openStepId)!=null?i:r.id,text:w,stepType:"prompt"})]}case"text_complete":return this.openTextBlockId===r.id&&(this.openTextBlockId=null),[];case"reasoning_start":return this.openReasoningId=typeof r.id=="string"?r.id:null,this.kind==="flow"?[this.out("reason_start",{id:r.id})]:[];case"reasoning_delta":{let w=String((c=r.delta)!=null?c:"");return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"thinking",delta:w,turnId:(d=this.openTurnId)!=null?d:r.id,iteration:this.iteration,executionId:this.executionId})]:[this.out("reason_delta",{id:r.id,delta:w})]}case"reasoning_complete":{let w=typeof r.text=="string"&&r.text.length>0;if(this.kind==="agent")return r.scope==="loop"||w?[this.out("agent_reflection",{reflection:(u=r.text)!=null?u:"",executionId:this.executionId,iteration:this.iteration})]:[];let k=[];return w&&k.push(this.out("reason_delta",{id:r.id,delta:r.text})),k.push(this.out("reason_complete",{id:r.id})),k}case"tool_start":return this.kind==="agent"?[this.out("agent_tool_start",{toolCallId:r.toolCallId,toolName:r.toolName,parameters:r.parameters,executionId:this.executionId,iteration:(g=r.iteration)!=null?g:this.iteration,startedAt:r.startedAt})]:[this.out("tool_start",{toolId:r.toolCallId,toolName:r.toolName,parameters:r.parameters,executionId:this.executionId,iteration:(p=r.iteration)!=null?p:this.iteration,startedAt:r.startedAt})];case"tool_input_delta":return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"tool_input",delta:String((m=r.delta)!=null?m:""),toolCallId:r.toolCallId})]:[];case"tool_input_complete":return[];case"tool_output_delta":{let w=String((x=r.delta)!=null?x:"");return this.kind==="agent"?[this.out("agent_tool_delta",{toolCallId:r.toolCallId,delta:w})]:[this.out("tool_delta",{toolId:r.toolCallId,delta:w})]}case"tool_complete":return this.kind==="agent"?[this.out("agent_tool_complete",{toolCallId:r.toolCallId,result:r.result,executionTime:r.executionTime,completedAt:r.completedAt})]:[this.out("tool_complete",{toolId:r.toolCallId,result:r.result,duration:r.executionTime,completedAt:r.completedAt})];case"media_start":{let w=String(r.id);return this.mediaBuffers.set(w,{mediaType:typeof r.mediaType=="string"?r.mediaType:void 0,role:typeof r.role=="string"?r.role:void 0,toolCallId:r.toolCallId,parts:[]}),[]}case"media_delta":{let w=this.mediaBuffers.get(String(r.id));return w&&typeof r.delta=="string"&&w.parts.push(r.delta),[]}case"media_complete":{let w=String(r.id),k=this.mediaBuffers.get(w);this.mediaBuffers.delete(w);let y=(T=(C=typeof r.mediaType=="string"?r.mediaType:void 0)!=null?C:k==null?void 0:k.mediaType)!=null?T:"application/octet-stream",S=typeof r.data=="string"?r.data:void 0,b=typeof r.url=="string"?r.url:k&&k.parts.length>0?k.parts.join(""):void 0,M=null;return S?M={type:"media",data:S,mediaType:y}:b&&(M={type:y.startsWith("image/")?"image-url":"file-url",url:b,mediaType:y}),M?[this.out("agent_media",{media:[M],executionId:this.executionId,iteration:this.iteration,toolCallId:(E=r.toolCallId)!=null?E:k==null?void 0:k.toolCallId})]:[]}case"approval_start":return[this.out("agent_approval_start",{approvalId:r.approvalId,toolName:r.toolName,toolType:r.toolType,description:r.description,reason:r.reason,parameters:r.parameters,executionId:this.executionId})];case"approval_complete":return[this.out("agent_approval_complete",{approvalId:r.approvalId,decision:r.decision,executionId:this.executionId,toolName:r.toolName,description:r.description})];case"await":{let w=typeof r.toolName=="string"?r.toolName:"",k=r.origin==="webmcp"&&!w.startsWith(_g)?`${_g}${w}`:w;return[this.out("step_await",{awaitReason:"local_tool_required",toolName:k,parameters:r.parameters,toolCallId:r.toolCallId,toolId:r.toolId,executionId:this.executionId,awaitedAt:r.awaitedAt})]}case"step_start":return this.openStepId=typeof r.id=="string"?r.id:null,[this.out("step_start",{id:r.id,name:r.name,stepType:r.stepType,index:r.index,totalSteps:r.totalSteps,startedAt:r.startedAt,outputVariable:r.outputVariable})];case"step_complete":{let w=this.out("step_complete",{id:r.id,name:r.name,stepType:r.stepType,success:r.success,duration:r.durationMs,result:r.result,stopReason:r.stopReason,completedAt:r.completedAt,unresolvedVariables:r.unresolvedVariables});return this.openStepId===r.id&&(this.openStepId=null),[w]}case"step_skip":return[];case"artifact_start":return[this.out("artifact_start",{id:r.id,artifactType:r.artifactType,title:r.title,component:r.component})];case"artifact_delta":return[this.out("artifact_delta",{id:r.id,delta:r.delta})];case"artifact_update":return[this.out("artifact_update",{id:r.id,component:r.component,props:r.props})];case"artifact_complete":return[this.out("artifact_complete",{id:r.id})];case"source":case"custom":return[];default:return[]}}out(t,r){let o={};for(let[n,a]of Object.entries(r))a!==void 0&&(o[n]=a);return{payloadType:t,payload:o}}};var qg="3.37.0";var oa=qg;var jy="https://api.runtype.com/v1/dispatch",Di="https://api.runtype.com";function Gy(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 sd=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 Ky(e){switch(e){case"json":return Ri;case"regex-json":return Ii;case"xml":return Wi;default:return Pi}}var Vg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Xy(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=Vg(r);if(!Vg(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ra(e);return ra(t)!==null&&s===null?t:e}var na=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:jy,this.headers={"Content-Type":"application/json","X-Persona-Version":oa,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Ky(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 Wa(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}withEventsParam(t){return this.config.events!=="unified"?t:t+(t.includes("?")?"&":"?")+"events=unified"}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Di}/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":oa},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$/,""))||Di}/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":oa},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 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:c.sessionId,messages:t.messages.filter(sd).map(y=>{var S,b,M;return{id:y.id,role:y.role,content:(M=(b=(S=y.contentParts)!=null?S:y.llmContent)!=null?b:y.rawContent)!=null?M: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}},p=d.clientTools,m=!!(p&&p.length>0),x=m?Cg(p):void 0,C=this.clientToolsFingerprintSessionId===c.sessionId,T=m&&C&&this.lastSentClientToolsFingerprint===x,E=!1,w=null,k;for(let y=0;;y++){let b={...g,...m&&(E||!T)&&p?{clientTools:p}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",b),k=await fetch(this.withEventsParam(this.getClientApiUrl("chat")),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":oa},body:JSON.stringify(b),signal:o.signal}),k.status===409&&y===0&&m){let M=await k.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}w=M!=null?M:{error:"Chat request failed"}}break}if(!k.ok){let y=w!=null?w:await k.json().catch(()=>({error:"Chat request failed"}));if(k.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(k.status===429){let b=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:b}),b}let S=new Error(y.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!k.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(k.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let d=c instanceof Error?c:new Error(String(c));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.withEventsParam(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.withEventsParam(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.withEventsParam(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.withEventsParam(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$/,""))||Di}/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=this.withEventsParam(n?this.getClientApiUrl("resume"):`${((d=this.config.apiUrl)==null?void 0:d.replace(/\/+$/,""))||Di}/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:(u=o==null?void 0:o.streamResponse)!=null?u:!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(sd).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,c)=>{let d=new Date(i.createdAt).getTime(),u=new Date(c.createdAt).getTime();return d-u}).map(i=>{var c,d,u;return{role:i.role,content:(u=(d=(c=i.contentParts)!=null?c: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=[...As(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 d=await c({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(sd).sort((i,c)=>{let d=new Date(i.createdAt).getTime(),u=new Date(c.createdAt).getTime();return d-u}).map(i=>{var c,d,u;return{role:i.role,content:(u=(d=(c=i.contentParts)!=null?c:i.llmContent)!=null?d:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},n=[...As(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 d=await c({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 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=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:c(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)),c(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 To,Tr,je,Nt;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,d=()=>i+c++,u=V=>{let Me=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,we=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,He=V.tools?V.tools.map(nt=>({...nt,chunks:nt.chunks?[...nt.chunks]:void 0})):void 0;return{...V,reasoning:Me,toolCall:we,tools:He}},g=V=>{if(V.role!=="assistant"||V.variant)return!0;let Me=Array.isArray(V.contentParts)&&V.contentParts.length>0,we=typeof V.rawContent=="string"&&V.rawContent.trim()!=="";return typeof V.content=="string"&&V.content.trim()!==""||Me||we||!!V.stopReason},p=V=>{g(V)&&r({type:"message",message:u(V)})},m=null,x=null,C={current:null},T={current:null},E=!1,w=new Map,k=new Map,y=new Map,S=new Map,b={lastId:null,byStep:new Map},M={lastId:null,byCall:new Map},W=(V,Me,we="")=>`${V}::${Me}::${we}`,R=(V,Me)=>`${V}::${Me}::`,L=(V,Me,we,He)=>{let nt=W(V,Me,we),lt=y.get(nt);if(lt)return lt;let ot=we?`-${we}`:"",Tt={id:`nested-${V}-${Me}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...we?{partId:we}:{},agentMetadata:{executionId:He,parentToolId:V,parentStepId:Me}};return y.set(nt,Tt),p(Tt),Tt},N=V=>{if(V==null)return null;try{return String(V)}catch{return null}},q=V=>{var Me,we,He,nt,lt;return N((lt=(nt=(He=(we=(Me=V.stepId)!=null?Me:V.step_id)!=null?we:V.step)!=null?He:V.parentId)!=null?nt:V.flowStepId)!=null?lt:V.flow_step_id)},Y=V=>{var Me,we,He,nt,lt,ot,Tt;return N((Tt=(ot=(lt=(nt=(He=(we=(Me=V.callId)!=null?Me:V.call_id)!=null?we:V.requestId)!=null?He:V.request_id)!=null?nt:V.toolCallId)!=null?lt:V.tool_call_id)!=null?ot:V.stepId)!=null?Tt:V.step_id)},me=o,Ge=!1,Ce=()=>{if(m)return m;let V;return!Ge&&me?(V=me,Ge=!0):me&&T.current?V=`${me}_${T.current}`:V=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:V,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d()},p(m),m},Be=(V,Me)=>{b.lastId=Me,V&&b.byStep.set(V,Me)},qe=(V,Me)=>{var lt;let we=(lt=V.reasoningId)!=null?lt:V.id,He=q(V);if(we){let ot=String(we);return Be(He,ot),ot}if(He){let ot=b.byStep.get(He);if(ot)return b.lastId=ot,ot}if(b.lastId&&!Me)return b.lastId;if(!Me)return null;let nt=`reason-${d()}`;return Be(He,nt),nt},Ee=V=>{let Me=w.get(V);if(Me)return Me;let we={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:V,status:"streaming",chunks:[]}};return w.set(V,we),p(we),we},De=(V,Me)=>{M.lastId=Me,V&&M.byCall.set(V,Me)},le=new Set,Q=new Map,ie=new Set,ge=new Map,ue=V=>{if(!V)return!1;let Me=V.replace(/_+/g,"_").replace(/^_|_$/g,"");return Me==="emit_artifact_markdown"||Me==="emit_artifact_component"},j=(V,Me)=>{var lt;let we=(lt=V.toolId)!=null?lt:V.id,He=Y(V);if(we){let ot=String(we);return De(He,ot),ot}if(He){let ot=M.byCall.get(He);if(ot)return M.lastId=ot,ot}if(M.lastId&&!Me)return M.lastId;if(!Me)return null;let nt=`tool-${d()}`;return De(He,nt),nt},de=V=>{let Me=k.get(V);if(Me)return Me;let we={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:V,status:"pending"}};return k.set(V,we),p(we),we},Ne=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let Me=Number(V);if(!Number.isNaN(Me)&&Number.isFinite(Me))return Me;let we=Date.parse(V);if(!Number.isNaN(we))return we}return Date.now()},te=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},Z=new Map,ae=new Map,wt=new Map,Pt=new Map,xt=null,Ue=(V,Me,we)=>{var Tt;let He=wt.get(V);He||(He=[],wt.set(V,He));let nt=0,lt=He.length;for(;nt<lt;){let z=nt+lt>>>1;He[z].seq<Me?nt=z+1:lt=z}((Tt=He[nt])==null?void 0:Tt.seq)===Me?He[nt]={seq:Me,text:we}:He.splice(nt,0,{seq:Me,text:we});let ot="";for(let z=0;z<He.length;z++)ot+=He[z].text;return ot},be=(V,Me)=>{let we=te(Me),He=ae.get(V.id),nt=Xy(He,we);V.rawContent=nt;let lt=Z.get(V.id),ot=pe=>{var dt;let Ae=(dt=V.content)!=null?dt:"";pe.trim()!==""&&(Ae.trim().length===0||pe.startsWith(Ae)||pe.trimStart().startsWith(Ae.trim()))&&(V.content=pe)},Tt=()=>{var pe;if(lt){let Ae=(pe=lt.close)==null?void 0:pe.call(lt);Ae instanceof Promise&&Ae.catch(()=>{})}Z.delete(V.id),ae.delete(V.id),V.streaming=!1,p(V)};if(!lt){ot(we),Tt();return}let z=ra(nt);if(z!==null&&z.trim()!==""){ot(z),Tt();return}let St=pe=>{var er;let Ae=typeof pe=="string"?pe:(er=pe==null?void 0:pe.text)!=null?er:null;if(Ae!==null&&Ae.trim()!=="")return Ae;let dt=lt.getExtractedText();return dt!==null&&dt.trim()!==""?dt:we},se;try{se=lt.processChunk(nt)}catch{ot(we),Tt();return}if(se instanceof Promise){se.then(pe=>{ot(St(pe)),Tt()}).catch(()=>{ot(we),Tt()});return}ot(St(se)),Tt()},Je=[],J=!1,ce,Te=()=>{J||(J=!0,queueMicrotask(()=>{J=!1,ce()}))},Xe=new Hi((V,Me)=>{Je.push({payloadType:V,payload:Me}),Te()}),Kt=new Bi,ke=this.config.events==="unified",Ve=!1,rt=null,Ft=new Map,vr=(To=this.config.iterationDisplay)!=null?To:"separate";for(ce=()=>{var V,Me,we,He,nt,lt,ot,Tt,z,St,se,pe,Ae,dt,er,ir,Sr,_t,et,Ot,ct,tr,io,Wr,lr,qr,Eo,vt,Gr,ko,$o,xo,yt,Nn,Lo,On,Vr,ga,cn,zo,pn,un,_n,Un,fn,At,Kr,Xr,Hr,Et,lo,co,Qr,mn,jo,gn,Jr,Ut,Br,po,hn,Go,xn,Po,Yr,xe,pt,or,fr,Io,Za,Ko,qn,Ro,_,ha,Wo,Ho,Xo,Bo,yo,xa,Xs,Zr,eo,bo,vo,Vn,Qo,Er,Do,ya,$n,ba,Qs,va,Js,Ca,ht,es,uo,$r,Ys,Zs,wa,Jo,ts,yn,rs,os,ns,as,zr,Sa,Fo,No,ss,ei,is,ls,zn,ti,ri,oi,ni,ai,bn,vn,si,ds,Cn,ii,cs,wn,ps,li,Yo,di;for(let Oo=0;Oo<Je.length;Oo++){let he=Je[Oo].payloadType,P=Je[Oo].payload;if(he==="reason_start"){let U=(V=qe(P,!0))!=null?V:`reason-${d()}`,H=Ee(U);H.reasoning=(Me=H.reasoning)!=null?Me:{id:U,status:"streaming",chunks:[]},H.reasoning.startedAt=(He=H.reasoning.startedAt)!=null?He:Ne((we=P.startedAt)!=null?we:P.timestamp),H.reasoning.completedAt=void 0,H.reasoning.durationMs=void 0,H.streaming=!0,H.reasoning.status="streaming",p(H)}else if(he==="reason_delta"||he==="reason_chunk"){let U=(lt=(nt=qe(P,!1))!=null?nt:qe(P,!0))!=null?lt:`reason-${d()}`,H=Ee(U);H.reasoning=(ot=H.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},H.reasoning.startedAt=(z=H.reasoning.startedAt)!=null?z:Ne((Tt=P.startedAt)!=null?Tt:P.timestamp);let G=(pe=(se=(St=P.reasoningText)!=null?St:P.text)!=null?se:P.delta)!=null?pe:"";if(G&&P.hidden!==!0){let re=typeof P.sequenceIndex=="number"?P.sequenceIndex:void 0;if(re!==void 0){let K=Ue(U,re,String(G));H.reasoning.chunks=[K]}else H.reasoning.chunks.push(String(G))}if(H.reasoning.status=P.done?"complete":"streaming",P.done){H.reasoning.completedAt=Ne((Ae=P.completedAt)!=null?Ae:P.timestamp);let re=(dt=H.reasoning.startedAt)!=null?dt:Date.now();H.reasoning.durationMs=Math.max(0,((er=H.reasoning.completedAt)!=null?er:Date.now())-re)}H.streaming=H.reasoning.status!=="complete",p(H)}else if(he==="reason_complete"){let U=(Sr=(ir=qe(P,!1))!=null?ir:qe(P,!0))!=null?Sr:`reason-${d()}`,H=w.get(U);if(H!=null&&H.reasoning){H.reasoning.status="complete",H.reasoning.completedAt=Ne((_t=P.completedAt)!=null?_t:P.timestamp);let re=(et=H.reasoning.startedAt)!=null?et:Date.now();H.reasoning.durationMs=Math.max(0,((Ot=H.reasoning.completedAt)!=null?Ot:Date.now())-re),H.streaming=!1,p(H)}let G=q(P);G&&b.byStep.delete(G)}else if(he==="tool_start"){let U=(ct=j(P,!0))!=null?ct:`tool-${d()}`,H=(tr=P.toolName)!=null?tr:P.name;if(ue(H)){le.add(U);continue}let G=de(U),re=(io=G.toolCall)!=null?io:{id:U,status:"pending"};re.name=H!=null?H:re.name,re.status="running",P.args!==void 0?re.args=P.args:P.parameters!==void 0&&(re.args=P.parameters),re.startedAt=(lr=re.startedAt)!=null?lr:Ne((Wr=P.startedAt)!=null?Wr:P.timestamp),re.completedAt=void 0,re.durationMs=void 0,G.toolCall=re,G.streaming=!0;let K=P.agentContext;(K||P.executionId)&&(G.agentMetadata={executionId:(qr=K==null?void 0:K.executionId)!=null?qr:P.executionId,iteration:(Eo=K==null?void 0:K.iteration)!=null?Eo:P.iteration}),p(G)}else if(he==="tool_chunk"||he==="tool_delta"){let U=(Gr=(vt=j(P,!1))!=null?vt:j(P,!0))!=null?Gr:`tool-${d()}`;if(le.has(U))continue;let H=de(U),G=(ko=H.toolCall)!=null?ko:{id:U,status:"running"};G.startedAt=(xo=G.startedAt)!=null?xo:Ne(($o=P.startedAt)!=null?$o:P.timestamp);let re=(Lo=(Nn=(yt=P.text)!=null?yt:P.delta)!=null?Nn:P.message)!=null?Lo:"";re&&(G.chunks=(On=G.chunks)!=null?On:[],G.chunks.push(String(re))),G.status="running",H.toolCall=G,H.streaming=!0;let K=P.agentContext;(K||P.executionId)&&(H.agentMetadata=(cn=H.agentMetadata)!=null?cn:{executionId:(Vr=K==null?void 0:K.executionId)!=null?Vr:P.executionId,iteration:(ga=K==null?void 0:K.iteration)!=null?ga:P.iteration}),p(H)}else if(he==="tool_complete"){let U=(pn=(zo=j(P,!1))!=null?zo:j(P,!0))!=null?pn:`tool-${d()}`;if(le.has(U)){le.delete(U);continue}let H=de(U),G=(un=H.toolCall)!=null?un:{id:U,status:"running"};G.status="complete",P.result!==void 0&&(G.result=P.result),typeof P.duration=="number"&&(G.duration=P.duration),G.completedAt=Ne((_n=P.completedAt)!=null?_n:P.timestamp);let re=(Un=P.duration)!=null?Un:P.executionTime;if(typeof re=="number")G.durationMs=re;else{let Oe=(fn=G.startedAt)!=null?fn:Date.now();G.durationMs=Math.max(0,((At=G.completedAt)!=null?At:Date.now())-Oe)}H.toolCall=G,H.streaming=!1;let K=P.agentContext;(K||P.executionId)&&(H.agentMetadata=(Hr=H.agentMetadata)!=null?Hr:{executionId:(Kr=K==null?void 0:K.executionId)!=null?Kr:P.executionId,iteration:(Xr=K==null?void 0:K.iteration)!=null?Xr:P.iteration}),p(H);let Pe=Y(P);Pe&&M.byCall.delete(Pe)}else if(he==="step_await"&&P.awaitReason==="local_tool_required"&&P.toolName){let U=typeof P.toolCallId=="string"&&P.toolCallId.length>0?P.toolCallId:void 0,H=(Et=U!=null?U:P.toolId)!=null?Et:`local-${d()}`,G=de(H),re=P.toolName,K=ea(re),Pe=(lo=G.toolCall)!=null?lo:{id:H,status:"pending"};Pe.name=re,Pe.args=P.parameters,Pe.status=K?"running":"complete",Pe.chunks=(co=Pe.chunks)!=null?co:[],Pe.startedAt=(mn=Pe.startedAt)!=null?mn:Ne((Qr=P.startedAt)!=null?Qr:P.timestamp),K?(Pe.completedAt=void 0,Pe.duration=void 0,Pe.durationMs=void 0):Pe.completedAt=(jo=Pe.completedAt)!=null?jo:Pe.startedAt,G.toolCall=Pe,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Jr=P.executionId)!=null?Jr:(gn=G.agentMetadata)==null?void 0:gn.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},p(G)}else if(he==="text_start"){if((Ut=P.toolContext)!=null&&Ut.toolId)continue;let U=P.partId;if(U!==void 0&&T.current!==null&&U!==T.current){let H=m;H&&(H.streaming=!1,p(H),xt=H,m=null,E=!0)}U!==void 0&&(T.current=U)}else if(he==="text_end"){if((Br=P.toolContext)!=null&&Br.toolId)continue;let U=m;U&&(U.streaming=!1,p(U),xt=U,m=null,E=!0)}else if(he==="step_chunk"||he==="step_delta"){let U=P.stepType,H=P.executionType;if(U==="tool"||H==="context")continue;let G=P.toolContext;if(G!=null&&G.toolId){let Oe=String((hn=(po=P.id)!=null?po:G.stepId)!=null?hn:`step-${d()}`),at=P.partId!==void 0&&P.partId!==null?String(P.partId):"",Ye=`${G.toolId}::${Oe}`,It=S.get(Ye);if(at!==""&&It!==void 0&&It!==""&&It!==at){let Rt=y.get(W(G.toolId,Oe,It));Rt&&Rt.streaming!==!1&&(Rt.streaming=!1,p(Rt))}at!==""&&S.set(Ye,at);let qt=L(G.toolId,Oe,at,G.executionId),Cr=(Yr=(Po=(xn=(Go=P.text)!=null?Go:P.delta)!=null?xn:P.content)!=null?Po:P.chunk)!=null?Yr:"";Cr&&(qt.content+=String(Cr),qt.streaming=!0,p(qt)),P.isComplete&&(qt.streaming=!1,p(qt));continue}let re=P.partId;if(re!==void 0&&T.current!==null&&re!==T.current){let Oe=m;Oe&&(Oe.streaming=!1,p(Oe),xt=Oe,m=null,E=!0)}re!==void 0&&(T.current=re);let K=re!==void 0&&(xe=Pt.get(re))!=null?xe:Ce();re!==void 0&&(K.partId||(K.partId=re),Pt.set(re,K));let Pe=(Io=(fr=(or=(pt=P.text)!=null?pt:P.delta)!=null?or:P.content)!=null?fr:P.chunk)!=null?Io:"";if(Pe){let Oe=typeof P.seq=="number"?P.seq:void 0,at=re!=null?re:K.id,Ye=Oe!==void 0?Ue(at,Oe,String(Pe)):((Za=ae.get(K.id))!=null?Za:"")+Pe;K.rawContent=Ye,Z.has(K.id)||Z.set(K.id,this.createStreamParser());let It=Z.get(K.id),qt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(qt&&ae.set(K.id,Ye),It.__isPlainTextParser===!0){K.content=Oe!==void 0?Ye:K.content+Pe,ae.delete(K.id),Z.delete(K.id),K.rawContent=void 0,p(K);continue}let Rt=It.processChunk(Ye);if(Rt instanceof Promise)Rt.then(Bt=>{var kr;let mr=typeof Bt=="string"?Bt:(kr=Bt==null?void 0:Bt.text)!=null?kr:null;if(mr!==null&&mr.trim()!=="")K.content=mr,p(K);else if(!qt&&!Ye.trim().startsWith("<")){let Ar=m,Dt=Ar&&Ar.id===K.id?Ar:K;Dt.id===K.id&&(Dt.content=Oe!==void 0?Ye:Dt.content+Pe,ae.delete(Dt.id),Z.delete(Dt.id),Dt.rawContent=void 0,p(Dt))}}).catch(()=>{K.content=Oe!==void 0?Ye:K.content+Pe,ae.delete(K.id),Z.delete(K.id),K.rawContent=void 0,p(K)});else{let Bt=typeof Rt=="string"?Rt:(Ko=Rt==null?void 0:Rt.text)!=null?Ko:null;Bt!==null&&Bt.trim()!==""?(K.content=Bt,p(K)):!qt&&!Ye.trim().startsWith("<")&&(K.content=Oe!==void 0?Ye:K.content+Pe,ae.delete(K.id),Z.delete(K.id),K.rawContent=void 0,p(K))}}if(P.isComplete){let Oe=(Ro=(qn=P.result)==null?void 0:qn.response)!=null?Ro:K.content;if(Oe){let at=ae.get(K.id),Ye=at!=null?at:te(Oe);K.rawContent=Ye;let It=Z.get(K.id),qt=null,Cr=!1;if(It&&(qt=It.getExtractedText(),qt===null&&(qt=ra(Ye)),qt===null)){let Rt=It.processChunk(Ye);Rt instanceof Promise?(Cr=!0,Rt.then(Bt=>{var kr;let mr=typeof Bt=="string"?Bt:(kr=Bt==null?void 0:Bt.text)!=null?kr:null;if(mr!==null){let Ar=m;Ar&&Ar.id===K.id&&(Ar.content=mr,Ar.streaming=!1,Z.delete(Ar.id),ae.delete(Ar.id),p(Ar))}})):qt=typeof Rt=="string"?Rt:(_=Rt==null?void 0:Rt.text)!=null?_:null}if(!Cr){qt!==null&&qt.trim()!==""?K.content=qt:ae.has(K.id)||(K.content=te(Oe));let Rt=Z.get(K.id);if(Rt){let Bt=(ha=Rt.close)==null?void 0:ha.call(Rt);Bt instanceof Promise&&Bt.catch(()=>{}),Z.delete(K.id)}ae.delete(K.id),K.streaming=!1,p(K)}}}}else if(he==="step_complete"){let U=P.stepType,H=P.executionType;if(U==="tool"||H==="context")continue;let G=P.toolContext;if(G!=null&&G.toolId){let Oe=String((Ho=(Wo=P.id)!=null?Wo:G.stepId)!=null?Ho:"");if(Oe){let at=R(G.toolId,Oe);for(let[Ye,It]of y)Ye.startsWith(at)&&It.streaming!==!1&&(It.streaming=!1,p(It));S.delete(`${G.toolId}::${Oe}`)}continue}let re=P.stopReason;if(E){if(m!==null){let Ye=m;re&&(Ye.stopReason=re),Z.delete(Ye.id),ae.delete(Ye.id),Ye.streaming!==!1&&(Ye.streaming=!1,p(Ye))}let Oe=(Xo=P.result)==null?void 0:Xo.response,at=xt;at&&(re&&(at.stopReason=re),Oe!=null?be(at,Oe):(Z.delete(at.id),ae.delete(at.id))),xt=null;continue}let K=(Bo=P.result)==null?void 0:Bo.response,Pe=Ce();if(re&&(Pe.stopReason=re),K!=null){let Oe=Z.get(Pe.id),at=!1,Ye=!1;if(Oe){let It=Oe.getExtractedText(),qt=ae.get(Pe.id),Cr=qt!=null?qt:te(K);if(Pe.rawContent=Cr,It!==null&&It.trim()!=="")Pe.content=It,at=!0;else{let Rt=ra(Cr);if(Rt!==null)Pe.content=Rt,at=!0;else{let Bt=Oe.processChunk(Cr);if(Bt instanceof Promise)Ye=!0,Bt.then(mr=>{var Ar;let kr=typeof mr=="string"?mr:(Ar=mr==null?void 0:mr.text)!=null?Ar:null;if(kr!==null&&kr.trim()!==""){let Dt=m;Dt&&Dt.id===Pe.id&&(Dt.content=kr,Dt.streaming=!1,Z.delete(Dt.id),ae.delete(Dt.id),p(Dt))}else{let Dt=Oe.getExtractedText(),dr=m;dr&&dr.id===Pe.id&&(Dt!==null&&Dt.trim()!==""?dr.content=Dt:ae.has(dr.id)||(dr.content=te(K)),dr.streaming=!1,Z.delete(dr.id),ae.delete(dr.id),p(dr))}});else{let mr=typeof Bt=="string"?Bt:(yo=Bt==null?void 0:Bt.text)!=null?yo:null;if(mr!==null&&mr.trim()!=="")Pe.content=mr,at=!0;else{let kr=Oe.getExtractedText();kr!==null&&kr.trim()!==""&&(Pe.content=kr,at=!0)}}}}}if(!Ye){if(!Pe.rawContent){let It=ae.get(Pe.id);Pe.rawContent=It!=null?It:te(K)}if(!at&&!ae.has(Pe.id)&&(Pe.content=te(K)),Oe){let It=(xa=Oe.close)==null?void 0:xa.call(Oe);It instanceof Promise&&It.catch(()=>{})}Z.delete(Pe.id),ae.delete(Pe.id),Pe.streaming=!1,p(Pe)}}else Z.delete(Pe.id),ae.delete(Pe.id),Pe.streaming=!1,p(Pe)}else if(he==="flow_complete"){let U=(Xs=P.result)==null?void 0:Xs.response;if(E){if(m!==null){let H=m;Z.delete(H.id),ae.delete(H.id),H.streaming!==!1&&(H.streaming=!1,p(H))}}else if(U!=null){let H=Ce(),G=ae.get(H.id),re=G!=null?G:te(U);H.rawContent=re;let K=te(U),Pe=Z.get(H.id);if(Pe){let Ye=ra(re);if(Ye!==null)K=Ye;else{let It=Pe.processChunk(re);It instanceof Promise&&It.then(Cr=>{var Bt;let Rt=typeof Cr=="string"?Cr:(Bt=Cr==null?void 0:Cr.text)!=null?Bt:null;Rt!==null&&(H.content=Rt,H.streaming=!1,p(H))});let qt=Pe.getExtractedText();qt!==null&&(K=qt)}}Z.delete(H.id),ae.delete(H.id);let Oe=K!==H.content,at=H.streaming!==!1;Oe&&(H.content=K),H.streaming=!1,(Oe||at)&&p(H)}else if(m!==null){let H=m;Z.delete(H.id),ae.delete(H.id),H.streaming!==!1&&(H.streaming=!1,p(H))}r({type:"status",status:"idle"})}else if(he==="agent_start")rt={executionId:P.executionId,agentId:(Zr=P.agentId)!=null?Zr:"virtual",agentName:(eo=P.agentName)!=null?eo:"",status:"running",currentIteration:0,maxTurns:(bo=P.maxTurns)!=null?bo:1,startedAt:Ne(P.startedAt)};else if(he==="agent_iteration_start"){if(rt&&(rt.currentIteration=P.iteration),vr==="separate"&&P.iteration>1){let U=m;U&&(U.streaming=!1,p(U),Ft.set(P.iteration-1,U),m=null)}}else if(he==="agent_turn_start")x=null;else if(he==="agent_turn_delta"){if(P.contentType==="text"){let U=Ce();U.content+=(vo=P.delta)!=null?vo:"",U.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId,agentName:rt==null?void 0:rt.agentName},x=U,p(U)}else if(P.contentType==="thinking"){let U=(Vn=P.turnId)!=null?Vn:`agent-think-${P.iteration}`,H=Ee(U);H.reasoning=(Qo=H.reasoning)!=null?Qo:{id:U,status:"streaming",chunks:[]},H.reasoning.chunks.push((Er=P.delta)!=null?Er:""),H.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId},p(H)}else if(P.contentType==="tool_input"){let U=(Do=P.toolCallId)!=null?Do:M.lastId;if(U){let H=k.get(U);H!=null&&H.toolCall&&(H.toolCall.chunks=(ya=H.toolCall.chunks)!=null?ya:[],H.toolCall.chunks.push(($n=P.delta)!=null?$n:""),p(H))}}}else if(he==="agent_turn_complete"){let U=P.turnId;if(U){let re=w.get(U);if(re!=null&&re.reasoning){re.reasoning.status="complete",re.reasoning.completedAt=Ne(P.completedAt);let K=(ba=re.reasoning.startedAt)!=null?ba:Date.now();re.reasoning.durationMs=Math.max(0,((Qs=re.reasoning.completedAt)!=null?Qs:Date.now())-K),re.streaming=!1,p(re)}}let H=P.stopReason,G=m!=null?m:x;if(H&&G!==null){let re=P.turnId;(!re||((va=G.agentMetadata)==null?void 0:va.turnId)===re)&&(G.stopReason=H,p(G))}}else if(he==="agent_tool_start"){m&&(m.streaming=!1,p(m),m=null);let U=(Js=P.toolCallId)!=null?Js:`agent-tool-${d()}`;De(Y(P),U);let H=de(U),G=(Ca=H.toolCall)!=null?Ca:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};G.name=(es=(ht=P.toolName)!=null?ht:P.name)!=null?es:G.name,G.status="running",P.parameters!==void 0&&(G.args=P.parameters),G.startedAt=Ne((uo=P.startedAt)!=null?uo:P.timestamp),H.toolCall=G,H.streaming=!0,H.agentMetadata={executionId:P.executionId,iteration:P.iteration},p(H)}else if(he==="agent_tool_delta"){let U=($r=P.toolCallId)!=null?$r:M.lastId;if(U){let H=(Ys=k.get(U))!=null?Ys:de(U);H.toolCall&&(H.toolCall.chunks=(Zs=H.toolCall.chunks)!=null?Zs:[],H.toolCall.chunks.push((wa=P.delta)!=null?wa:""),H.toolCall.status="running",H.streaming=!0,p(H))}}else if(he==="agent_tool_complete"){let U=(Jo=P.toolCallId)!=null?Jo:M.lastId;if(U){let H=(ts=k.get(U))!=null?ts:de(U);if(H.toolCall){H.toolCall.status="complete",P.result!==void 0&&(H.toolCall.result=P.result),typeof P.executionTime=="number"&&(H.toolCall.durationMs=P.executionTime),H.toolCall.completedAt=Ne((yn=P.completedAt)!=null?yn:P.timestamp),H.streaming=!1,p(H);let G=Y(P);G&&M.byCall.delete(G)}}}else if(he==="agent_media"){let U=Array.isArray(P.media)?P.media:[],H=[];for(let G of U){if(!G||typeof G!="object")continue;let re=G,K=typeof re.type=="string"?re.type:void 0,Pe=typeof re.mediaType=="string"?re.mediaType.toLowerCase():"",Oe=null,at="";if(K==="media"){let Ye=typeof re.data=="string"?re.data:void 0;if(!Ye)continue;at=Pe.length>0?Pe:"application/octet-stream",Oe=`data:${at};base64,${Ye}`}else if(K==="image-url"){let Ye=typeof re.url=="string"?re.url:void 0;if(!Ye)continue;at=Pe,Oe=Ye}else if(K==="file-url"){let Ye=typeof re.url=="string"?re.url:void 0;if(!Ye)continue;at=Pe,Oe=Ye}else continue;if(Oe)if(K==="image-url"||at.startsWith("image/"))H.push({type:"image",image:Oe,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))H.push({type:"audio",audio:Oe,mimeType:at});else if(at.startsWith("video/"))H.push({type:"video",video:Oe,mimeType:at});else{let Ye=at||"application/octet-stream";H.push({type:"file",data:Oe,mimeType:Ye,filename:Gy(Ye)})}}if(H.length>0){let G=d(),re=P.toolCallId,Pe={id:`agent-media-${typeof re=="string"&&re.length>0?`${re}-${G}`:String(G)}`,role:"assistant",content:"",contentParts:H,createdAt:new Date().toISOString(),streaming:!1,sequence:G,agentMetadata:{executionId:P.executionId,iteration:P.iteration}};p(Pe);let Oe=m;Oe&&(Oe.streaming=!1,p(Oe)),m=null,C.current=null}}else if(he!=="agent_iteration_complete"){if(he==="agent_reflection"||he==="agent_reflect"){let U=`agent-reflection-${P.executionId}-${P.iteration}`,H={id:U,role:"assistant",content:(rs=P.reflection)!=null?rs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:d(),reasoning:{id:U,status:"complete",chunks:[(os=P.reflection)!=null?os:""]},agentMetadata:{executionId:P.executionId,iteration:P.iteration}};p(H)}else if(he==="agent_complete"){rt&&(rt.status=P.success?"complete":"error",rt.completedAt=Ne(P.completedAt),rt.stopReason=P.stopReason);let U=m;U&&(U.streaming=!1,p(U)),r({type:"status",status:"idle"})}else if(he==="agent_error"){let U=typeof P.error=="string"?P.error:(as=(ns=P.error)==null?void 0:ns.message)!=null?as:"Agent execution error";P.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):r({type:"error",error:new Error(U)})}else if(he!=="agent_ping"){if(he==="agent_approval_start"){let U=(zr=P.approvalId)!=null?zr:`approval-${d()}`,H={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:"pending",agentId:(Sa=rt==null?void 0:rt.agentId)!=null?Sa:"virtual",executionId:(No=(Fo=P.executionId)!=null?Fo:rt==null?void 0:rt.executionId)!=null?No:"",toolName:(ss=P.toolName)!=null?ss:"",toolType:P.toolType,description:(is=P.description)!=null?is:`Execute ${(ei=P.toolName)!=null?ei:"tool"}`,...typeof P.reason=="string"&&P.reason?{reason:P.reason}:{},parameters:P.parameters}};p(H)}else if(he==="step_await"&&P.awaitReason==="approval_required"){let U=(ls=P.approvalId)!=null?ls:`approval-${d()}`,H={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:"pending",agentId:(zn=rt==null?void 0:rt.agentId)!=null?zn:"virtual",executionId:(ri=(ti=P.executionId)!=null?ti:rt==null?void 0:rt.executionId)!=null?ri:"",toolName:(oi=P.toolName)!=null?oi:"",toolType:P.toolType,description:(ai=P.description)!=null?ai:`Execute ${(ni=P.toolName)!=null?ni:"tool"}`,...typeof P.reason=="string"&&P.reason?{reason:P.reason}:{},parameters:P.parameters}};p(H)}else if(he==="agent_approval_complete"){let U=P.approvalId;if(U){let G={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:(bn=P.decision)!=null?bn:"approved",agentId:(vn=rt==null?void 0:rt.agentId)!=null?vn:"virtual",executionId:(ds=(si=P.executionId)!=null?si:rt==null?void 0:rt.executionId)!=null?ds:"",toolName:(Cn=P.toolName)!=null?Cn:"",description:(ii=P.description)!=null?ii:"",resolvedAt:Date.now()}};p(G)}}else if(he==="artifact_start"||he==="artifact_delta"||he==="artifact_update"||he==="artifact_complete"){if(he==="artifact_start"){let U=P.artifactType,H=String(P.id),G=typeof P.title=="string"?P.title:void 0;if(r({type:"artifact_start",id:H,artifactType:U,title:G,component:typeof P.component=="string"?P.component:void 0}),ge.set(H,{markdown:"",title:G}),!ie.has(H)){ie.add(H);let re={id:`artifact-ref-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:H,title:G,artifactType:U,status:"streaming"}})};Q.set(H,re),p(re)}}else if(he==="artifact_delta"){let U=String(P.id),H=typeof P.delta=="string"?P.delta:String((cs=P.delta)!=null?cs:"");r({type:"artifact_delta",id:U,artDelta:H});let G=ge.get(U);G&&(G.markdown+=H)}else if(he==="artifact_update"){let U=P.props&&typeof P.props=="object"&&!Array.isArray(P.props)?P.props:{};r({type:"artifact_update",id:String(P.id),props:U,component:typeof P.component=="string"?P.component:void 0})}else if(he==="artifact_complete"){let U=String(P.id);r({type:"artifact_complete",id:U});let H=Q.get(U);if(H){H.streaming=!1;try{let G=JSON.parse((wn=H.rawContent)!=null?wn:"{}");if(G.props){G.props.status="complete";let re=ge.get(U);re!=null&&re.markdown&&(G.props.markdown=re.markdown)}H.rawContent=JSON.stringify(G)}catch{}ge.delete(U),p(H),Q.delete(U)}}}else if(he==="transcript_insert"){let U=P.message;if(!U||typeof U!="object")continue;let H=String((ps=U.id)!=null?ps:`msg-${d()}`),G=U.role,K={id:H,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:d()};if(p(K),K.rawContent)try{let Pe=JSON.parse(K.rawContent),Oe=(li=Pe==null?void 0:Pe.props)==null?void 0:li.artifactId;typeof Oe=="string"&&ie.add(Oe)}catch{}m=null,C.current=null,Z.delete(H),ae.delete(H)}else if(he==="error"||he==="step_error"||he==="dispatch_error"||he==="flow_error"){let U=null;if(P.error instanceof Error)U=P.error;else if(he==="dispatch_error"){let H=(Yo=P.message)!=null?Yo:P.error;H!=null&&H!==""&&(U=new Error(String(H)))}else if(he==="step_error"||he==="flow_error"){let H=P.error;typeof H=="string"&&H!==""?U=new Error(H):H!=null&&typeof H=="object"&&"message"in H&&(U=new Error(String((di=H.message)!=null?di:H)))}else he==="error"&&P.error!=null&&P.error!==""&&(U=new Error(String(P.error)));if(U){r({type:"error",error:U});let H=m;H&&H.streaming&&(H.streaming=!1,p(H)),r({type:"status",status:"idle"})}}}}}Je.length=0};;){let{done:V,value:Me}=await n.read();if(V)break;s+=a.decode(Me,{stream:!0});let we=s.split(`
11
11
 
12
- `);s=(Wt=he.pop())!=null?Wt:"";for(let Xe of he){let et=Xe.split(`
13
- `),qe="message",Ne="";for(let Jt of et)Jt.startsWith("event:")?qe=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(Ne+=Jt.replace("data:","").trim());if(!Ne)continue;let Pt;try{Pt=JSON.parse(Ne)}catch(Jt){r({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let Gt=qe!=="message"?qe:(ur=Pt.type)!=null?ur:"message";if((Eo=this.onSSEEvent)==null||Eo.call(this,Gt,Pt),this.parseSSEEvent){C.current=m;let Jt=await this.handleCustomSSEEvent(Pt,r,C,p,d,T);if(C.current&&C.current!==m&&(m=C.current),Jt)continue}Je.push(Gt,Pt),pe()}}Je.flushPending(),pe(),Je.destroy()}};function Ug(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Oa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function aa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Bi="[Image]";function qg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Vg(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 zg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ks(e){return{type:"text",text:e}}function jg(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 Gg(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 Kg(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 Xg=["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"],an=[...Xg,...Gy];function Ky(e){return Xg.includes(e)||e.startsWith("image/")}function Di(e){return Ky(e.type)}async function Qg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;Di(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 Jg(e,t=an,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 Yg(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 Fi=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 Zg=16e3,Qy=24e3,Jy=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 Ls=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 d=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Zg,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:Zg});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let p=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new Fi(Qy);if(n!==this.callGeneration){p.destroy(),d.getTracks().forEach(C=>C.stop()),g.close().catch(()=>{});return}this.playback=p,p.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 T=C.code?` (code ${C.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),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(Jy,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),d=new Int16Array(c.length);for(let u=0;u<c.length;u++){let g=Math.max(-1,Math.min(1,c[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 sa=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 Rn(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ls(e.runtype);case"browser":if(!sa.isSupported())throw new Error("Browser speech recognition not supported");return new sa(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 Ni(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Rn({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Rn({type:"runtype",runtype:e.runtype});if(sa.isSupported())return Rn({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ps(e){try{return Ni(e),!0}catch{return!1}}function _a(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 In=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):_a(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 c=i.error;c==="canceled"||c==="interrupted"?(d=r.onEnd)==null||d.call(r):(u=r.onError)==null||u.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 ia=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 ad(e){if(!e)return"";let t=tb(e);return eh(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 eh(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,`
12
+ `);s=(Tr=we.pop())!=null?Tr:"";for(let He of we){let nt=He.split(`
13
+ `),lt="message",ot="";for(let St of nt)St.startsWith("event:")?lt=St.replace("event:","").trim():St.startsWith("data:")&&(ot+=St.replace("data:","").trim());if(!ot)continue;let Tt;try{Tt=JSON.parse(ot)}catch(St){r({type:"error",error:St instanceof Error?St:new Error("Failed to parse chat stream payload")});continue}let z=lt!=="message"?lt:(je=Tt.type)!=null?je:"message";if((Nt=this.onSSEEvent)==null||Nt.call(this,z,Tt),this.parseSSEEvent){C.current=m;let St=await this.handleCustomSSEEvent(Tt,r,C,p,d,T);if(C.current&&C.current!==m&&(m=C.current),St)continue}if(Ve||(Ug(z)?(ke=!0,Ve=!0):(z==="agent_start"||z==="flow_start"||z==="step_start")&&(ke=!1,Ve=!0)),ke){for(let St of Kt.push(z,Tt))Je.push(St);ce();continue}Xe.push(z,Tt),ce()}}Xe.flushPending(),ce(),Xe.destroy()}};function $g(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Na(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function aa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Fi="[Image]";function zg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function jg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Gg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Kg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Es(e){return{type:"text",text:e}}function Xg(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 Qg(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 Jg(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 Yg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Qy=["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"],an=[...Yg,...Qy];function Jy(e){return Yg.includes(e)||e.startsWith("image/")}function Ni(e){return Jy(e.type)}async function Zg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;Ni(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 eh(e,t=an,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 Yy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function th(e,t){let r=Yy(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 Oi=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 rh=16e3,Zy=24e3,eb=4096,tb=1380533830;function rb(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===tb?new Uint8Array(e,44):new Uint8Array(e)}function ob(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 ks=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 d=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:rh,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:rh});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let p=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new Oi(Zy);if(n!==this.callGeneration){p.destroy(),d.getTracks().forEach(C=>C.stop()),g.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${ob(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 T=C.code?` (code ${C.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),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(eb,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),d=new Int16Array(c.length);for(let u=0;u<c.length;u++){let g=Math.max(-1,Math.min(1,c[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=rb(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 sa=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 In(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ks(e.runtype);case"browser":if(!sa.isSupported())throw new Error("Browser speech recognition not supported");return new sa(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 _i(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return In({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return In({type:"runtype",runtype:e.runtype});if(sa.isSupported())return In({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ls(e){try{return _i(e),!0}catch{return!1}}function Oa(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 Rn=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):Oa(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 c=i.error;c==="canceled"||c==="interrupted"?(d=r.onEnd)==null||d.call(r):(u=r.onError)==null||u.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 ia=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 id(e){if(!e)return"";let t=nb(e);return oh(t!==null?t:e)}function nb(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 oh(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
14
  `),t=t.replace(/\n{2,}/g,`
15
- `),t.trim()}var sd=null,th=e=>{sd=e},id=()=>sd?sd():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 rh(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}
15
+ `),t.trim()}var ld=null,nh=e=>{ld=e},dd=()=>ld?ld():import("./runtype-tts-entry");var ab=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function sb(e,t){return ab.some(r=>e[r]!==t[r])}function ah(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
16
 
17
- _Details: ${r.message}_`:o}var Rs=e=>({isError:!0,content:[{type:"text",text:e}]}),oh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,nh=e=>ea(e)||e===Mo,Ua=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 ia(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,d,u,g;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall,m=!!(p!=null&&p.name)&&(ea(p.name)||p.name===Mo&&((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 p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((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 na(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||id().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 Ps((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=In.isSupported()?new In({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,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(c&&d&&u)return id().then(({RuntypeSpeechEngine:p,FallbackSpeechEngine:m})=>{let x=new p({host:c,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=Rn(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,d)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:c,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:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:c,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 c,d;(d=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||d.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,d;this.voiceStatus=i,this.voiceActive=i==="listening",(d=(c=this.callbacks).onVoiceStatusChanged)==null||d.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,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:(c=t.runtype)==null?void 0:c.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 na(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:d=!1,voiceProcessing:u,rawContent:g}=t,m={id:s!=null?s:r==="user"?Oa():r==="assistant"?aa():`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: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:c,createdAt:d,sequence:u,streaming:g=!1,voiceProcessing:p,rawContent:m}=o,C={id:c!=null?c:n==="user"?Oa():n==="assistant"?aa():`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},...p!==void 0&&{voiceProcessing:p},...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:c}=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},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var d,u,g,p,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=Oa(),a=aa(),s={id:n,role:"user",content:o||Bi,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 C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let T=rh(x,this.config.errorMessage);if(T){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,x):(m=(p=this.callbacks).onError)==null||m.call(p,new Error(String(x))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort();let t=aa();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=rh(d,this.config.errorMessage);if(g){let p={id:t,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(p)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,d):(c=(i=this.callbacks).onError)==null||c.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,p,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 c=this.config.approval,d=c&&typeof c=="object"?c.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 T=null;if(C instanceof Response){if(!C.ok){let E=await C.json().catch(()=>null);throw new Error((p=E==null?void 0:E.error)!=null?p:`Approval request failed: ${C.status}`)}T=C.body}else C instanceof ReadableStream&&(T=C);T?await this.connectStream(T,{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 T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(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,p,m,x,C,T,E,M,P,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=(p=t.toolCall)==null?void 0:p.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,A=Array.isArray(b==null?void 0:b.questions)?b.questions:[];if(A.length===1){let H=typeof((T=A[0])==null?void 0:T.question)=="string"?A[0].question:"";H&&(s={[H]:r})}}this.markAskUserQuestionResolved(t,s),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(M=t.toolCall)==null?void 0:M.args,d=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(d.length===0){let b=typeof r=="string"?r:Object.entries(r).map(([A,H])=>`${A}: ${Array.isArray(H)?H.join(", "):H}`).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((A,H)=>{let W=typeof(A==null?void 0:A.question)=="string"?A.question:"";if(!W)return;let k=b[W],N=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${H}`,role:"assistant",content:W,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${H}`,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 A=await b.json().catch(()=>null);throw new Error((P=A==null?void 0:A.error)!=null?P:`Resume failed: ${b.status}`)}b.body?await this.connectStream(b.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(b){let A=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,A||(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)!==Mo)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,d,u,g;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async p=>{var w,b,A,H,W,k,N;let m=(w=p.toolCall)==null?void 0:w.name,x=(b=p.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(p))return null;this.webMcpInflightKeys.add(C),o.push(C);let T=this.markWebMcpToolRunning(p),E=(H=(A=p.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?H:m;if(m===Mo)return{dedupeKey:C,resumeKey:E,output:Zl(),toolMessage:p,startedAt:T,completedAt:Date.now()};let M=new AbortController;this.webMcpResolveControllers.add(M),n.push(M);let P=this.client.executeWebMcpToolCall(m,(W=p.toolCall)==null?void 0:W.args,M.signal),y;if(!P)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await P}catch(q){let Z=q instanceof Error&&(q.name==="AbortError"||q.message.includes("aborted")||q.message.includes("abort"));return Z||(N=(k=this.callbacks).onError)==null||N.call(k,q instanceof Error?q:new Error(String(q))),this.markWebMcpToolComplete(p,Rs(Z?"Aborted by cancel()":oh(q)),T),this.webMcpInflightKeys.delete(C),null}return M.signal.aborted?(this.markWebMcpToolComplete(p,Rs("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:E,output:y,toolMessage:p,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=s.filter(x=>x!==null),i.length===0)return;let p={};for(let x of i)p[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,p,{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,((d=x.toolMessage.toolCall)==null?void 0:d.name)===Mo?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,p instanceof Error?p:new Error(String(p)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,Rs("Aborted by cancel()"),x.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of n)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,C,T,E,M,P,y,w,b,A,H,W;let r=(x=t.agentMetadata)==null?void 0:x.executionId,o=(C=t.toolCall)==null?void 0:C.name,n=(T=t.toolCall)==null?void 0:T.id;if(!r){(M=(E=this.callbacks).onError)==null||M.call(E,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=(P=this.callbacks).onError)==null||y.call(P,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:c}=i;this.setStreaming(!0);let d=o===Mo,u=(w=t.toolCall)==null?void 0:w.args,g=d?null:this.client.executeWebMcpToolCall(o,u,c),p="execute",m=s;try{let k;if(d?k=Zl():g?k=await g:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),c.aborted){this.markWebMcpToolComplete(t,Rs("Aborted by cancel()"),s);return}let N=(A=(b=t.agentMetadata)==null?void 0:b.webMcpToolCallId)!=null?A:o;p="resume",await this.resumeWithToolOutput(r,N,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,k,s,m,d?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(k){let N=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(p==="execute"||N||c.aborted)&&this.markWebMcpToolComplete(t,Rs(N||c.aborted?"Aborted by cancel()":oh(k)),s),N||(W=(H=this.callbacks).onError)==null||W.call(H,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 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=ad(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return _a(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=ad(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,p,m,x,C,T,E,M,P,y,w,b,A,H;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={...(p=s.agentMetadata)!=null?p:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let W=n.approval,k=r.approval;s.approval={...W,...k,executionId:k.executionId||W.executionId,toolName:k.toolName||W.toolName,description:k.description||W.description,toolType:(m=k.toolType)!=null?m:W.toolType,reason:(x=k.reason)!=null?x:W.reason,parameters:(C=k.parameters)!=null?C:W.parameters}}let i=(T=r.toolCall)==null?void 0:T.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,d=(M=r.toolCall)==null?void 0:M.id;if(i&&nh(i)&&c&&d&&((P=r.agentMetadata)==null?void 0:P.awaitingLocalTool)===!0){let W=`${c}:${d}`,k=this.webMcpInflightKeys.has(W),N=this.webMcpResolvedKeys.has(W),q=(y=n.toolCall)==null?void 0:y.name,Z=((w=n.agentMetadata)==null?void 0:w.executionId)===c&&((b=n.toolCall)==null?void 0:b.id)===d&&q!==void 0&&nh(q)&&((A=n.toolCall)==null?void 0:A.status)==="complete";(k||N||Z)&&(s.agentMetadata={...(H=s.agentMetadata)!=null?H:{},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,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=(c=r.sequence)!=null?c:0,i=(d=o.sequence)!=null?d:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var ld=[["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 dd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var cd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var pd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var ud=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var fd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var md=[["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 gd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var hd=[["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 xd=[["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 yd=[["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 bd=[["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 vd=[["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 Cd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var wd=[["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 Sd=[["path",{d:"M20 6 9 17l-5-5"}]];var Ad=[["path",{d:"m6 9 6 6 6-6"}]];var Md=[["path",{d:"m15 18-6-6 6-6"}]];var Td=[["path",{d:"m9 18 6-6-6-6"}]];var Ed=[["path",{d:"m18 15-6-6-6 6"}]];var Oi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var _i=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var kd=[["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 Pd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Rd=[["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 Id=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Wd=[["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 Hd=[["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 Ui=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var qi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Bd=[["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 Dd=[["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 Fd=[["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 Nd=[["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 Od=[["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 _d=[["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 Ud=[["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 qd=[["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 Vd=[["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 $d=[["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 zd=[["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 jd=[["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 Gd=[["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 Kd=[["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 Xd=[["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 Qd=[["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 Jd=[["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 Yd=[["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 $i=[["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 Zd=[["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 ec=[["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 tc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var rc=[["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 oc=[["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 zi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var nc=[["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 ac=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var sc=[["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 ic=[["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 lc=[["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 dc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var cc=[["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 pc=[["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 uc=[["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 fc=[["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 mc=[["path",{d:"M5 12h14"}]];var gc=[["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 hc=[["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 xc=[["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 yc=[["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 bc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var vc=[["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 Cc=[["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 wc=[["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 Sc=[["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 Mc=[["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 Tc=[["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 Ec=[["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 kc=[["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 Lc=[["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 Rc=[["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 Ic=[["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 Wc=[["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 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"}],["path",{d:"m9 12 2 2 4-4"}]];var ji=[["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 Bc=[["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 Dc=[["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 Fc=[["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 Nc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Gi=[["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 Oc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var _c=[["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 Uc=[["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 qc=[["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 Vc=[["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 $c=[["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 zc=[["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 jc=[["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 Gc=[["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 Kc=[["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 Ki=[["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 Xc=[["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 Qc=[["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 Jc=[["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 Yc=[["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 Zc=[["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 ep=[["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 tp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var rp=[["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:ld,"arrow-down":dd,"arrow-up":fd,"arrow-up-right":ud,bot:yd,"chevron-down":Ad,"chevron-up":Ed,"chevron-right":Td,"chevron-left":Md,check:Sd,clipboard:Ld,"clipboard-copy":kd,copy:Rd,file:Ud,"file-code":Nd,"file-spreadsheet":Od,"file-text":_d,"image-plus":Zd,loader:nc,"loader-circle":zi,mic:uc,paperclip:yc,"refresh-cw":Tc,search:Lc,send:Pc,"shield-alert":Wc,"shield-check":Hc,"shield-x":ji,square:Oc,"thumbs-down":$c,"thumbs-up":zc,upload:Qc,"volume-2":Yc,x:tp,user:Jc,mail:sc,phone:wc,calendar:Cd,clock:Pd,building:bd,"map-pin":ic,lock:ac,key:rc,"credit-card":Id,"at-sign":md,hash:Xd,globe:Kd,link:oc,"circle-check":Oi,"circle-x":_i,"triangle-alert":Ki,info:tc,ban:gd,shield:Bc,"arrow-left":cd,"arrow-right":pd,"external-link":Dd,ellipsis:qi,"ellipsis-vertical":Ui,menu:dc,house:$i,plus:Ac,minus:mc,pencil:vc,trash:Kc,"trash-2":Gc,save:kc,download:Hd,share:Ic,funnel:Vi,settings:Rc,"rotate-cw":Ec,maximize:lc,minimize:fc,"shopping-cart":Fc,"shopping-bag":Dc,package:xc,truck:Xc,tag:Vc,gift:Gd,receipt:Mc,wallet:ep,store:Uc,"dollar-sign":Wd,percent:Cc,play:Sc,pause:bc,"volume-x":Zc,camera:wd,image:ec,film:Vd,headphones:Qd,"message-circle":cc,"message-square":pc,bell:hd,heart:Jd,star:_c,eye:Fd,"eye-off":Bd,bookmark:xd,"calendar-days":vd,history:Yd,timer:jc,folder:jd,"folder-open":zd,files:qd,sparkles:Gi,zap:rp,sun:qc,moon:hc,flag:$d,monitor:gc,smartphone:Nc},ve=(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 c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([d,u])=>{d!=="stroke"&&c.setAttribute(d,String(u))}),n.appendChild(c)}),n}var Xi={allowedTypes:an,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 la=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Xi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Xi.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Xi.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:Xi.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 d of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,d,"count");continue}let u=Jg(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 Qg(d),p=Di(d)?URL.createObjectURL(d):null,m={id:sb(),file:d,previewUrl:p,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}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=Di(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),c=ve(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let d=S("span");d.textContent=Yg(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=ve("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 ah=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Is(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];ah(a)&&ah(n)?r[o]=Is(a,n):r[o]=n}return r}var oo="min(440px, calc(100vw - 24px))",Qi="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:oo,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)"},_t={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 sh(e,t){if(!(!e&&!t))return e?t?Is(e,t):e:t}function Ji(e){var t,r,o,n,a,s,i,c,d,u,g,p,m,x,C,T,E,M,P,y,w;return e?{..._t,...e,theme:sh(_t.theme,e.theme),darkTheme:sh(_t.darkTheme,e.darkTheme),launcher:{..._t.launcher,...e.launcher,dock:{...(t=_t.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=_t.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{..._t.copy,...e.copy},sendButton:{..._t.sendButton,...e.sendButton},statusIndicator:{..._t.statusIndicator,...e.statusIndicator},voiceRecognition:{..._t.voiceRecognition,...e.voiceRecognition},features:(()=>{var de,J,le,ge,ue,G,ce,Be,ne,ee;let b=(de=_t.features)==null?void 0:de.artifacts,A=(J=e.features)==null?void 0:J.artifacts,H=(le=_t.features)==null?void 0:le.scrollToBottom,W=(ge=e.features)==null?void 0:ge.scrollToBottom,k=(ue=_t.features)==null?void 0:ue.scrollBehavior,N=(G=e.features)==null?void 0:G.scrollBehavior,q=(ce=_t.features)==null?void 0:ce.streamAnimation,Z=(Be=e.features)==null?void 0:Be.streamAnimation,me=(ne=_t.features)==null?void 0:ne.askUserQuestion,Ke=(ee=e.features)==null?void 0:ee.askUserQuestion,Ce=b===void 0&&A===void 0?void 0:{...b,...A,layout:{...b==null?void 0:b.layout,...A==null?void 0:A.layout}},Ie=H===void 0&&W===void 0?void 0:{...H,...W},Ue=k===void 0&&N===void 0?void 0:{...k,...N},Te=q===void 0&&Z===void 0?void 0:{...q,...Z},We=me===void 0&&Ke===void 0?void 0:{...me,...Ke,styles:{...me==null?void 0:me.styles,...Ke==null?void 0:Ke.styles}};return{..._t.features,...e.features,...Ie!==void 0?{scrollToBottom:Ie}:{},...Ue!==void 0?{scrollBehavior:Ue}:{},...Ce!==void 0?{artifacts:Ce}:{},...Te!==void 0?{streamAnimation:Te}:{},...We!==void 0?{askUserQuestion:We}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:_t.suggestionChips,suggestionChipsConfig:{..._t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{..._t.layout,...e.layout,header:{...(s=_t.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=_t.layout)==null?void 0:c.messages,...(d=e.layout)==null?void 0:d.messages,avatar:{...(g=(u=_t.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(p=e.layout)==null?void 0:p.messages)==null?void 0:m.avatar},timestamp:{...(C=(x=_t.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(E=(T=e.layout)==null?void 0:T.messages)==null?void 0:E.timestamp}},slots:{...(M=_t.layout)==null?void 0:M.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{..._t.markdown,...e.markdown,options:{...(y=_t.markdown)==null?void 0:y.options,...(w=e.markdown)==null?void 0:w.options}},messageActions:{..._t.messageActions,...e.messageActions}}:_t}var op={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"}},np={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"}},ap={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:oo,maxWidth:Qi,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 qa(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."))?qa(e,o):o}function Yi(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=qa(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 sp(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 ih(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]=ih(a,n):r[o]=n}return r}function db(e,t){return t?ih(e,t):e}function Va(e,t={}){var n,a,s,i,c,d,u,g,p,m,x,C,T;let r={palette:op,semantic:np,components:ap},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,...(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,...(p=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:p.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,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:db(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=sp(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(M=>M.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Zi(e){var C,T,E,M,P,y,w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de,J,le,ge,ue,G,ce,Be,ne,ee,ie,vt,Lt,gt,_e,be,Ze,Y,pe,Me,Je,Ge,ke,je,Cr,Wt,ur,Eo,V,j,he,Xe,et,qe,Ne,Pt,Gt,Jt,Pr,z,Ht,oe,we,De,At,ar,sr,wr,Ft,ot,Dt,lt,Yt,so,Rr,ir,Ur,ko,yt,jr,Lo,zo,yo,ht,Nn,Po,On,qr,ga,cn,jo,pn,un,_n,Un,fn,Ct,Gr,Kr,Ir,Mt,io,lo,Xr,mn,Go,gn,Qr,Nt,Wr,co,hn,Ko,xn,Ro,Jr;let t=Yi(e),r={};for(let[xe,dt]of Object.entries(t)){let tr=xe.replace(/\./g,"-");r[`--persona-${tr}`]=dt.value}r["--persona-primary"]=(C=r["--persona-semantic-colors-primary"])!=null?C:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(T=r["--persona-semantic-colors-secondary"])!=null?T: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"]=(M=r["--persona-semantic-colors-surface"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(P=r["--persona-semantic-colors-background"])!=null?P: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"]=(A=r["--persona-semantic-colors-text-inverse"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(H=r["--persona-semantic-colors-border"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(W=r["--persona-semantic-colors-divider"])!=null?W: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"]=(q=r["--persona-components-voice-processing-icon"])!=null?q:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Z=r["--persona-components-voice-speaking-icon"])!=null?Z:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Ke=r["--persona-components-approval-requested-border"])!=null?Ke:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(Ce=r["--persona-components-approval-requested-text"])!=null?Ce: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"]=(Ue=r["--persona-components-approval-approve-background"])!=null?Ue:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Te=r["--persona-components-approval-deny-background"])!=null?Te:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(We=r["--persona-components-attachment-image-background"])!=null?We:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(de=r["--persona-components-attachment-image-border"])!=null?de:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(J=r["--persona-semantic-typography-fontFamily"])!=null?J:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(le=r["--persona-semantic-typography-fontSize"])!=null?le:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(ge=r["--persona-semantic-typography-fontWeight"])!=null?ge:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(ue=r["--persona-semantic-typography-lineHeight"])!=null?ue: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"]=(G=r["--persona-palette-radius-sm"])!=null?G:"0.125rem",r["--persona-radius-md"]=(ce=r["--persona-palette-radius-md"])!=null?ce:"0.375rem",r["--persona-radius-lg"]=(Be=r["--persona-palette-radius-lg"])!=null?Be:"0.5rem",r["--persona-radius-xl"]=(ne=r["--persona-palette-radius-xl"])!=null?ne:"0.75rem",r["--persona-radius-full"]=(ee=r["--persona-palette-radius-full"])!=null?ee:"9999px",r["--persona-launcher-radius"]=(vt=(ie=r["--persona-components-launcher-borderRadius"])!=null?ie:r["--persona-palette-radius-full"])!=null?vt:"9999px",r["--persona-launcher-bg"]=(Lt=r["--persona-components-launcher-background"])!=null?Lt:r["--persona-primary"],r["--persona-launcher-fg"]=(gt=r["--persona-components-launcher-foreground"])!=null?gt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(_e=r["--persona-components-launcher-border"])!=null?_e:r["--persona-border"],r["--persona-button-primary-bg"]=(be=r["--persona-components-button-primary-background"])!=null?be:r["--persona-primary"],r["--persona-button-primary-fg"]=(Ze=r["--persona-components-button-primary-foreground"])!=null?Ze:r["--persona-text-inverse"],r["--persona-button-radius"]=(pe=(Y=r["--persona-components-button-primary-borderRadius"])!=null?Y:r["--persona-palette-radius-full"])!=null?pe:"9999px",r["--persona-panel-radius"]=(Je=(Me=r["--persona-components-panel-borderRadius"])!=null?Me:r["--persona-radius-xl"])!=null?Je:"0.75rem",r["--persona-panel-border"]=(Ge=r["--persona-components-panel-border"])!=null?Ge:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(je=(ke=r["--persona-components-panel-shadow"])!=null?ke:r["--persona-palette-shadows-xl"])!=null?je:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(Cr=r["--persona-components-launcher-shadow"])!=null?Cr:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(ur=(Wt=r["--persona-components-input-borderRadius"])!=null?Wt:r["--persona-radius-lg"])!=null?ur:"0.5rem",r["--persona-message-user-radius"]=(V=(Eo=r["--persona-components-message-user-borderRadius"])!=null?Eo:r["--persona-radius-lg"])!=null?V:"0.5rem",r["--persona-message-assistant-radius"]=(he=(j=r["--persona-components-message-assistant-borderRadius"])!=null?j:r["--persona-radius-lg"])!=null?he:"0.5rem",r["--persona-header-bg"]=(Xe=r["--persona-components-header-background"])!=null?Xe:r["--persona-surface"],r["--persona-header-border"]=(et=r["--persona-components-header-border"])!=null?et:r["--persona-divider"],r["--persona-header-icon-bg"]=(qe=r["--persona-components-header-iconBackground"])!=null?qe:r["--persona-primary"],r["--persona-header-icon-fg"]=(Ne=r["--persona-components-header-iconForeground"])!=null?Ne:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Pt=r["--persona-components-header-titleForeground"])!=null?Pt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Gt=r["--persona-components-header-subtitleForeground"])!=null?Gt:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(Jt=r["--persona-components-header-actionIconForeground"])!=null?Jt:r["--persona-muted"];let o=(Pr=e.components)==null?void 0:Pr.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"]=(Ht=r["--persona-components-introCard-background"])!=null?Ht:r["--persona-surface"],r["--persona-intro-card-radius"]=(oe=r["--persona-components-introCard-borderRadius"])!=null?oe:"1rem",r["--persona-intro-card-padding"]=(we=r["--persona-components-introCard-padding"])!=null?we:"1.5rem",r["--persona-intro-card-shadow"]=(At=(De=n==null?void 0:n.shadow)!=null?De:r["--persona-components-introCard-shadow"])!=null?At:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(ar=r["--persona-components-input-background"])!=null?ar:r["--persona-surface"],r["--persona-input-placeholder"]=(sr=r["--persona-components-input-placeholder"])!=null?sr:r["--persona-text-muted"],r["--persona-message-user-bg"]=(wr=r["--persona-components-message-user-background"])!=null?wr:r["--persona-accent"],r["--persona-message-user-text"]=(Ft=r["--persona-components-message-user-text"])!=null?Ft:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(ot=r["--persona-components-message-user-shadow"])!=null?ot:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Dt=r["--persona-components-message-assistant-background"])!=null?Dt:r["--persona-surface"],r["--persona-message-assistant-text"]=(lt=r["--persona-components-message-assistant-text"])!=null?lt:r["--persona-text"],r["--persona-message-assistant-border"]=(Yt=r["--persona-components-message-assistant-border"])!=null?Yt:r["--persona-border"],r["--persona-message-assistant-shadow"]=(so=r["--persona-components-message-assistant-shadow"])!=null?so:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(ir=(Rr=r["--persona-components-scrollToBottom-background"])!=null?Rr:r["--persona-button-primary-bg"])!=null?ir:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(ko=(Ur=r["--persona-components-scrollToBottom-foreground"])!=null?Ur:r["--persona-button-primary-fg"])!=null?ko: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"]=(jr=r["--persona-components-scrollToBottom-size"])!=null?jr:"40px",r["--persona-scroll-to-bottom-radius"]=(yo=(zo=(Lo=r["--persona-components-scrollToBottom-borderRadius"])!=null?Lo:r["--persona-button-radius"])!=null?zo:r["--persona-radius-full"])!=null?yo:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Nn=(ht=r["--persona-components-scrollToBottom-shadow"])!=null?ht:r["--persona-palette-shadows-sm"])!=null?Nn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Po=r["--persona-components-scrollToBottom-padding"])!=null?Po:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(On=r["--persona-components-scrollToBottom-gap"])!=null?On:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(ga=(qr=r["--persona-components-scrollToBottom-fontSize"])!=null?qr:r["--persona-palette-typography-fontSize-sm"])!=null?ga:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(cn=r["--persona-components-scrollToBottom-iconSize"])!=null?cn:"14px",r["--persona-tool-bubble-shadow"]=(jo=r["--persona-components-toolBubble-shadow"])!=null?jo:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(pn=r["--persona-components-reasoningBubble-shadow"])!=null?pn:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(un=r["--persona-components-composer-shadow"])!=null?un:"none",r["--persona-md-inline-code-bg"]=(_n=r["--persona-components-markdown-inlineCode-background"])!=null?_n:r["--persona-container"],r["--persona-md-inline-code-color"]=(Un=r["--persona-components-markdown-inlineCode-foreground"])!=null?Un:r["--persona-text"],r["--persona-md-link-color"]=(Ct=(fn=r["--persona-components-markdown-link-foreground"])!=null?fn:r["--persona-accent"])!=null?Ct:"#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 d=r["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(r["--persona-md-prose-font-family"]=d),r["--persona-md-code-block-bg"]=(Gr=r["--persona-components-markdown-codeBlock-background"])!=null?Gr:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Kr=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Kr:r["--persona-border"],r["--persona-md-code-block-text-color"]=(Ir=r["--persona-components-markdown-codeBlock-textColor"])!=null?Ir:"inherit",r["--persona-md-table-header-bg"]=(Mt=r["--persona-components-markdown-table-headerBackground"])!=null?Mt:r["--persona-container"],r["--persona-md-table-border-color"]=(io=r["--persona-components-markdown-table-borderColor"])!=null?io:r["--persona-border"],r["--persona-md-hr-color"]=(lo=r["--persona-components-markdown-hr-color"])!=null?lo:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(Xr=r["--persona-components-markdown-blockquote-borderColor"])!=null?Xr:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(mn=r["--persona-components-markdown-blockquote-background"])!=null?mn:"transparent",r["--persona-md-blockquote-text-color"]=(Go=r["--persona-components-markdown-blockquote-textColor"])!=null?Go:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(gn=r["--persona-components-collapsibleWidget-container"])!=null?gn:r["--persona-surface"],r["--cw-surface"]=(Qr=r["--persona-components-collapsibleWidget-surface"])!=null?Qr:r["--persona-surface"],r["--cw-border"]=(Nt=r["--persona-components-collapsibleWidget-border"])!=null?Nt:r["--persona-border"],r["--persona-message-border"]=(Wr=r["--persona-components-message-border"])!=null?Wr: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 p=u==null?void 0:u.labelButton;p&&(p.background&&(r["--persona-label-btn-bg"]=p.background),p.border&&(r["--persona-label-btn-border"]=p.border),p.color&&(r["--persona-label-btn-color"]=p.color),p.padding&&(r["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(r["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(r["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(r["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(r["--persona-label-btn-gap"]=p.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 xe=x.toolbar;xe.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,r["--persona-dropdown-bg"]=(co=r["--persona-dropdown-bg"])!=null?co:xe.copyMenuBackground),xe.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,r["--persona-dropdown-border"]=(hn=r["--persona-dropdown-border"])!=null?hn:xe.copyMenuBorder),xe.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,r["--persona-dropdown-shadow"]=(Ko=r["--persona-dropdown-shadow"])!=null?Ko:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(xn=r["--persona-dropdown-radius"])!=null?xn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Ro=r["--persona-dropdown-item-hover-bg"])!=null?Ro:xe.copyMenuItemHoverBackground),xe.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(x!=null&&x.tab){let xe=x.tab;xe.background&&(r["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(r["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(r["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(r["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(r["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(r["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(r["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(x!=null&&x.pane){let xe=x.pane;if(xe.toolbarBackground){let dt=(Jr=qa(e,xe.toolbarBackground))!=null?Jr:xe.toolbarBackground;r["--persona-artifact-toolbar-bg"]=dt}}return r}var lh={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 cb={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"}}},dh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ws=()=>{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"},pb=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Ws()},ip=e=>pb(e),ub=e=>Va(e),fb=e=>{var r;let t=Va(void 0,{validate:!1});return Va({...e,palette:{...t.palette,colors:{...cb.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},$a=e=>{let t=ip(e),r=dh(e==null?void 0:e.theme),o=dh(e==null?void 0:e.darkTheme);return t==="dark"?fb(Is(r!=null?r:{},o!=null?o:{})):ub(r)},mb=e=>Zi(e),Wn=(e,t)=>{let r=$a(t),o=mb(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},el=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Ws())});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(Ws());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 ch=(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:p=>p.getAttribute("im-preserve")==="true",shouldReAppend:p=>p.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(p,m,x={}){p=u(p);let C=g(m),T=d(p,C,x),E=n(T,()=>i(T,p,C,M=>M.morphStyle==="innerHTML"?(a(M,p,C),Array.from(p.childNodes)):o(M,p,C)));return T.pantry.remove(),E}function o(p,m,x){let C=g(m);return a(p,C,x,m,m.nextSibling),Array.from(C.childNodes)}function n(p,m){var P;if(!p.config.restoreFocus)return m();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return m();let{id:C,selectionStart:T,selectionEnd:E}=x,M=m();return C&&C!==((P=document.activeElement)==null?void 0:P.getAttribute("id"))&&(x=p.target.querySelector(`[id="${C}"]`),x==null||x.focus()),x&&!x.selectionEnd&&E&&x.setSelectionRange(T,E),M}let a=(function(){function p(y,w,b,A=null,H=null){w instanceof HTMLTemplateElement&&b instanceof HTMLTemplateElement&&(w=w.content,b=b.content),A||(A=w.firstChild);for(let W of b.childNodes){if(A&&A!=H){let N=x(y,W,A,H);if(N){N!==A&&T(y,A,N),s(N,W,y),A=N.nextSibling;continue}}if(W instanceof Element){let N=W.getAttribute("id");if(y.persistentIds.has(N)){let q=E(w,N,A,y);s(q,W,y),A=q.nextSibling;continue}}let k=m(w,W,A,y);k&&(A=k.nextSibling)}for(;A&&A!=H;){let W=A;A=A.nextSibling,C(y,W)}}function m(y,w,b,A){if(A.callbacks.beforeNodeAdded(w)===!1)return null;if(A.idMap.has(w)){let H=document.createElement(w.tagName);return y.insertBefore(H,b),s(H,w,A),A.callbacks.afterNodeAdded(H),H}else{let H=document.importNode(w,!0);return y.insertBefore(H,b),A.callbacks.afterNodeAdded(H),H}}let x=(function(){function y(A,H,W,k){let N=null,q=H.nextSibling,Z=0,me=W;for(;me&&me!=k;){if(b(me,H)){if(w(A,me,H))return me;N===null&&(A.idMap.has(me)||(N=me))}if(N===null&&q&&b(me,q)&&(Z++,q=q.nextSibling,Z>=2&&(N=void 0)),A.activeElementAndParents.includes(me))break;me=me.nextSibling}return N||null}function w(A,H,W){let k=A.idMap.get(H),N=A.idMap.get(W);if(!N||!k)return!1;for(let q of k)if(N.has(q))return!0;return!1}function b(A,H){var N,q,Z;let W=A,k=H;return W.nodeType===k.nodeType&&W.tagName===k.tagName&&(!((N=W.getAttribute)!=null&&N.call(W,"id"))||((q=W.getAttribute)==null?void 0:q.call(W,"id"))===((Z=k.getAttribute)==null?void 0:Z.call(k,"id")))}return y})();function C(y,w){var b;if(y.idMap.has(w))P(y.pantry,w,null);else{if(y.callbacks.beforeNodeRemoved(w)===!1)return;(b=w.parentNode)==null||b.removeChild(w),y.callbacks.afterNodeRemoved(w)}}function T(y,w,b){let A=w;for(;A&&A!==b;){let H=A;A=A.nextSibling,C(y,H)}return A}function E(y,w,b,A){var W,k;let H=((k=(W=A.target).getAttribute)==null?void 0:k.call(W,"id"))===w&&A.target||A.target.querySelector(`[id="${w}"]`)||A.pantry.querySelector(`[id="${w}"]`);return M(H,A),P(y,H,b),H}function M(y,w){let b=y.getAttribute("id");for(;y=y.parentNode;){let A=w.idMap.get(y);A&&(A.delete(b),A.size||w.idMap.delete(y))}}function P(y,w,b){if(y.moveBefore)try{y.moveBefore(w,b)}catch{y.insertBefore(w,b)}else y.insertBefore(w,b)}return p})(),s=(function(){function p(M,P,y){return y.ignoreActive&&M===document.activeElement?null:(y.callbacks.beforeNodeMorphed(M,P)===!1||(M instanceof HTMLHeadElement&&y.head.ignore||(M instanceof HTMLHeadElement&&y.head.style!=="morph"?c(M,P,y):(m(M,P,y),E(M,y)||a(y,M,P))),y.callbacks.afterNodeMorphed(M,P)),M)}function m(M,P,y){let w=P.nodeType;if(w===1){let b=M,A=P,H=b.attributes,W=A.attributes;for(let k of W)T(k.name,b,"update",y)||b.getAttribute(k.name)!==k.value&&b.setAttribute(k.name,k.value);for(let k=H.length-1;0<=k;k--){let N=H[k];if(N&&!A.hasAttribute(N.name)){if(T(N.name,b,"remove",y))continue;b.removeAttribute(N.name)}}E(b,y)||x(b,A,y)}(w===8||w===3)&&M.nodeValue!==P.nodeValue&&(M.nodeValue=P.nodeValue)}function x(M,P,y){if(M instanceof HTMLInputElement&&P instanceof HTMLInputElement&&P.type!=="file"){let w=P.value,b=M.value;C(M,P,"checked",y),C(M,P,"disabled",y),P.hasAttribute("value")?b!==w&&(T("value",M,"update",y)||(M.setAttribute("value",w),M.value=w)):T("value",M,"remove",y)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&P instanceof HTMLOptionElement)C(M,P,"selected",y);else if(M instanceof HTMLTextAreaElement&&P instanceof HTMLTextAreaElement){let w=P.value,b=M.value;if(T("value",M,"update",y))return;w!==b&&(M.value=w),M.firstChild&&M.firstChild.nodeValue!==w&&(M.firstChild.nodeValue=w)}}function C(M,P,y,w){let b=P[y],A=M[y];if(b!==A){let H=T(y,M,"update",w);H||(M[y]=P[y]),b?H||M.setAttribute(y,""):T(y,M,"remove",w)||M.removeAttribute(y)}}function T(M,P,y,w){return M==="value"&&w.ignoreActiveValue&&P===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(M,P,y)===!1}function E(M,P){return!!P.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return p})();function i(p,m,x,C){if(p.head.block){let T=m.querySelector("head"),E=x.querySelector("head");if(T&&E){let M=c(T,E,p);return Promise.all(M).then(()=>{let P=Object.assign(p,{head:{block:!1,ignore:!0}});return C(P)})}}return C(p)}function c(p,m,x){let C=[],T=[],E=[],M=[],P=new Map;for(let w of m.children)P.set(w.outerHTML,w);for(let w of p.children){let b=P.has(w.outerHTML),A=x.head.shouldReAppend(w),H=x.head.shouldPreserve(w);b||H?A?T.push(w):(P.delete(w.outerHTML),E.push(w)):x.head.style==="append"?A&&(T.push(w),M.push(w)):x.head.shouldRemove(w)!==!1&&T.push(w)}M.push(...P.values());let y=[];for(let w of M){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 A,H=new Promise(function(W){A=W});b.addEventListener("load",function(){A()}),y.push(H)}p.appendChild(b),x.callbacks.afterNodeAdded(b),C.push(b)}}for(let w of T)x.callbacks.beforeNodeRemoved(w)!==!1&&(p.removeChild(w),x.callbacks.afterNodeRemoved(w));return x.head.afterHeadMorphed(p,{added:C,kept:E,removed:T}),y}let d=(function(){function p(y,w,b){let{persistentIds:A,idMap:H}=M(y,w),W=m(b),k=W.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(k))throw`Do not understand how to morph style ${k}`;return{target:y,newContent:w,config:W,morphStyle:k,ignoreActive:W.ignoreActive,ignoreActiveValue:W.ignoreActiveValue,restoreFocus:W.restoreFocus,idMap:H,persistentIds:A,pantry:x(),activeElementAndParents:C(y),callbacks:W.callbacks,head:W.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 T(y){var b;let w=Array.from(y.querySelectorAll("[id]"));return(b=y.getAttribute)!=null&&b.call(y,"id")&&w.push(y),w}function E(y,w,b,A){for(let H of A){let W=H.getAttribute("id");if(w.has(W)){let k=H;for(;k;){let N=y.get(k);if(N==null&&(N=new Set,y.set(k,N)),N.add(W),k===b)break;k=k.parentElement}}}}function M(y,w){let b=T(y),A=T(w),H=P(b,A),W=new Map;E(W,H,y,b);let k=w.__idiomorphRoot||w;return E(W,H,k,A),{persistentIds:H,idMap:W}}function P(y,w){let b=new Set,A=new Map;for(let{id:W,tagName:k}of y)A.has(W)?b.add(W):A.set(W,k);let H=new Set;for(let{id:W,tagName:k}of w)H.has(W)?b.add(W):A.get(W)===k&&H.add(W);for(let W of b)H.delete(W);return H}return p})(),{normalizeElement:u,normalizeParent:g}=(function(){let p=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(T(E));if(p.has(E))return E;if(E instanceof Node){if(E.parentNode)return new C(E);{let M=document.createElement("div");return M.append(E),M}}else{let M=document.createElement("div");for(let P of[...E])M.append(P);return M}}class C{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],P=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;P&&P!=this.nextSibling;)M.push(P),P=P.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((P,y)=>{if(y instanceof Element){y.matches(M)&&P.push(y);let w=y.querySelectorAll(M);for(let b=0;b<w.length;b++)P.push(w[b])}return P},[])}insertBefore(M,P){return this.realParentNode.insertBefore(M,P)}moveBefore(M,P){return this.realParentNode.moveBefore(M,P)}get __idiomorphRoot(){return this.originalNode}}function T(E){let M=new DOMParser,P=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(P.match(/<\/html>/)||P.match(/<\/head>/)||P.match(/<\/body>/)){let y=M.parseFromString(E,"text/html");if(P.match(/<\/html>/))return p.add(y),y;{let w=y.firstChild;return w&&p.add(w),w}}else{let w=M.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return p.add(w),w}}return{normalizeElement:m,normalizeParent:x}})();return{morph:r,defaults:t}})();var tl=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;ch.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:"",d=(i=a.textContent)!=null?i:"";if(c!==d)return}return!1}}}}})};var rl={index:-1,draft:""};function ph(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:{...rl}}}function uh(e,t){var r,o,n,a,s,i,c,d,u,g,p,m,x,C,T,E,M,P,y,w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de,J,le;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,(u=(d=e.llmContent)==null?void 0:d.length)!=null?u:0,(p=(g=e.approval)==null?void 0:g.status)!=null?p:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(T=(C=e.toolCall)==null?void 0:C.name)!=null?T:"",(P=(M=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:M.length)!=null?P:0,(A=(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?A:"",typeof((H=e.toolCall)==null?void 0:H.args)=="string"?e.toolCall.args.length:(W=e.toolCall)!=null&&W.args?JSON.stringify(e.toolCall.args).length:0,(q=(N=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:N.length)!=null?q:0,(Ce=(Ke=(me=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:Ke.length)!=null?Ce:0,(We=(Te=(Ue=(Ie=e.reasoning)==null?void 0:Ie.chunks)==null?void 0:Ue[e.reasoning.chunks.length-1])==null?void 0:Te.slice(-32))!=null?We:"",(J=(de=e.contentParts)==null?void 0:de.length)!=null?J:0,(le=e.stopReason)!=null?le:"",t].join("\0")}function fh(){return new Map}function mh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function gh(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function hh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function ol(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function sn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function da(e,t){return sn(e)-e.scrollTop<=t}function nl(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!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&&c&&!n?{action:"pause",delta:u,nextLastScrollTop:r}:{action:"none",delta:u,nextLastScrollTop:r}}function al(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 xh(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function yh(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 bh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var kr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Lr=1e5,Hn=Lr+1;var Hs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},gb=["pre","code","a","script","style"],sl=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"}],Bs=new Map;for(let e of Ch)Bs.set(e.name,e);var ca=e=>{Bs.set(e.name,e)},cp=e=>{Ch.some(t=>t.name===e)||Bs.delete(e)},pp=()=>Array.from(Bs.keys()),Ds=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Bs.get(e))!=null?o:null},il=(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},lp=/\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 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(lp.test(a[i])){let d=i;for(;d<a.length&&lp.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&&!lp.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 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 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)},Fs=(e,t,r,o)=>{var g,p;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=[],c=s.nextNode();for(;c;)yb(c,a)||i.push(c),c=s.nextNode();let d={value:(p=o==null?void 0:o.startIndex)!=null?p:0},u=t==="char"?bb:vb;for(let m of i)u(m,r,d);return n.innerHTML},ll=(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},Ns=(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},vh=new WeakMap,Cb=(e,t)=>{var a;if(!e.styles)return;let r=vh.get(t);if(r||(r=new Set,vh.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)},dp=new WeakMap,wb=(e,t)=>{if(!e.onAttach)return;let r=dp.get(t);if(r||(r=new Map,dp.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},wh=e=>{let t=dp.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},up=(e,t)=>{Cb(e,t),wb(e,t)};function fp(e,t=Lr){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 Os=0,Bn=null;function mp(e=document){var r;if(Os++,Os===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Bn={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,Os=Math.max(0,Os-1),Os===0&&Bn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Bn.originalOverflow,n.style.position=Bn.originalPosition,n.style.top=Bn.originalTop,n.style.width=Bn.originalWidth,a.scrollTo(0,Bn.scrollY),Bn=null}}}var _s={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},pr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Dn=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},no=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:_s.side,width:(n=t==null?void 0:t.width)!=null?n:_s.width,animate:(a=t==null?void 0:t.animate)!=null?a:_s.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:_s.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:_s.maxHeight}};var To={"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",dl=(e,t={})=>{var T,E,M,P,y,w;let{showClose:r=!0,wrapperClassName:o=Sb,buttonSize:n,iconSize:a="28px"}=t,s=(T=e==null?void 0:e.launcher)!=null?T:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=S("div",o),d=(M=s.closeButtonTooltipText)!=null?M:"Close chat",u=(P=s.closeButtonShowTooltip)!=null?P:!0,g=(y=s.closeButtonIconName)!=null?y:"x",p=(w=s.closeButtonIconText)!=null?w:"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=kt("button",{className:vs("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||_r.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=ve(g,a,"currentColor",1);if(C?(C.style.display="block",x.appendChild(C)):x.textContent=p,c.appendChild(x),u&&d){let b=null,A=()=>{if(b)return;let W=x.ownerDocument,k=W.body;if(!k)return;b=Vo(W,"div","persona-clear-chat-tooltip"),b.textContent=d;let N=Vo(W,"div");N.className="persona-clear-chat-tooltip-arrow",b.appendChild(N);let q=x.getBoundingClientRect();b.style.position="fixed",b.style.zIndex=String(Hn),b.style.left=`${q.left+q.width/2}px`,b.style.top=`${q.top-8}px`,b.style.transform="translate(-50%, -100%)",k.appendChild(b)},H=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};c.addEventListener("mouseenter",A),c.addEventListener("mouseleave",H),x.addEventListener("focus",A),x.addEventListener("blur",H),c._cleanupTooltip=()=>{H(),c.removeEventListener("mouseenter",A),c.removeEventListener("mouseleave",H),x.removeEventListener("focus",A),x.removeEventListener("blur",H)}}return{button:x,wrapper:c}},Ab="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",cl=(e,t={})=>{var b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue;let{wrapperClassName:r=Ab,buttonSize:o,iconSize:n="20px"}=t,s=(A=((b=e==null?void 0:e.launcher)!=null?b:{}).clearChat)!=null?A:{},i=(H=o!=null?o:s.size)!=null?H:"32px",c=(W=s.iconName)!=null?W:"refresh-cw",d=(k=s.iconColor)!=null?k:"",u=(N=s.backgroundColor)!=null?N:"",g=(q=s.borderWidth)!=null?q:"",p=(Z=s.borderColor)!=null?Z:"",m=(me=s.borderRadius)!=null?me:"",x=(Ke=s.paddingX)!=null?Ke:"",C=(Ce=s.paddingY)!=null?Ce:"",T=(Ie=s.tooltipText)!=null?Ie:"Clear chat",E=(Ue=s.showTooltip)!=null?Ue:!0,M=S("div",r),P=!!(g||p),y=kt("button",{className:vs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!P&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:d||_r.actionIconColor,backgroundColor:u||void 0,border:P?`${g||"0px"} solid ${p||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),w=ve(c,n,"currentColor",1);if(w&&(w.style.display="block",y.appendChild(w)),M.appendChild(y),E&&T){let Te=null,We=()=>{if(Te)return;let J=y.ownerDocument,le=J.body;if(!le)return;Te=Vo(J,"div","persona-clear-chat-tooltip"),Te.textContent=T;let ge=Vo(J,"div");ge.className="persona-clear-chat-tooltip-arrow",Te.appendChild(ge);let ue=y.getBoundingClientRect();Te.style.position="fixed",Te.style.zIndex=String(Hn),Te.style.left=`${ue.left+ue.width/2}px`,Te.style.top=`${ue.top-8}px`,Te.style.transform="translate(-50%, -100%)",le.appendChild(Te)},de=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};M.addEventListener("mouseenter",We),M.addEventListener("mouseleave",de),y.addEventListener("focus",We),y.addEventListener("blur",de),M._cleanupTooltip=()=>{de(),M.removeEventListener("mouseenter",We),M.removeEventListener("mouseleave",de),y.removeEventListener("focus",We),y.removeEventListener("blur",de)}}return{button:y,wrapper:M}};var _r={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))"},ln=e=>{var w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We;let{config:t,showClose:r=!0}=e,o=kt("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=(A=n.closeButtonPlacement)!=null?A:"inline",i=(H=n.headerIconHidden)!=null?H:!1,c=n.headerIconName,d=kt("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 de=parseFloat(a)||24,J=ve(c,de*.6,"currentColor",1);J?d.replaceChildren(J):d.textContent=(k=(W=t==null?void 0:t.launcher)==null?void 0:W.agentIconText)!=null?k:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let de=S("img");de.src=t.launcher.iconUrl,de.alt="",de.className="persona-rounded-xl persona-object-cover",de.style.height=a,de.style.width=a,d.replaceChildren(de)}else d.textContent=(Z=(q=t==null?void 0:t.launcher)==null?void 0:q.agentIconText)!=null?Z:"\u{1F4AC}";let u=S("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=kt("span",{className:"persona-text-base persona-font-semibold",text:(Ke=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?Ke:"Chat Assistant",style:{color:_r.titleColor}}),p=kt("span",{className:"persona-text-xs",text:(Ie=(Ce=t==null?void 0:t.launcher)==null?void 0:Ce.subtitle)!=null?Ie:"Here to help you get answers fast",style:{color:_r.subtitleColor}});u.append(g,p),i?o.append(u):o.append(d,u);let m=(Ue=n.clearChat)!=null?Ue:{},x=(Te=m.enabled)!=null?Te:!0,C=(We=m.placement)!=null?We:"inline",T=null,E=null;if(x){let J=cl(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=J.button,E=J.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let M=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:P,wrapper:y}=dl(t,{showClose:r,wrapperClassName:M});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:d,headerTitle:g,headerSubtitle:p,closeButton:P,closeButtonWrapper:y,clearChatButton:T,clearChatButtonWrapper:E}},pa=(e,t,r)=>{var s,i,c,d;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(d=(c=o.clearChat)==null?void 0:c.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 Fn(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(Hn)):(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 T=document.createElement("hr");s.appendChild(T)}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 T=ve(m.icon,16,"currentColor",1.5);T&&x.appendChild(T)}let C=document.createElement("span");C.textContent=m.label,x.appendChild(C),x.addEventListener("click",T=>{T.stopPropagation(),u(),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 d(){c(),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 p(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:u,toggle:g,destroy:p}}function yr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=S("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let d=ve(t,o!=null?o:16,"currentColor",n!=null?n:2);if(d&&c.appendChild(d),s&&c.addEventListener("click",s),i)for(let[u,g]of Object.entries(i))c.setAttribute(u,g);return c}function Us(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=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 p=ve(t,a!=null?a:14,"currentColor",2);p&&u.appendChild(p)}let g=S("span");if(g.textContent=r,u.appendChild(g),i&&u.addEventListener("click",i),c)for(let[p,m]of Object.entries(c))u.setAttribute(p,m);return u}function Sh(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 c(){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=yr({icon:u.icon,label:u.label,onClick:()=>{s=u.id,c(),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,c(),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,c()}return{element:a,setSelected:d}}function pl(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,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=ve(r,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",d.appendChild(g)),c&&(d.style.borderRadius=(m=c.borderRadius)!=null?m:"10px",d.style.padding=(x=c.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,T;d.style.backgroundColor=(C=c.background)!=null?C:"",d.style.borderColor=(T=c.border)!=null?T:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let p=Fn({items:o,onSelect:C=>{d.setAttribute("aria-expanded","false"),n(C)},anchor:d,position:a,portal:s});return s||d.appendChild(p.element),d.addEventListener("click",C=>{C.stopPropagation();let T=!p.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",T?"false":"true"),p.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"),p.show()},close:()=>{d.setAttribute("aria-expanded","false"),p.hide()},toggle:()=>{let C=!p.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",C?"false":"true"),p.toggle()},destroy:()=>{p.destroy(),d.remove()}}}var gp=e=>{var o;let t=ln({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 c=ve(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=S("div","persona-relative");c.appendChild(i);let d=Fn({items:s.menuItems,onSelect:u=>r==null?void 0:r(u),anchor:c,position:"bottom-left"});c.appendChild(d.element),i.addEventListener("click",u=>{u.stopPropagation(),d.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var hp=e=>{var M,P,y,w,b,A,H,W,k;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(M=t==null?void 0:t.launcher)!=null?M:{},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 c=n==null?void 0:n.titleMenu,d,u;if(c)d=pl({label:(P=s.title)!=null?P:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,d.style.color=_r.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=_r.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 q=n.onTitleClick;d.addEventListener("click",Z=>{Z.target.closest("button")||q()}),d.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),q())})}let N=n==null?void 0:n.titleRowHover;N&&(d.style.borderRadius=(A=N.borderRadius)!=null?A:"10px",d.style.padding=(H=N.padding)!=null?H:"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 q,Z;d.style.backgroundColor=(q=N.background)!=null?q:"",d.style.borderColor=(Z=N.border)!=null?Z:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let g=(W=s.closeButtonSize)!=null?W:"32px",p=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||_r.actionIconColor;let x=(k=s.closeButtonIconName)!=null?k:"x",C=ve(x,"28px","currentColor",1);C?m.appendChild(C):m.textContent="\xD7",o&&m.addEventListener("click",o),p.appendChild(m),i.appendChild(p);let T=S("div");T.style.display="none";let E=S("span");return E.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:E,closeButton:m,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},ul={default:gp,minimal:hp},xp=e=>{var t;return(t=ul[e])!=null?t:ul.default},za=(e,t,r)=>{var s,i,c;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"),p=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:p,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=xp(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 fl=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 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}},ml=e=>{var w,b,A,H,W,k,N,q,Z,me,Ke,Ce;let t=(w=e==null?void 0:e.sendButton)!=null?w:{},r=(b=t.useIcon)!=null?b:!1,o=(A=t.iconText)!=null?A:"\u2191",n=t.iconName,a=(H=t.stopIconName)!=null?H:"square",s=(W=t.tooltipText)!=null?W:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",c=(q=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?q:"Send",d=(me=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?me:"Stop",u=(Ke=t.showTooltip)!=null?Ke:!1,g=(Ce=t.size)!=null?Ce:"40px",p=t.backgroundColor,m=t.textColor,x=S("div","persona-send-button-wrapper"),C=kt("button",{className:vs("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&&!p&&"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&&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}}),T=null,E=null;if(r){let Ie=parseFloat(g)||24,Ue=(m==null?void 0:m.trim())||"currentColor";n?(T=ve(n,Ie,Ue,2),T?C.appendChild(T):C.textContent=o):C.textContent=o,E=ve(a,Ie,Ue,2)}else C.textContent=c;let M=null;u&&s&&(M=S("div","persona-send-button-tooltip"),M.textContent=s,x.appendChild(M)),C.setAttribute("aria-label",s),x.appendChild(C);let P="send";return{button:C,wrapper:x,setMode:Ie=>{if(Ie===P)return;P=Ie;let Ue=Ie==="stop"?i:s;if(C.setAttribute("aria-label",Ue),M&&(M.textContent=Ue),r){if(T&&E){let Te=Ie==="stop"?E:T;C.replaceChildren(Te)}}else C.textContent=Ie==="stop"?d:c}}},gl=e=>{var M,P,y,w,b,A,H,W,k,N,q,Z;let t=(M=e==null?void 0:e.voiceRecognition)!=null?M:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((P=t.provider)==null?void 0:P.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",c=(A=t.iconSize)!=null?A:s,d=parseFloat(c)||24,u=(W=t.backgroundColor)!=null?W:(H=e==null?void 0:e.sendButton)==null?void 0:H.backgroundColor,g=(N=t.iconColor)!=null?N:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor,p=S("div","persona-send-button-wrapper"),m=kt("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: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=ve(i,d,g||"currentColor",1.5);C?m.appendChild(C):m.textContent="\u{1F3A4}",p.appendChild(m);let T=(q=t.tooltipText)!=null?q:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&T){let me=S("div","persona-send-button-tooltip");me.textContent=T,p.appendChild(me)}return{button:m,wrapper:p}},hl=e=>{var x,C,T,E,M,P,y,w;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(T=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?T:"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=((E=t.allowedTypes)!=null?E:an).join(","),n.multiple=((M=t.maxFiles)!=null?M:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(P=t.buttonIconName)!=null?P:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),d=S("div","persona-send-button-wrapper"),u=kt("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=ve(a,c,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",b=>{b.preventDefault(),n.click()}),d.appendChild(u);let p=(w=t.buttonTooltipText)!=null?w:"Attach file",m=S("div","persona-send-button-tooltip");return m.textContent=p,d.appendChild(m),{button:u,wrapper:d,input:n,previewsContainer:o}},xl=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=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=(c=t.idleText)!=null?c:"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},yl=()=>kt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ja=e=>{var x,C,T,E,M,P;let{config:t}=e,r=kt("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=yl(),n=kt("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}=fl(t);s();let i=ml(t),c=gl(t),d=hl(t),u=xl(t);d&&(d.previewsContainer.style.gap="8px",n.append(d.previewsContainer,d.input)),n.append(a);let g=kt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),p=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&&p.append(d.wrapper),c&&m.append(c.wrapper),m.append(i.wrapper),g.append(p,m),n.append(g),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!==(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=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,statusText:u,attachmentButton:(T=d==null?void 0:d.button)!=null?T:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(M=d==null?void 0:d.input)!=null?M:null,attachmentPreviewsContainer:(P=d==null?void 0:d.previewsContainer)!=null?P:null,actionsRow:g,leftActions:p,rightActions:m,setSendButtonMode:i.setMode}};var Ah=()=>{let e=kt("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=ve("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=ve("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Mh=e=>{var x,C,T,E,M,P;let{config:t}=e,r=kt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=yl();o.style.display="none";let n=xl(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=fl(t);a.style.maxHeight="100px",s();let i=ml(t),c=gl(t),d=hl(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let u=kt("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 p=S("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&p.append(c.wrapper),p.append(i.wrapper),u.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!==(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,p),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=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,statusText:n,attachmentButton:(T=d==null?void 0:d.button)!=null?T:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(M=d==null?void 0:d.input)!=null?M:null,attachmentPreviewsContainer:(P=d==null?void 0:d.previewsContainer)!=null?P:null,actionsRow:m,leftActions:g,rightActions:p,setSendButtonMode:i.setMode}};var Th=e=>{var u,g,p,m,x,C,T,E,M,P,y,w,b,A,H,W,k;let t=(g=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?g:!0,r=pr(e);if(Dn(e)){let N=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.composerBar)!=null?m:{},q=S("div","persona-widget-wrapper persona-fixed persona-transition");q.setAttribute("data-persona-composer-bar",""),q.dataset.state="collapsed",q.dataset.expandedSize=(x=N.expandedSize)!=null?x:"anchored",q.style.zIndex=String((T=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?T:Lr);let Z=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",q.appendChild(Z);let me=S("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=N.expandedSize)!=null?E:"anchored",me.style.zIndex=String((P=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?P:Lr),{wrapper:q,panel:Z,pillRoot:me}}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"),q=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(q),{wrapper:N,panel:q}}if(!t){let N=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),q=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?w:"100%";return N.style.width=Z,q.style.width="100%",N.appendChild(q),{wrapper:N,panel:q}}let n=(b=e==null?void 0:e.launcher)!=null?b:{},a=n.position&&To[n.position]?To[n.position]:To["bottom-right"],s=S("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((H=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?H:Lr);let i=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(k=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?k:e==null?void 0:e.launcherWidth,d=c!=null?c:oo;return i.style.width=d,i.style.maxWidth=d,s.appendChild(i),{wrapper:s,panel:i}},Tb=(e,t)=>{var y,w,b,A,H,W,k,N,q;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}=dl(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 Z=cl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=kt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=kt("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=kt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(H=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?H:"Hello \u{1F44B}"}),g=kt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),p=kt("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%"),((q=e==null?void 0:e.copy)==null?void 0:q.showWelcomeCard)!==!1||(p.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(p,m);let T=kt("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=Mh({config:e}),{root:M,textNode:P}=Ah();return r.append(c,n,d,T),i&&r.appendChild(i),{container:r,body:d,messagesWrapper:m,composerOverlay:T,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:u,introSubtitle:g,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("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:M,peekTextNode:P}},Eh=(e,t=!0)=>{var T,E,M,P,y,w,b,A,H;if(Dn(e))return Tb(e,t);let r=kt("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=(T=e==null?void 0:e.layout)==null?void 0:T.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?za(e,o,{showClose:t}):ln({config:e,showClose:t}),s=kt("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=kt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(P=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?P:"Hello \u{1F44B}"}),c=kt("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=kt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:pr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),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%"),((A=e==null?void 0:e.copy)==null?void 0:A.showWelcomeCard)!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,u);let m=ja({config:e}),x=((H=e==null?void 0:e.layout)==null?void 0:H.showFooter)!==!1;n?pa(r,a,e):(a.header.style.display="none",pa(r,a,e)),r.append(s);let C=kt("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: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 yp=(e,t)=>{let r=S("button");r.type="button",r.innerHTML=`
17
+ _Details: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]}),sh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ih=e=>ea(e)||e===Ao,_a=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 ia(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,d,u,g;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall,m=!!(p!=null&&p.name)&&(ea(p.name)||p.name===Ao&&((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 p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((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 na(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||dd().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 Ls((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=Rn.isSupported()?new Rn({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,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(c&&d&&u)return dd().then(({RuntypeSpeechEngine:p,FallbackSpeechEngine:m})=>{let x=new p({host:c,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=In(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,d)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:c,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:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:c,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 c,d;(d=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||d.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,d;this.voiceStatus=i,this.voiceActive=i==="listening",(d=(c=this.callbacks).onVoiceStatusChanged)==null||d.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,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:(c=t.runtype)==null?void 0:c.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(!sb(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 na(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:d=!1,voiceProcessing:u,rawContent:g}=t,m={id:s!=null?s:r==="user"?Na():r==="assistant"?aa():`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: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:c,createdAt:d,sequence:u,streaming:g=!1,voiceProcessing:p,rawContent:m}=o,C={id:c!=null?c:n==="user"?Na():n==="assistant"?aa():`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},...p!==void 0&&{voiceProcessing:p},...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:c}=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},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var d,u,g,p,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=Na(),a=aa(),s={id:n,role:"user",content:o||Fi,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 C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let T=ah(x,this.config.errorMessage);if(T){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,x):(m=(p=this.callbacks).onError)==null||m.call(p,new Error(String(x))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort();let t=aa();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=ah(d,this.config.errorMessage);if(g){let p={id:t,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(p)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,d):(c=(i=this.callbacks).onError)==null||c.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,p,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 c=this.config.approval,d=c&&typeof c=="object"?c.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 T=null;if(C instanceof Response){if(!C.ok){let E=await C.json().catch(()=>null);throw new Error((p=E==null?void 0:E.error)!=null?p:`Approval request failed: ${C.status}`)}T=C.body}else C instanceof ReadableStream&&(T=C);T?await this.connectStream(T,{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 T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(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,p,m,x,C,T,E,w,k,y,S;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=(p=t.toolCall)==null?void 0:p.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,M=Array.isArray(b==null?void 0:b.questions)?b.questions:[];if(M.length===1){let W=typeof((T=M[0])==null?void 0:T.question)=="string"?M[0].question:"";W&&(s={[W]:r})}}this.markAskUserQuestionResolved(t,s),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(w=t.toolCall)==null?void 0:w.args,d=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(d.length===0){let b=typeof r=="string"?r:Object.entries(r).map(([M,W])=>`${M}: ${Array.isArray(W)?W.join(", "):W}`).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((M,W)=>{let R=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!R)return;let L=b[R],N=Array.isArray(L)?L.join(", "):typeof L=="string"?L:"";this.appendMessage({id:`ask-user-q-${i}-${W}`,role:"assistant",content:R,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${W}`,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 M=await b.json().catch(()=>null);throw new Error((k=M==null?void 0:M.error)!=null?k:`Resume failed: ${b.status}`)}b.body?await this.connectStream(b.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(b){let M=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(S=(y=this.callbacks).onError)==null||S.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)!==Ao)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,d,u,g;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async p=>{var S,b,M,W,R,L,N;let m=(S=p.toolCall)==null?void 0:S.name,x=(b=p.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(p))return null;this.webMcpInflightKeys.add(C),o.push(C);let T=this.markWebMcpToolRunning(p),E=(W=(M=p.agentMetadata)==null?void 0:M.webMcpToolCallId)!=null?W:m;if(m===Ao)return{dedupeKey:C,resumeKey:E,output:td(),toolMessage:p,startedAt:T,completedAt:Date.now()};let w=new AbortController;this.webMcpResolveControllers.add(w),n.push(w);let k=this.client.executeWebMcpToolCall(m,(R=p.toolCall)==null?void 0:R.args,w.signal),y;if(!k)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await k}catch(q){let Y=q instanceof Error&&(q.name==="AbortError"||q.message.includes("aborted")||q.message.includes("abort"));return Y||(N=(L=this.callbacks).onError)==null||N.call(L,q instanceof Error?q:new Error(String(q))),this.markWebMcpToolComplete(p,Ps(Y?"Aborted by cancel()":sh(q)),T),this.webMcpInflightKeys.delete(C),null}return w.signal.aborted?(this.markWebMcpToolComplete(p,Ps("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:E,output:y,toolMessage:p,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=s.filter(x=>x!==null),i.length===0)return;let p={};for(let x of i)p[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,p,{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,((d=x.toolMessage.toolCall)==null?void 0:d.name)===Ao?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,p instanceof Error?p:new Error(String(p)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,Ps("Aborted by cancel()"),x.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of n)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,C,T,E,w,k,y,S,b,M,W,R;let r=(x=t.agentMetadata)==null?void 0:x.executionId,o=(C=t.toolCall)==null?void 0:C.name,n=(T=t.toolCall)==null?void 0:T.id;if(!r){(w=(E=this.callbacks).onError)==null||w.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let L=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(L)||this.webMcpResolvedKeys.has(L))return;this.webMcpInflightKeys.add(L);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(L)}catch(N){(y=(k=this.callbacks).onError)==null||y.call(k,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(L)}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 d=o===Ao,u=(S=t.toolCall)==null?void 0:S.args,g=d?null:this.client.executeWebMcpToolCall(o,u,c),p="execute",m=s;try{let L;if(d?L=td():g?L=await g:L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),c.aborted){this.markWebMcpToolComplete(t,Ps("Aborted by cancel()"),s);return}let N=(M=(b=t.agentMetadata)==null?void 0:b.webMcpToolCallId)!=null?M:o;p="resume",await this.resumeWithToolOutput(r,N,L,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,L,s,m,d?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(L){let N=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));(p==="execute"||N||c.aborted)&&this.markWebMcpToolComplete(t,Ps(N||c.aborted?"Aborted by cancel()":sh(L)),s),N||(R=(W=this.callbacks).onError)==null||R.call(W,L instanceof Error?L:new Error(String(L)))}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=id(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Oa(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=id(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,p,m,x,C,T,E,w,k,y,S,b,M,W;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={...(p=s.agentMetadata)!=null?p:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let R=n.approval,L=r.approval;s.approval={...R,...L,executionId:L.executionId||R.executionId,toolName:L.toolName||R.toolName,description:L.description||R.description,toolType:(m=L.toolType)!=null?m:R.toolType,reason:(x=L.reason)!=null?x:R.reason,parameters:(C=L.parameters)!=null?C:R.parameters}}let i=(T=r.toolCall)==null?void 0:T.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,d=(w=r.toolCall)==null?void 0:w.id;if(i&&ih(i)&&c&&d&&((k=r.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let R=`${c}:${d}`,L=this.webMcpInflightKeys.has(R),N=this.webMcpResolvedKeys.has(R),q=(y=n.toolCall)==null?void 0:y.name,Y=((S=n.agentMetadata)==null?void 0:S.executionId)===c&&((b=n.toolCall)==null?void 0:b.id)===d&&q!==void 0&&ih(q)&&((M=n.toolCall)==null?void 0:M.status)==="complete";(L||N||Y)&&(s.agentMetadata={...(W=s.agentMetadata)!=null?W:{},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,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=(c=r.sequence)!=null?c:0,i=(d=o.sequence)!=null?d:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var cd=[["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 pd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var ud=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var fd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var md=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var gd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var hd=[["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 xd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var yd=[["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 bd=[["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 vd=[["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 Cd=[["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 wd=[["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 Sd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Ad=[["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 Md=[["path",{d:"M20 6 9 17l-5-5"}]];var Td=[["path",{d:"m6 9 6 6 6-6"}]];var Ed=[["path",{d:"m15 18-6-6 6-6"}]];var kd=[["path",{d:"m9 18 6-6-6-6"}]];var Ld=[["path",{d:"m18 15-6-6-6 6"}]];var Ui=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var qi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Pd=[["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 Id=[["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 Rd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Wd=[["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 Hd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Bd=[["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 Dd=[["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 Vi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var $i=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Fd=[["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 Nd=[["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 Od=[["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 _d=[["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 Ud=[["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 qd=[["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 $d=[["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 zd=[["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 jd=[["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 Gd=[["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 Kd=[["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 zi=[["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 Xd=[["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 Qd=[["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 Jd=[["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 Yd=[["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 Zd=[["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 ec=[["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 ji=[["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 tc=[["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 rc=[["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 oc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var nc=[["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 ac=[["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 Gi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var sc=[["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 ic=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var lc=[["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 dc=[["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 cc=[["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 pc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var uc=[["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 fc=[["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 mc=[["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 gc=[["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 hc=[["path",{d:"M5 12h14"}]];var xc=[["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 yc=[["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 bc=[["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 vc=[["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 Cc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var wc=[["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 Sc=[["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 Ac=[["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 Mc=[["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 Tc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Ec=[["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 kc=[["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 Pc=[["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 Ic=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Rc=[["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 Wc=[["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 Hc=[["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 Bc=[["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 Dc=[["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 Ki=[["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 Fc=[["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 Nc=[["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 Oc=[["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 _c=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Xi=[["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 Uc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var qc=[["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 Vc=[["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 $c=[["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 zc=[["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 jc=[["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 Gc=[["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 Kc=[["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 Xc=[["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 Qc=[["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 Qi=[["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 Jc=[["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 Yc=[["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 Zc=[["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 ep=[["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 tp=[["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 rp=[["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 op=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var np=[["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 ib={activity:cd,"arrow-down":pd,"arrow-up":gd,"arrow-up-right":md,bot:vd,"chevron-down":Td,"chevron-up":Ld,"chevron-right":kd,"chevron-left":Ed,check:Md,clipboard:Id,"clipboard-copy":Pd,copy:Wd,file:Vd,"file-code":_d,"file-spreadsheet":Ud,"file-text":qd,"image-plus":tc,loader:sc,"loader-circle":Gi,mic:mc,paperclip:vc,"refresh-cw":kc,search:Ic,send:Rc,"shield-alert":Bc,"shield-check":Dc,"shield-x":Ki,square:Uc,"thumbs-down":jc,"thumbs-up":Gc,upload:Yc,"volume-2":ep,x:op,user:Zc,mail:lc,phone:Ac,calendar:Sd,clock:Rd,building:Cd,"map-pin":dc,lock:ic,key:nc,"credit-card":Hd,"at-sign":hd,hash:Jd,globe:Qd,link:ac,"circle-check":Ui,"circle-x":qi,"triangle-alert":Qi,info:oc,ban:xd,shield:Fc,"arrow-left":ud,"arrow-right":fd,"external-link":Nd,ellipsis:$i,"ellipsis-vertical":Vi,menu:pc,house:ji,plus:Tc,minus:hc,pencil:wc,trash:Qc,"trash-2":Xc,save:Pc,download:Dd,share:Hc,funnel:zi,settings:Wc,"rotate-cw":Lc,maximize:cc,minimize:gc,"shopping-cart":Oc,"shopping-bag":Nc,package:bc,truck:Jc,tag:zc,gift:Xd,receipt:Ec,wallet:rp,store:Vc,"dollar-sign":Bd,percent:Sc,play:Mc,pause:Cc,"volume-x":tp,camera:Ad,image:rc,film:zd,headphones:Yd,"message-circle":uc,"message-square":fc,bell:yd,heart:Zd,star:qc,eye:Od,"eye-off":Fd,bookmark:bd,"calendar-days":wd,history:ec,timer:Kc,folder:Kd,"folder-open":Gd,files:$d,sparkles:Xi,zap:np,sun:$c,moon:yc,flag:jd,monitor:xc,smartphone:_c},ve=(e,t=24,r="currentColor",o=2)=>{let n=ib[e];return n?lb(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 lb(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(([d,u])=>{d!=="stroke"&&c.setAttribute(d,String(u))}),n.appendChild(c)}),n}var Ji={allowedTypes:an,maxFileSize:10*1024*1024,maxFiles:4};function db(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cb(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 la=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ji.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ji.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Ji.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:Ji.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 d of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,d,"count");continue}let u=eh(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 Zg(d),p=Ni(d)?URL.createObjectURL(d):null,m={id:db(),file:d,previewUrl:p,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}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=Ni(t.file),o=A("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=A("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=A("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=cb(t.file.type),c=ve(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let d=A("span");d.textContent=th(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=A("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=ve("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 lh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Is(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];lh(a)&&lh(n)?r[o]=Is(a,n):r[o]=n}return r}var no="min(440px, calc(100vw - 24px))",Yi="440px",pb={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:no,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)"},$t={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:pb,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 dh(e,t){if(!(!e&&!t))return e?t?Is(e,t):e:t}function Zi(e){var t,r,o,n,a,s,i,c,d,u,g,p,m,x,C,T,E,w,k,y,S;return e?{...$t,...e,theme:dh($t.theme,e.theme),darkTheme:dh($t.darkTheme,e.darkTheme),launcher:{...$t.launcher,...e.launcher,dock:{...(t=$t.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=$t.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{...$t.copy,...e.copy},sendButton:{...$t.sendButton,...e.sendButton},statusIndicator:{...$t.statusIndicator,...e.statusIndicator},voiceRecognition:{...$t.voiceRecognition,...e.voiceRecognition},features:(()=>{var le,Q,ie,ge,ue,j,de,Ne,te,Z;let b=(le=$t.features)==null?void 0:le.artifacts,M=(Q=e.features)==null?void 0:Q.artifacts,W=(ie=$t.features)==null?void 0:ie.scrollToBottom,R=(ge=e.features)==null?void 0:ge.scrollToBottom,L=(ue=$t.features)==null?void 0:ue.scrollBehavior,N=(j=e.features)==null?void 0:j.scrollBehavior,q=(de=$t.features)==null?void 0:de.streamAnimation,Y=(Ne=e.features)==null?void 0:Ne.streamAnimation,me=(te=$t.features)==null?void 0:te.askUserQuestion,Ge=(Z=e.features)==null?void 0:Z.askUserQuestion,Ce=b===void 0&&M===void 0?void 0:{...b,...M,layout:{...b==null?void 0:b.layout,...M==null?void 0:M.layout}},Be=W===void 0&&R===void 0?void 0:{...W,...R},qe=L===void 0&&N===void 0?void 0:{...L,...N},Ee=q===void 0&&Y===void 0?void 0:{...q,...Y},De=me===void 0&&Ge===void 0?void 0:{...me,...Ge,styles:{...me==null?void 0:me.styles,...Ge==null?void 0:Ge.styles}};return{...$t.features,...e.features,...Be!==void 0?{scrollToBottom:Be}:{},...qe!==void 0?{scrollBehavior:qe}:{},...Ce!==void 0?{artifacts:Ce}:{},...Ee!==void 0?{streamAnimation:Ee}:{},...De!==void 0?{askUserQuestion:De}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:$t.suggestionChips,suggestionChipsConfig:{...$t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...$t.layout,...e.layout,header:{...(s=$t.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=$t.layout)==null?void 0:c.messages,...(d=e.layout)==null?void 0:d.messages,avatar:{...(g=(u=$t.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(p=e.layout)==null?void 0:p.messages)==null?void 0:m.avatar},timestamp:{...(C=(x=$t.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(E=(T=e.layout)==null?void 0:T.messages)==null?void 0:E.timestamp}},slots:{...(w=$t.layout)==null?void 0:w.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...$t.markdown,...e.markdown,options:{...(y=$t.markdown)==null?void 0:y.options,...(S=e.markdown)==null?void 0:S.options}},messageActions:{...$t.messageActions,...e.messageActions}}:$t}var ap={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"}},sp={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"}},ip={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:no,maxWidth:Yi,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 Ua(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."))?Ua(e,o):o}function el(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=Ua(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 lp(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 ch(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]=ch(a,n):r[o]=n}return r}function ub(e,t){return t?ch(e,t):e}function qa(e,t={}){var n,a,s,i,c,d,u,g,p,m,x,C,T;let r={palette:ap,semantic:sp,components:ip},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,...(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,...(p=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:p.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,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:ub(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=lp(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(w=>w.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function tl(e){var C,T,E,w,k,y,S,b,M,W,R,L,N,q,Y,me,Ge,Ce,Be,qe,Ee,De,le,Q,ie,ge,ue,j,de,Ne,te,Z,ae,wt,Pt,xt,Ue,be,Je,J,ce,Te,Xe,Kt,ke,Ve,rt,Ft,vr,To,Tr,je,Nt,V,Me,we,He,nt,lt,ot,Tt,z,St,se,pe,Ae,dt,er,ir,Sr,_t,et,Ot,ct,tr,io,Wr,lr,qr,Eo,vt,Gr,ko,$o,xo,yt,Nn,Lo,On,Vr,ga,cn,zo,pn,un,_n,Un,fn,At,Kr,Xr,Hr,Et,lo,co,Qr,mn,jo,gn,Jr,Ut,Br,po,hn,Go,xn,Po,Yr;let t=el(e),r={};for(let[xe,pt]of Object.entries(t)){let or=xe.replace(/\./g,"-");r[`--persona-${or}`]=pt.value}r["--persona-primary"]=(C=r["--persona-semantic-colors-primary"])!=null?C:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(T=r["--persona-semantic-colors-secondary"])!=null?T: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"]=(w=r["--persona-semantic-colors-surface"])!=null?w:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(k=r["--persona-semantic-colors-background"])!=null?k: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"]=(b=r["--persona-semantic-colors-text-muted"])!=null?b: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"]=(W=r["--persona-semantic-colors-border"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(R=r["--persona-semantic-colors-divider"])!=null?R:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(L=r["--persona-components-voice-recording-indicator"])!=null?L: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"]=(q=r["--persona-components-voice-processing-icon"])!=null?q: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"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Ge=r["--persona-components-approval-requested-border"])!=null?Ge:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(Ce=r["--persona-components-approval-requested-text"])!=null?Ce:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Be=r["--persona-components-approval-requested-shadow"])!=null?Be:"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"]=(De=r["--persona-components-attachment-image-background"])!=null?De:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(le=r["--persona-components-attachment-image-border"])!=null?le: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"]=(ie=r["--persona-semantic-typography-fontSize"])!=null?ie:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(ge=r["--persona-semantic-typography-fontWeight"])!=null?ge:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(ue=r["--persona-semantic-typography-lineHeight"])!=null?ue: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"]=(j=r["--persona-palette-radius-sm"])!=null?j:"0.125rem",r["--persona-radius-md"]=(de=r["--persona-palette-radius-md"])!=null?de:"0.375rem",r["--persona-radius-lg"]=(Ne=r["--persona-palette-radius-lg"])!=null?Ne:"0.5rem",r["--persona-radius-xl"]=(te=r["--persona-palette-radius-xl"])!=null?te:"0.75rem",r["--persona-radius-full"]=(Z=r["--persona-palette-radius-full"])!=null?Z:"9999px",r["--persona-launcher-radius"]=(wt=(ae=r["--persona-components-launcher-borderRadius"])!=null?ae:r["--persona-palette-radius-full"])!=null?wt:"9999px",r["--persona-launcher-bg"]=(Pt=r["--persona-components-launcher-background"])!=null?Pt:r["--persona-primary"],r["--persona-launcher-fg"]=(xt=r["--persona-components-launcher-foreground"])!=null?xt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(Ue=r["--persona-components-launcher-border"])!=null?Ue:r["--persona-border"],r["--persona-button-primary-bg"]=(be=r["--persona-components-button-primary-background"])!=null?be:r["--persona-primary"],r["--persona-button-primary-fg"]=(Je=r["--persona-components-button-primary-foreground"])!=null?Je:r["--persona-text-inverse"],r["--persona-button-radius"]=(ce=(J=r["--persona-components-button-primary-borderRadius"])!=null?J:r["--persona-palette-radius-full"])!=null?ce:"9999px",r["--persona-panel-radius"]=(Xe=(Te=r["--persona-components-panel-borderRadius"])!=null?Te:r["--persona-radius-xl"])!=null?Xe:"0.75rem",r["--persona-panel-border"]=(Kt=r["--persona-components-panel-border"])!=null?Kt:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Ve=(ke=r["--persona-components-panel-shadow"])!=null?ke:r["--persona-palette-shadows-xl"])!=null?Ve:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(rt=r["--persona-components-launcher-shadow"])!=null?rt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(vr=(Ft=r["--persona-components-input-borderRadius"])!=null?Ft:r["--persona-radius-lg"])!=null?vr:"0.5rem",r["--persona-message-user-radius"]=(Tr=(To=r["--persona-components-message-user-borderRadius"])!=null?To:r["--persona-radius-lg"])!=null?Tr:"0.5rem",r["--persona-message-assistant-radius"]=(Nt=(je=r["--persona-components-message-assistant-borderRadius"])!=null?je:r["--persona-radius-lg"])!=null?Nt:"0.5rem",r["--persona-header-bg"]=(V=r["--persona-components-header-background"])!=null?V:r["--persona-surface"],r["--persona-header-border"]=(Me=r["--persona-components-header-border"])!=null?Me:r["--persona-divider"],r["--persona-header-icon-bg"]=(we=r["--persona-components-header-iconBackground"])!=null?we:r["--persona-primary"],r["--persona-header-icon-fg"]=(He=r["--persona-components-header-iconForeground"])!=null?He:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(nt=r["--persona-components-header-titleForeground"])!=null?nt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(lt=r["--persona-components-header-subtitleForeground"])!=null?lt:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(ot=r["--persona-components-header-actionIconForeground"])!=null?ot:r["--persona-muted"];let o=(Tt=e.components)==null?void 0:Tt.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"]=(St=r["--persona-components-introCard-background"])!=null?St:r["--persona-surface"],r["--persona-intro-card-radius"]=(se=r["--persona-components-introCard-borderRadius"])!=null?se:"1rem",r["--persona-intro-card-padding"]=(pe=r["--persona-components-introCard-padding"])!=null?pe:"1.5rem",r["--persona-intro-card-shadow"]=(dt=(Ae=n==null?void 0:n.shadow)!=null?Ae:r["--persona-components-introCard-shadow"])!=null?dt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(er=r["--persona-components-input-background"])!=null?er:r["--persona-surface"],r["--persona-input-placeholder"]=(ir=r["--persona-components-input-placeholder"])!=null?ir:r["--persona-text-muted"],r["--persona-message-user-bg"]=(Sr=r["--persona-components-message-user-background"])!=null?Sr:r["--persona-accent"],r["--persona-message-user-text"]=(_t=r["--persona-components-message-user-text"])!=null?_t: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"]=(Ot=r["--persona-components-message-assistant-background"])!=null?Ot:r["--persona-surface"],r["--persona-message-assistant-text"]=(ct=r["--persona-components-message-assistant-text"])!=null?ct:r["--persona-text"],r["--persona-message-assistant-border"]=(tr=r["--persona-components-message-assistant-border"])!=null?tr:r["--persona-border"],r["--persona-message-assistant-shadow"]=(io=r["--persona-components-message-assistant-shadow"])!=null?io:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(lr=(Wr=r["--persona-components-scrollToBottom-background"])!=null?Wr:r["--persona-button-primary-bg"])!=null?lr:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(Eo=(qr=r["--persona-components-scrollToBottom-foreground"])!=null?qr:r["--persona-button-primary-fg"])!=null?Eo:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(vt=r["--persona-components-scrollToBottom-border"])!=null?vt:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(Gr=r["--persona-components-scrollToBottom-size"])!=null?Gr:"40px",r["--persona-scroll-to-bottom-radius"]=(xo=($o=(ko=r["--persona-components-scrollToBottom-borderRadius"])!=null?ko:r["--persona-button-radius"])!=null?$o:r["--persona-radius-full"])!=null?xo:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Nn=(yt=r["--persona-components-scrollToBottom-shadow"])!=null?yt:r["--persona-palette-shadows-sm"])!=null?Nn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Lo=r["--persona-components-scrollToBottom-padding"])!=null?Lo:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(On=r["--persona-components-scrollToBottom-gap"])!=null?On:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(ga=(Vr=r["--persona-components-scrollToBottom-fontSize"])!=null?Vr:r["--persona-palette-typography-fontSize-sm"])!=null?ga:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(cn=r["--persona-components-scrollToBottom-iconSize"])!=null?cn:"14px",r["--persona-tool-bubble-shadow"]=(zo=r["--persona-components-toolBubble-shadow"])!=null?zo:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(pn=r["--persona-components-reasoningBubble-shadow"])!=null?pn:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(un=r["--persona-components-composer-shadow"])!=null?un:"none",r["--persona-md-inline-code-bg"]=(_n=r["--persona-components-markdown-inlineCode-background"])!=null?_n:r["--persona-container"],r["--persona-md-inline-code-color"]=(Un=r["--persona-components-markdown-inlineCode-foreground"])!=null?Un:r["--persona-text"],r["--persona-md-link-color"]=(At=(fn=r["--persona-components-markdown-link-foreground"])!=null?fn:r["--persona-accent"])!=null?At:"#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 d=r["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(r["--persona-md-prose-font-family"]=d),r["--persona-md-code-block-bg"]=(Kr=r["--persona-components-markdown-codeBlock-background"])!=null?Kr:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Xr=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Xr:r["--persona-border"],r["--persona-md-code-block-text-color"]=(Hr=r["--persona-components-markdown-codeBlock-textColor"])!=null?Hr:"inherit",r["--persona-md-table-header-bg"]=(Et=r["--persona-components-markdown-table-headerBackground"])!=null?Et:r["--persona-container"],r["--persona-md-table-border-color"]=(lo=r["--persona-components-markdown-table-borderColor"])!=null?lo:r["--persona-border"],r["--persona-md-hr-color"]=(co=r["--persona-components-markdown-hr-color"])!=null?co: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"]=(mn=r["--persona-components-markdown-blockquote-background"])!=null?mn:"transparent",r["--persona-md-blockquote-text-color"]=(jo=r["--persona-components-markdown-blockquote-textColor"])!=null?jo:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(gn=r["--persona-components-collapsibleWidget-container"])!=null?gn:r["--persona-surface"],r["--cw-surface"]=(Jr=r["--persona-components-collapsibleWidget-surface"])!=null?Jr:r["--persona-surface"],r["--cw-border"]=(Ut=r["--persona-components-collapsibleWidget-border"])!=null?Ut:r["--persona-border"],r["--persona-message-border"]=(Br=r["--persona-components-message-border"])!=null?Br: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 p=u==null?void 0:u.labelButton;p&&(p.background&&(r["--persona-label-btn-bg"]=p.background),p.border&&(r["--persona-label-btn-border"]=p.border),p.color&&(r["--persona-label-btn-color"]=p.color),p.padding&&(r["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(r["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(r["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(r["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(r["--persona-label-btn-gap"]=p.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 xe=x.toolbar;xe.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,r["--persona-dropdown-bg"]=(po=r["--persona-dropdown-bg"])!=null?po:xe.copyMenuBackground),xe.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,r["--persona-dropdown-border"]=(hn=r["--persona-dropdown-border"])!=null?hn:xe.copyMenuBorder),xe.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,r["--persona-dropdown-shadow"]=(Go=r["--persona-dropdown-shadow"])!=null?Go:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(xn=r["--persona-dropdown-radius"])!=null?xn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Po=r["--persona-dropdown-item-hover-bg"])!=null?Po:xe.copyMenuItemHoverBackground),xe.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(x!=null&&x.tab){let xe=x.tab;xe.background&&(r["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(r["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(r["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(r["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(r["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(r["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(r["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(x!=null&&x.pane){let xe=x.pane;if(xe.toolbarBackground){let pt=(Yr=Ua(e,xe.toolbarBackground))!=null?Yr:xe.toolbarBackground;r["--persona-artifact-toolbar-bg"]=pt}}return r}var ph={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 fb={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"}}},uh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Rs=()=>{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"},mb=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Rs()},dp=e=>mb(e),gb=e=>qa(e),hb=e=>{var r;let t=qa(void 0,{validate:!1});return qa({...e,palette:{...t.palette,colors:{...fb.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Va=e=>{let t=dp(e),r=uh(e==null?void 0:e.theme),o=uh(e==null?void 0:e.darkTheme);return t==="dark"?hb(Is(r!=null?r:{},o!=null?o:{})):gb(r)},xb=e=>tl(e),Wn=(e,t)=>{let r=Va(t),o=xb(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},rl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Rs())});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(Rs());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 fh=(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:p=>p.getAttribute("im-preserve")==="true",shouldReAppend:p=>p.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(p,m,x={}){p=u(p);let C=g(m),T=d(p,C,x),E=n(T,()=>i(T,p,C,w=>w.morphStyle==="innerHTML"?(a(w,p,C),Array.from(p.childNodes)):o(w,p,C)));return T.pantry.remove(),E}function o(p,m,x){let C=g(m);return a(p,C,x,m,m.nextSibling),Array.from(C.childNodes)}function n(p,m){var k;if(!p.config.restoreFocus)return m();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return m();let{id:C,selectionStart:T,selectionEnd:E}=x,w=m();return C&&C!==((k=document.activeElement)==null?void 0:k.getAttribute("id"))&&(x=p.target.querySelector(`[id="${C}"]`),x==null||x.focus()),x&&!x.selectionEnd&&E&&x.setSelectionRange(T,E),w}let a=(function(){function p(y,S,b,M=null,W=null){S instanceof HTMLTemplateElement&&b instanceof HTMLTemplateElement&&(S=S.content,b=b.content),M||(M=S.firstChild);for(let R of b.childNodes){if(M&&M!=W){let N=x(y,R,M,W);if(N){N!==M&&T(y,M,N),s(N,R,y),M=N.nextSibling;continue}}if(R instanceof Element){let N=R.getAttribute("id");if(y.persistentIds.has(N)){let q=E(S,N,M,y);s(q,R,y),M=q.nextSibling;continue}}let L=m(S,R,M,y);L&&(M=L.nextSibling)}for(;M&&M!=W;){let R=M;M=M.nextSibling,C(y,R)}}function m(y,S,b,M){if(M.callbacks.beforeNodeAdded(S)===!1)return null;if(M.idMap.has(S)){let W=document.createElement(S.tagName);return y.insertBefore(W,b),s(W,S,M),M.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(S,!0);return y.insertBefore(W,b),M.callbacks.afterNodeAdded(W),W}}let x=(function(){function y(M,W,R,L){let N=null,q=W.nextSibling,Y=0,me=R;for(;me&&me!=L;){if(b(me,W)){if(S(M,me,W))return me;N===null&&(M.idMap.has(me)||(N=me))}if(N===null&&q&&b(me,q)&&(Y++,q=q.nextSibling,Y>=2&&(N=void 0)),M.activeElementAndParents.includes(me))break;me=me.nextSibling}return N||null}function S(M,W,R){let L=M.idMap.get(W),N=M.idMap.get(R);if(!N||!L)return!1;for(let q of L)if(N.has(q))return!0;return!1}function b(M,W){var N,q,Y;let R=M,L=W;return R.nodeType===L.nodeType&&R.tagName===L.tagName&&(!((N=R.getAttribute)!=null&&N.call(R,"id"))||((q=R.getAttribute)==null?void 0:q.call(R,"id"))===((Y=L.getAttribute)==null?void 0:Y.call(L,"id")))}return y})();function C(y,S){var b;if(y.idMap.has(S))k(y.pantry,S,null);else{if(y.callbacks.beforeNodeRemoved(S)===!1)return;(b=S.parentNode)==null||b.removeChild(S),y.callbacks.afterNodeRemoved(S)}}function T(y,S,b){let M=S;for(;M&&M!==b;){let W=M;M=M.nextSibling,C(y,W)}return M}function E(y,S,b,M){var R,L;let W=((L=(R=M.target).getAttribute)==null?void 0:L.call(R,"id"))===S&&M.target||M.target.querySelector(`[id="${S}"]`)||M.pantry.querySelector(`[id="${S}"]`);return w(W,M),k(y,W,b),W}function w(y,S){let b=y.getAttribute("id");for(;y=y.parentNode;){let M=S.idMap.get(y);M&&(M.delete(b),M.size||S.idMap.delete(y))}}function k(y,S,b){if(y.moveBefore)try{y.moveBefore(S,b)}catch{y.insertBefore(S,b)}else y.insertBefore(S,b)}return p})(),s=(function(){function p(w,k,y){return y.ignoreActive&&w===document.activeElement?null:(y.callbacks.beforeNodeMorphed(w,k)===!1||(w instanceof HTMLHeadElement&&y.head.ignore||(w instanceof HTMLHeadElement&&y.head.style!=="morph"?c(w,k,y):(m(w,k,y),E(w,y)||a(y,w,k))),y.callbacks.afterNodeMorphed(w,k)),w)}function m(w,k,y){let S=k.nodeType;if(S===1){let b=w,M=k,W=b.attributes,R=M.attributes;for(let L of R)T(L.name,b,"update",y)||b.getAttribute(L.name)!==L.value&&b.setAttribute(L.name,L.value);for(let L=W.length-1;0<=L;L--){let N=W[L];if(N&&!M.hasAttribute(N.name)){if(T(N.name,b,"remove",y))continue;b.removeAttribute(N.name)}}E(b,y)||x(b,M,y)}(S===8||S===3)&&w.nodeValue!==k.nodeValue&&(w.nodeValue=k.nodeValue)}function x(w,k,y){if(w instanceof HTMLInputElement&&k instanceof HTMLInputElement&&k.type!=="file"){let S=k.value,b=w.value;C(w,k,"checked",y),C(w,k,"disabled",y),k.hasAttribute("value")?b!==S&&(T("value",w,"update",y)||(w.setAttribute("value",S),w.value=S)):T("value",w,"remove",y)||(w.value="",w.removeAttribute("value"))}else if(w instanceof HTMLOptionElement&&k instanceof HTMLOptionElement)C(w,k,"selected",y);else if(w instanceof HTMLTextAreaElement&&k instanceof HTMLTextAreaElement){let S=k.value,b=w.value;if(T("value",w,"update",y))return;S!==b&&(w.value=S),w.firstChild&&w.firstChild.nodeValue!==S&&(w.firstChild.nodeValue=S)}}function C(w,k,y,S){let b=k[y],M=w[y];if(b!==M){let W=T(y,w,"update",S);W||(w[y]=k[y]),b?W||w.setAttribute(y,""):T(y,w,"remove",S)||w.removeAttribute(y)}}function T(w,k,y,S){return w==="value"&&S.ignoreActiveValue&&k===document.activeElement?!0:S.callbacks.beforeAttributeUpdated(w,k,y)===!1}function E(w,k){return!!k.ignoreActiveValue&&w===document.activeElement&&w!==document.body}return p})();function i(p,m,x,C){if(p.head.block){let T=m.querySelector("head"),E=x.querySelector("head");if(T&&E){let w=c(T,E,p);return Promise.all(w).then(()=>{let k=Object.assign(p,{head:{block:!1,ignore:!0}});return C(k)})}}return C(p)}function c(p,m,x){let C=[],T=[],E=[],w=[],k=new Map;for(let S of m.children)k.set(S.outerHTML,S);for(let S of p.children){let b=k.has(S.outerHTML),M=x.head.shouldReAppend(S),W=x.head.shouldPreserve(S);b||W?M?T.push(S):(k.delete(S.outerHTML),E.push(S)):x.head.style==="append"?M&&(T.push(S),w.push(S)):x.head.shouldRemove(S)!==!1&&T.push(S)}w.push(...k.values());let y=[];for(let S of w){let b=document.createRange().createContextualFragment(S.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(b)!==!1){if("href"in b&&b.href||"src"in b&&b.src){let M,W=new Promise(function(R){M=R});b.addEventListener("load",function(){M()}),y.push(W)}p.appendChild(b),x.callbacks.afterNodeAdded(b),C.push(b)}}for(let S of T)x.callbacks.beforeNodeRemoved(S)!==!1&&(p.removeChild(S),x.callbacks.afterNodeRemoved(S));return x.head.afterHeadMorphed(p,{added:C,kept:E,removed:T}),y}let d=(function(){function p(y,S,b){let{persistentIds:M,idMap:W}=w(y,S),R=m(b),L=R.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(L))throw`Do not understand how to morph style ${L}`;return{target:y,newContent:S,config:R,morphStyle:L,ignoreActive:R.ignoreActive,ignoreActiveValue:R.ignoreActiveValue,restoreFocus:R.restoreFocus,idMap:W,persistentIds:M,pantry:x(),activeElementAndParents:C(y),callbacks:R.callbacks,head:R.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 C(y){let S=[],b=document.activeElement;if((b==null?void 0:b.tagName)!=="BODY"&&y.contains(b))for(;b&&(S.push(b),b!==y);)b=b.parentElement;return S}function T(y){var b;let S=Array.from(y.querySelectorAll("[id]"));return(b=y.getAttribute)!=null&&b.call(y,"id")&&S.push(y),S}function E(y,S,b,M){for(let W of M){let R=W.getAttribute("id");if(S.has(R)){let L=W;for(;L;){let N=y.get(L);if(N==null&&(N=new Set,y.set(L,N)),N.add(R),L===b)break;L=L.parentElement}}}}function w(y,S){let b=T(y),M=T(S),W=k(b,M),R=new Map;E(R,W,y,b);let L=S.__idiomorphRoot||S;return E(R,W,L,M),{persistentIds:W,idMap:R}}function k(y,S){let b=new Set,M=new Map;for(let{id:R,tagName:L}of y)M.has(R)?b.add(R):M.set(R,L);let W=new Set;for(let{id:R,tagName:L}of S)W.has(R)?b.add(R):M.get(R)===L&&W.add(R);for(let R of b)W.delete(R);return W}return p})(),{normalizeElement:u,normalizeParent:g}=(function(){let p=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(T(E));if(p.has(E))return E;if(E instanceof Node){if(E.parentNode)return new C(E);{let w=document.createElement("div");return w.append(E),w}}else{let w=document.createElement("div");for(let k of[...E])w.append(k);return w}}class C{constructor(w){this.originalNode=w,this.realParentNode=w.parentNode,this.previousSibling=w.previousSibling,this.nextSibling=w.nextSibling}get childNodes(){let w=[],k=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;k&&k!=this.nextSibling;)w.push(k),k=k.nextSibling;return w}querySelectorAll(w){return this.childNodes.reduce((k,y)=>{if(y instanceof Element){y.matches(w)&&k.push(y);let S=y.querySelectorAll(w);for(let b=0;b<S.length;b++)k.push(S[b])}return k},[])}insertBefore(w,k){return this.realParentNode.insertBefore(w,k)}moveBefore(w,k){return this.realParentNode.moveBefore(w,k)}get __idiomorphRoot(){return this.originalNode}}function T(E){let w=new DOMParser,k=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(k.match(/<\/html>/)||k.match(/<\/head>/)||k.match(/<\/body>/)){let y=w.parseFromString(E,"text/html");if(k.match(/<\/html>/))return p.add(y),y;{let S=y.firstChild;return S&&p.add(S),S}}else{let S=w.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return p.add(S),S}}return{normalizeElement:m,normalizeParent:x}})();return{morph:r,defaults:t}})();var ol=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;fh.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:"",d=(i=a.textContent)!=null?i:"";if(c!==d)return}return!1}}}}})};var nl={index:-1,draft:""};function mh(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:{...nl}}}function gh(e,t){var r,o,n,a,s,i,c,d,u,g,p,m,x,C,T,E,w,k,y,S,b,M,W,R,L,N,q,Y,me,Ge,Ce,Be,qe,Ee,De,le,Q,ie;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,(u=(d=e.llmContent)==null?void 0:d.length)!=null?u:0,(p=(g=e.approval)==null?void 0:g.status)!=null?p:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(T=(C=e.toolCall)==null?void 0:C.name)!=null?T:"",(k=(w=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:w.length)!=null?k:0,(M=(b=(S=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:S[e.toolCall.chunks.length-1])==null?void 0:b.slice(-32))!=null?M:"",typeof((W=e.toolCall)==null?void 0:W.args)=="string"?e.toolCall.args.length:(R=e.toolCall)!=null&&R.args?JSON.stringify(e.toolCall.args).length:0,(q=(N=(L=e.reasoning)==null?void 0:L.chunks)==null?void 0:N.length)!=null?q:0,(Ce=(Ge=(me=(Y=e.reasoning)==null?void 0:Y.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:Ge.length)!=null?Ce:0,(De=(Ee=(qe=(Be=e.reasoning)==null?void 0:Be.chunks)==null?void 0:qe[e.reasoning.chunks.length-1])==null?void 0:Ee.slice(-32))!=null?De:"",(Q=(le=e.contentParts)==null?void 0:le.length)!=null?Q:0,(ie=e.stopReason)!=null?ie:"",t].join("\0")}function hh(){return new Map}function xh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function yh(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function bh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function al(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function sn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function da(e,t){return sn(e)-e.scrollTop<=t}function sl(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!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&&c&&!n?{action:"pause",delta:u,nextLastScrollTop:r}:{action:"none",delta:u,nextLastScrollTop:r}}function il(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 vh(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Ch(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 wh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ir={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Rr=1e5,Hn=Rr+1;var Ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},yb=["pre","code","a","script","style"],ll=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:Ws.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Ws.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ws.speed,duration:(n=e==null?void 0:e.duration)!=null?n:Ws.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:Ws.buffer}},Ah=[{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"}],Hs=new Map;for(let e of Ah)Hs.set(e.name,e);var ca=e=>{Hs.set(e.name,e)},up=e=>{Ah.some(t=>t.name===e)||Hs.delete(e)},fp=()=>Array.from(Hs.keys()),Bs=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Hs.get(e))!=null?o:null},dl=(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},bb=(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},vb=(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},cp=/\s/,Cb=(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},wb=(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(cp.test(a[i])){let d=i;for(;d<a.length&&cp.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&&!cp.test(a[u]);)d.appendChild(bb(o,a[u],t,r.value)),r.value+=1,u+=1;s.appendChild(d),i=u}n.replaceChild(s,e)},Sb=(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 d of i)d&&(/^\s+$/.test(d)?s.appendChild(o.createTextNode(d)):(s.appendChild(vb(o,d,t,r.value)),r.value+=1));n.replaceChild(s,e)},Ds=(e,t,r,o)=>{var g,p;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:yb).map(m=>m.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)Cb(c,a)||i.push(c),c=s.nextNode();let d={value:(p=o==null?void 0:o.startIndex)!=null?p:0},u=t==="char"?wb:Sb;for(let m of i)u(m,r,d);return n.innerHTML},cl=(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},Fs=(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},Sh=new WeakMap,Ab=(e,t)=>{var a;if(!e.styles)return;let r=Sh.get(t);if(r||(r=new Set,Sh.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)},pp=new WeakMap,Mb=(e,t)=>{if(!e.onAttach)return;let r=pp.get(t);if(r||(r=new Map,pp.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},Mh=e=>{let t=pp.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},mp=(e,t)=>{Ab(e,t),Mb(e,t)};function gp(e,t=Rr){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 Ns=0,Bn=null;function hp(e=document){var r;if(Ns++,Ns===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Bn={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,Ns=Math.max(0,Ns-1),Ns===0&&Bn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Bn.originalOverflow,n.style.position=Bn.originalPosition,n.style.top=Bn.originalTop,n.style.width=Bn.originalWidth,a.scrollTo(0,Bn.scrollY),Bn=null}}}var Os={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},ur=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Dn=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},ao=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:Os.side,width:(n=t==null?void 0:t.width)!=null?n:Os.width,animate:(a=t==null?void 0:t.animate)!=null?a:Os.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:Os.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Os.maxHeight}};var Mo={"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 Tb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",pl=(e,t={})=>{var T,E,w,k,y,S;let{showClose:r=!0,wrapperClassName:o=Tb,buttonSize:n,iconSize:a="28px"}=t,s=(T=e==null?void 0:e.launcher)!=null?T:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=A("div",o),d=(w=s.closeButtonTooltipText)!=null?w:"Close chat",u=(k=s.closeButtonShowTooltip)!=null?k:!0,g=(y=s.closeButtonIconName)!=null?y:"x",p=(S=s.closeButtonIconText)!=null?S:"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=Lt("button",{className:bs("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||Ur.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=ve(g,a,"currentColor",1);if(C?(C.style.display="block",x.appendChild(C)):x.textContent=p,c.appendChild(x),u&&d){let b=null,M=()=>{if(b)return;let R=x.ownerDocument,L=R.body;if(!L)return;b=qo(R,"div","persona-clear-chat-tooltip"),b.textContent=d;let N=qo(R,"div");N.className="persona-clear-chat-tooltip-arrow",b.appendChild(N);let q=x.getBoundingClientRect();b.style.position="fixed",b.style.zIndex=String(Hn),b.style.left=`${q.left+q.width/2}px`,b.style.top=`${q.top-8}px`,b.style.transform="translate(-50%, -100%)",L.appendChild(b)},W=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};c.addEventListener("mouseenter",M),c.addEventListener("mouseleave",W),x.addEventListener("focus",M),x.addEventListener("blur",W),c._cleanupTooltip=()=>{W(),c.removeEventListener("mouseenter",M),c.removeEventListener("mouseleave",W),x.removeEventListener("focus",M),x.removeEventListener("blur",W)}}return{button:x,wrapper:c}},Eb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ul=(e,t={})=>{var b,M,W,R,L,N,q,Y,me,Ge,Ce,Be,qe;let{wrapperClassName:r=Eb,buttonSize:o,iconSize:n="20px"}=t,s=(M=((b=e==null?void 0:e.launcher)!=null?b:{}).clearChat)!=null?M:{},i=(W=o!=null?o:s.size)!=null?W:"32px",c=(R=s.iconName)!=null?R:"refresh-cw",d=(L=s.iconColor)!=null?L:"",u=(N=s.backgroundColor)!=null?N:"",g=(q=s.borderWidth)!=null?q:"",p=(Y=s.borderColor)!=null?Y:"",m=(me=s.borderRadius)!=null?me:"",x=(Ge=s.paddingX)!=null?Ge:"",C=(Ce=s.paddingY)!=null?Ce:"",T=(Be=s.tooltipText)!=null?Be:"Clear chat",E=(qe=s.showTooltip)!=null?qe:!0,w=A("div",r),k=!!(g||p),y=Lt("button",{className:bs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:d||Ur.actionIconColor,backgroundColor:u||void 0,border:k?`${g||"0px"} solid ${p||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),S=ve(c,n,"currentColor",1);if(S&&(S.style.display="block",y.appendChild(S)),w.appendChild(y),E&&T){let Ee=null,De=()=>{if(Ee)return;let Q=y.ownerDocument,ie=Q.body;if(!ie)return;Ee=qo(Q,"div","persona-clear-chat-tooltip"),Ee.textContent=T;let ge=qo(Q,"div");ge.className="persona-clear-chat-tooltip-arrow",Ee.appendChild(ge);let ue=y.getBoundingClientRect();Ee.style.position="fixed",Ee.style.zIndex=String(Hn),Ee.style.left=`${ue.left+ue.width/2}px`,Ee.style.top=`${ue.top-8}px`,Ee.style.transform="translate(-50%, -100%)",ie.appendChild(Ee)},le=()=>{Ee&&Ee.parentNode&&(Ee.parentNode.removeChild(Ee),Ee=null)};w.addEventListener("mouseenter",De),w.addEventListener("mouseleave",le),y.addEventListener("focus",De),y.addEventListener("blur",le),w._cleanupTooltip=()=>{le(),w.removeEventListener("mouseenter",De),w.removeEventListener("mouseleave",le),y.removeEventListener("focus",De),y.removeEventListener("blur",le)}}return{button:y,wrapper:w}};var Ur={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))"},ln=e=>{var S,b,M,W,R,L,N,q,Y,me,Ge,Ce,Be,qe,Ee,De;let{config:t,showClose:r=!0}=e,o=Lt("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=(b=n.headerIconSize)!=null?b:"48px",s=(M=n.closeButtonPlacement)!=null?M:"inline",i=(W=n.headerIconHidden)!=null?W:!1,c=n.headerIconName,d=Lt("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 le=parseFloat(a)||24,Q=ve(c,le*.6,"currentColor",1);Q?d.replaceChildren(Q):d.textContent=(L=(R=t==null?void 0:t.launcher)==null?void 0:R.agentIconText)!=null?L:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let le=A("img");le.src=t.launcher.iconUrl,le.alt="",le.className="persona-rounded-xl persona-object-cover",le.style.height=a,le.style.width=a,d.replaceChildren(le)}else d.textContent=(Y=(q=t==null?void 0:t.launcher)==null?void 0:q.agentIconText)!=null?Y:"\u{1F4AC}";let u=A("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Lt("span",{className:"persona-text-base persona-font-semibold",text:(Ge=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?Ge:"Chat Assistant",style:{color:Ur.titleColor}}),p=Lt("span",{className:"persona-text-xs",text:(Be=(Ce=t==null?void 0:t.launcher)==null?void 0:Ce.subtitle)!=null?Be:"Here to help you get answers fast",style:{color:Ur.subtitleColor}});u.append(g,p),i?o.append(u):o.append(d,u);let m=(qe=n.clearChat)!=null?qe:{},x=(Ee=m.enabled)!=null?Ee:!0,C=(De=m.placement)!=null?De:"inline",T=null,E=null;if(x){let Q=ul(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=Q.button,E=Q.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let w=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:k,wrapper:y}=pl(t,{showClose:r,wrapperClassName:w});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:d,headerTitle:g,headerSubtitle:p,closeButton:k,closeButtonWrapper:y,clearChatButton:T,clearChatButtonWrapper:E}},pa=(e,t,r)=>{var s,i,c,d;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(d=(c=o.clearChat)==null?void 0:c.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 Fn(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=A("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(Hn)):(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 T=document.createElement("hr");s.appendChild(T)}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 T=ve(m.icon,16,"currentColor",1.5);T&&x.appendChild(T)}let C=document.createElement("span");C.textContent=m.label,x.appendChild(C),x.addEventListener("click",T=>{T.stopPropagation(),u(),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 d(){c(),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 p(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:u,toggle:g,destroy:p}}function br(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=A("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let d=ve(t,o!=null?o:16,"currentColor",n!=null?n:2);if(d&&c.appendChild(d),s&&c.addEventListener("click",s),i)for(let[u,g]of Object.entries(i))c.setAttribute(u,g);return c}function _s(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let u=A("button",d);if(u.type="button",u.setAttribute("aria-label",r),t){let p=ve(t,a!=null?a:14,"currentColor",2);p&&u.appendChild(p)}let g=A("span");if(g.textContent=r,u.appendChild(g),i&&u.addEventListener("click",i),c)for(let[p,m]of Object.entries(c))u.setAttribute(p,m);return u}function Th(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=A("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){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=br({icon:u.icon,label:u.label,onClick:()=>{s=u.id,c(),o(u.id)}}):(g=A("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,c(),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,c()}return{element:a,setSelected:d}}function fl(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,d=A("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=A("span","persona-combo-btn-label");u.textContent=t,d.appendChild(u);let g=ve(r,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",d.appendChild(g)),c&&(d.style.borderRadius=(m=c.borderRadius)!=null?m:"10px",d.style.padding=(x=c.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,T;d.style.backgroundColor=(C=c.background)!=null?C:"",d.style.borderColor=(T=c.border)!=null?T:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let p=Fn({items:o,onSelect:C=>{d.setAttribute("aria-expanded","false"),n(C)},anchor:d,position:a,portal:s});return s||d.appendChild(p.element),d.addEventListener("click",C=>{C.stopPropagation();let T=!p.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",T?"false":"true"),p.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"),p.show()},close:()=>{d.setAttribute("aria-expanded","false"),p.hide()},toggle:()=>{let C=!p.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",C?"false":"true"),p.toggle()},destroy:()=>{p.destroy(),d.remove()}}}var xp=e=>{var o;let t=ln({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 kb(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=A("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=ve(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=A("div","persona-relative");c.appendChild(i);let d=Fn({items:s.menuItems,onSelect:u=>r==null?void 0:r(u),anchor:c,position:"bottom-left"});c.appendChild(d.element),i.addEventListener("click",u=>{u.stopPropagation(),d.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var yp=e=>{var w,k,y,S,b,M,W,R,L;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(w=t==null?void 0:t.launcher)!=null?w:{},i=A("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,d,u;if(c)d=fl({label:(k=s.title)!=null?k:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,d.style.color=Ur.titleColor,u=(y=d.querySelector(".persona-combo-btn-label"))!=null?y:d;else{if(d=A("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=A("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Ur.titleColor,u.textContent=(S=s.title)!=null?S:"Chat Assistant",d.appendChild(u),kb(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 q=n.onTitleClick;d.addEventListener("click",Y=>{Y.target.closest("button")||q()}),d.addEventListener("keydown",Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),q())})}let N=n==null?void 0:n.titleRowHover;N&&(d.style.borderRadius=(M=N.borderRadius)!=null?M:"10px",d.style.padding=(W=N.padding)!=null?W:"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 q,Y;d.style.backgroundColor=(q=N.background)!=null?q:"",d.style.borderColor=(Y=N.border)!=null?Y:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let g=(R=s.closeButtonSize)!=null?R:"32px",p=A("div",""),m=A("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||Ur.actionIconColor;let x=(L=s.closeButtonIconName)!=null?L:"x",C=ve(x,"28px","currentColor",1);C?m.appendChild(C):m.textContent="\xD7",o&&m.addEventListener("click",o),p.appendChild(m),i.appendChild(p);let T=A("div");T.style.display="none";let E=A("span");return E.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:E,closeButton:m,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},ml={default:xp,minimal:yp},bp=e=>{var t;return(t=ml[e])!=null?t:ml.default},$a=(e,t,r)=>{var s,i,c;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=A("div");u.style.display="none";let g=A("span"),p=A("span"),m=A("button");m.style.display="none";let x=A("div");return x.style.display="none",{header:d,iconHolder:u,headerTitle:g,headerSubtitle:p,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=bp(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 gl=e=>{var s,i;let t=A("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}},hl=e=>{var S,b,M,W,R,L,N,q,Y,me,Ge,Ce;let t=(S=e==null?void 0:e.sendButton)!=null?S:{},r=(b=t.useIcon)!=null?b:!1,o=(M=t.iconText)!=null?M:"\u2191",n=t.iconName,a=(W=t.stopIconName)!=null?W:"square",s=(R=t.tooltipText)!=null?R:"Send message",i=(L=t.stopTooltipText)!=null?L:"Stop generating",c=(q=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?q:"Send",d=(me=(Y=e==null?void 0:e.copy)==null?void 0:Y.stopButtonLabel)!=null?me:"Stop",u=(Ge=t.showTooltip)!=null?Ge:!1,g=(Ce=t.size)!=null?Ce:"40px",p=t.backgroundColor,m=t.textColor,x=A("div","persona-send-button-wrapper"),C=Lt("button",{className:bs("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&&!p&&"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&&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}}),T=null,E=null;if(r){let Be=parseFloat(g)||24,qe=(m==null?void 0:m.trim())||"currentColor";n?(T=ve(n,Be,qe,2),T?C.appendChild(T):C.textContent=o):C.textContent=o,E=ve(a,Be,qe,2)}else C.textContent=c;let w=null;u&&s&&(w=A("div","persona-send-button-tooltip"),w.textContent=s,x.appendChild(w)),C.setAttribute("aria-label",s),x.appendChild(C);let k="send";return{button:C,wrapper:x,setMode:Be=>{if(Be===k)return;k=Be;let qe=Be==="stop"?i:s;if(C.setAttribute("aria-label",qe),w&&(w.textContent=qe),r){if(T&&E){let Ee=Be==="stop"?E:T;C.replaceChildren(Ee)}}else C.textContent=Be==="stop"?d:c}}},xl=e=>{var w,k,y,S,b,M,W,R,L,N,q,Y;let t=(w=e==null?void 0:e.voiceRecognition)!=null?w:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((k=t.provider)==null?void 0:k.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=(b=t.iconName)!=null?b:"mic",c=(M=t.iconSize)!=null?M:s,d=parseFloat(c)||24,u=(R=t.backgroundColor)!=null?R:(W=e==null?void 0:e.sendButton)==null?void 0:W.backgroundColor,g=(N=t.iconColor)!=null?N:(L=e==null?void 0:e.sendButton)==null?void 0:L.textColor,p=A("div","persona-send-button-wrapper"),m=Lt("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: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=ve(i,d,g||"currentColor",1.5);C?m.appendChild(C):m.textContent="\u{1F3A4}",p.appendChild(m);let T=(q=t.tooltipText)!=null?q:"Start voice recognition";if(((Y=t.showTooltip)!=null?Y:!1)&&T){let me=A("div","persona-send-button-tooltip");me.textContent=T,p.appendChild(me)}return{button:m,wrapper:p}},yl=e=>{var x,C,T,E,w,k,y,S;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(T=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?T:"40px",o=A("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=A("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:an).join(","),n.multiple=((w=t.maxFiles)!=null?w:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(k=t.buttonIconName)!=null?k:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),d=A("div","persona-send-button-wrapper"),u=Lt("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=ve(a,c,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",b=>{b.preventDefault(),n.click()}),d.appendChild(u);let p=(S=t.buttonTooltipText)!=null?S:"Attach file",m=A("div","persona-send-button-tooltip");return m.textContent=p,d.appendChild(m),{button:u,wrapper:d,input:n,previewsContainer:o}},bl=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=A("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 d=A("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},vl=()=>Lt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var za=e=>{var x,C,T,E,w,k;let{config:t}=e,r=Lt("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=vl(),n=Lt("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}=gl(t);s();let i=hl(t),c=xl(t),d=yl(t),u=bl(t);d&&(d.previewsContainer.style.gap="8px",n.append(d.previewsContainer,d.input)),n.append(a);let g=Lt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),p=A("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=A("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&p.append(d.wrapper),c&&m.append(c.wrapper),m.append(i.wrapper),g.append(p,m),n.append(g),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!==(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=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,statusText:u,attachmentButton:(T=d==null?void 0:d.button)!=null?T:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(w=d==null?void 0:d.input)!=null?w:null,attachmentPreviewsContainer:(k=d==null?void 0:d.previewsContainer)!=null?k:null,actionsRow:g,leftActions:p,rightActions:m,setSendButtonMode:i.setMode}};var Eh=()=>{let e=Lt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=A("span","persona-pill-peek__icon"),r=ve("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=A("span","persona-pill-peek__text"),n=A("span","persona-pill-peek__caret"),a=ve("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},kh=e=>{var x,C,T,E,w,k;let{config:t}=e,r=Lt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=vl();o.style.display="none";let n=bl(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=gl(t);a.style.maxHeight="100px",s();let i=hl(t),c=xl(t),d=yl(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let u=Lt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=A("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&g.append(d.wrapper);let p=A("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&p.append(c.wrapper),p.append(i.wrapper),u.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!==(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,p),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=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,statusText:n,attachmentButton:(T=d==null?void 0:d.button)!=null?T:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(w=d==null?void 0:d.input)!=null?w:null,attachmentPreviewsContainer:(k=d==null?void 0:d.previewsContainer)!=null?k:null,actionsRow:m,leftActions:g,rightActions:p,setSendButtonMode:i.setMode}};var Lh=e=>{var u,g,p,m,x,C,T,E,w,k,y,S,b,M,W,R,L;let t=(g=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?g:!0,r=ur(e);if(Dn(e)){let N=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.composerBar)!=null?m:{},q=A("div","persona-widget-wrapper persona-fixed persona-transition");q.setAttribute("data-persona-composer-bar",""),q.dataset.state="collapsed",q.dataset.expandedSize=(x=N.expandedSize)!=null?x:"anchored",q.style.zIndex=String((T=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?T:Rr);let Y=A("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Y.style.width="100%",q.appendChild(Y);let me=A("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=N.expandedSize)!=null?E:"anchored",me.style.zIndex=String((k=(w=e==null?void 0:e.launcher)==null?void 0:w.zIndex)!=null?k:Rr),{wrapper:q,panel:Y,pillRoot:me}}if(r){let N=A("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),q=A("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(q),{wrapper:N,panel:q}}if(!t){let N=A("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),q=A("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Y=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?S:"100%";return N.style.width=Y,q.style.width="100%",N.appendChild(q),{wrapper:N,panel:q}}let n=(b=e==null?void 0:e.launcher)!=null?b:{},a=n.position&&Mo[n.position]?Mo[n.position]:Mo["bottom-right"],s=A("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((W=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?W:Rr);let i=A("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(L=(R=e==null?void 0:e.launcher)==null?void 0:R.width)!=null?L:e==null?void 0:e.launcherWidth,d=c!=null?c:no;return i.style.width=d,i.style.maxWidth=d,s.appendChild(i),{wrapper:s,panel:i}},Lb=(e,t)=>{var y,S,b,M,W,R,L,N,q;let r=A("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}=pl(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=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:S.enabled)!=null?b:!0,s=null,i=null;if(a){let Y=ul(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 c=Lt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Lt("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=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(W=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?W:"Hello \u{1F44B}"}),g=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(L=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeSubtitle)!=null?L:"Ask anything about your account or products."}),p=Lt("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=A("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%"),((q=e==null?void 0:e.copy)==null?void 0:q.showWelcomeCard)!==!1||(p.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(p,m);let T=Lt("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=kh({config:e}),{root:w,textNode:k}=Eh();return r.append(c,n,d,T),i&&r.appendChild(i),{container:r,body:d,messagesWrapper:m,composerOverlay:T,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:u,introSubtitle:g,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:A("span"),headerTitle:A("span"),headerSubtitle:A("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:w,peekTextNode:k}},Ph=(e,t=!0)=>{var T,E,w,k,y,S,b,M,W;if(Dn(e))return Lb(e,t);let r=Lt("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=(T=e==null?void 0:e.layout)==null?void 0:T.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?$a(e,o,{showClose:t}):ln({config:e,showClose:t}),s=Lt("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=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),c=Lt("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."}),d=Lt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:ur(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),u=A("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%"),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,u);let m=za({config:e}),x=((W=e==null?void 0:e.layout)==null?void 0:W.showFooter)!==!1;n?pa(r,a,e):(a.header.style.display="none",pa(r,a,e)),r.append(s);let C=Lt("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: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 vp=(e,t)=>{let r=A("button");r.type="button",r.innerHTML=`
19
19
  <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
20
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
21
21
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -23,14 +23,14 @@ _Details: ${r.message}_`:o}var Rs=e=>({isError:!0,content:[{type:"text",text:e}]
23
23
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
24
24
  </span>
25
25
  <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 P,y,w,b,A,H,W,k,N,q,Z,me,Ke;let s=(P=a.launcher)!=null?P:{},i=pr(a),c=r.querySelector("[data-role='launcher-title']");if(c){let Ce=(y=s.title)!=null?y:"Chat Assistant";c.textContent=Ce,c.setAttribute("title",Ce)}let d=r.querySelector("[data-role='launcher-subtitle']");if(d){let Ce=(w=s.subtitle)!=null?w:"Here to help you get answers fast";d.textContent=Ce,d.setAttribute("title",Ce)}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 Ce=(b=s.agentIconSize)!=null?b:"40px";if(g.style.height=Ce,g.style.width=Ce,g.innerHTML="",s.agentIconName){let Ie=parseFloat(Ce)||24,Ue=ve(s.agentIconName,Ie*.6,"var(--persona-text-inverse, #ffffff)",2);Ue?(g.appendChild(Ue),g.style.display=""):(g.textContent=(A=s.agentIconText)!=null?A:"\u{1F4AC}",g.style.display="")}else s.iconUrl?g.style.display="none":(g.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}",g.style.display="")}let p=r.querySelector("[data-role='launcher-image']");if(p){let Ce=(W=s.agentIconSize)!=null?W:"40px";p.style.height=Ce,p.style.width=Ce,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(p.src=s.iconUrl,p.style.display="block"):p.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ce=(k=s.callToActionIconSize)!=null?k:"32px";m.style.height=Ce,m.style.width=Ce,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 Ue=parseFloat(Ce)||24,Te=Math.max(Ue-Ie,8),We=ve(s.callToActionIconName,Te,"currentColor",2);We?m.appendChild(We):m.textContent=(N=s.callToActionIconText)!=null?N:"\u2197"}else m.textContent=(q=s.callToActionIconText)!=null?q:"\u2197"}let x=s.position&&To[s.position]?To[s.position]:To["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",T="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?T:`${C} ${x}`,i||(r.style.zIndex=String((Z=s.zIndex)!=null?Z:Lr));let E="1px solid var(--persona-border, #e5e7eb)",M="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:M,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=(Ke=s.collapsedMaxWidth)!=null?Ke:"",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 kh=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=Th(e),a=Eh(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},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:c,composer:d,replaceHeader:p=>(c.element.replaceWith(p.header),c.element=p.header,c.iconHolder=p.iconHolder,c.headerTitle=p.headerTitle,c.headerSubtitle=p.headerSubtitle,c.closeButton=p.closeButton,c.closeButtonWrapper=p.closeButtonWrapper,c.clearChatButton=p.clearChatButton,c.clearChatButtonWrapper=p.clearChatButtonWrapper,p),replaceComposer:p=>{d.footer.replaceWith(p),d.footer=p}}},bp=({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:()=>yp(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=yp(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(":"))},vp=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(":"))},Cp=320,Ph=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,c)=>{var g;let d=S("img");d.alt=((g=i.alt)==null?void 0:g.trim())||`Attached image ${c+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Cp}px`,d.style.maxHeight=`${Ph}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(!vp(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=`${Cp}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(!vp(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=`${Cp}px`,n.style.maxHeight=`${Ph}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(!vp(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}},ua=()=>{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},wp=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:ua};if(t){let n=t(o);if(n!==null)return n}return ua()},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},Lh=(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},Sp=(e,t,r)=>{var x,C,T,E,M,P,y;let o=(x=t.showCopy)!=null?x:!0,n=(C=t.showUpvote)!=null?C:!0,a=(T=t.showDownvote)!=null?T:!0,s=(E=t.showReadAloud)!=null?E:!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=(M=t.visibility)!=null?M:"hover",c=(P=t.align)!=null?P:"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"}[c],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=S("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${g} ${i==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=(w,b,A)=>{let H=yr({icon:w,label:b,size:14,className:"persona-message-action-btn"});return H.setAttribute("data-action",A),H};return o&&p.appendChild(m("copy","Copy message","copy")),s&&p.appendChild(m("volume-2","Read aloud","read-aloud")),n&&p.appendChild(m("thumbs-up","Upvote","upvote")),a&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},Ga=(e,t,r,o,n,a)=>{var de,J,le,ge,ue,G,ce,Be,ne,ee,ie,vt,Lt,gt,_e,be,Ze;let s=r!=null?r:{},i=(de=s.layout)!=null?de:"bubble",c=s.avatar,d=s.timestamp,u=(J=c==null?void 0:c.show)!=null?J:!1,g=(le=d==null?void 0:d.show)!=null?le:!1,p=(ge=c==null?void 0:c.position)!=null?ge:"left",m=(ue=d==null?void 0:d.position)!=null?ue:"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 T=Rb(e),E=(ce=(G=e.content)==null?void 0:G.trim())!=null?ce:"",P=T.length>0&&E===Bi,y=sl((ne=(Be=a==null?void 0:a.widgetConfig)==null?void 0:Be.features)==null?void 0:ne.streamAnimation),w=(vt=(ie=(ee=a==null?void 0:a.widgetConfig)==null?void 0:ee.features)==null?void 0:ie.streamAnimation)==null?void 0:vt.plugins,b=e.role==="assistant"&&y.type!=="none"?Ds(y.type,w):null,A=e.role==="assistant"&&((Lt=b==null?void 0:b.isAnimating)==null?void 0:Lt.call(b,e))===!0,H=e.role==="assistant"&&b!==null&&(!!e.streaming||A);H&&(b!=null&&b.bubbleClass)&&C.classList.add(b.bubbleClass);let W=document.createElement("div");W.classList.add("persona-message-content"),H&&b&&(b.containerClass&&W.classList.add(b.containerClass),W.style.setProperty("--persona-stream-step",`${y.speed}ms`),W.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let k=H?il((gt=e.content)!=null?gt:"",y.buffer,b,e,!!e.streaming):(_e=e.content)!=null?_e:"",N=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),q=N;H&&(b==null?void 0:b.wrap)==="char"?q=Fs(N,"char",e.id,{skipTags:b.skipTags}):H&&(b==null?void 0:b.wrap)==="word"&&(q=Fs(N,"word",e.id,{skipTags:b.skipTags}));let Z=null;if(P?(Z=document.createElement("div"),Z.innerHTML=q,Z.style.display="none",W.appendChild(Z)):W.innerHTML=q,H&&(b!=null&&b.useCaret)&&!P&&E){let Y=ll(),pe=W.querySelectorAll(".persona-stream-char, .persona-stream-word"),Me=pe[pe.length-1];if(Me!=null&&Me.parentNode)Me.parentNode.insertBefore(Y,Me.nextSibling);else{let Je=W.lastElementChild;Je?Je.appendChild(Y):W.appendChild(Y)}}if(g&&m==="inline"&&e.createdAt){let Y=Lh(e,d,"span");Y.classList.add("persona-timestamp-inline");let pe=W.lastElementChild;pe?pe.appendChild(Y):W.appendChild(Y)}if(T.length>0){let Y=Bb(T,!P&&!!E,()=>{P&&Z&&(Z.style.display="")});Y?C.appendChild(Y):P&&Z&&(Z.style.display="")}let me=Ib(e);if(me.length>0){let Y=Db(me);Y&&C.appendChild(Y)}let Ke=Wb(e);if(Ke.length>0){let Y=Fb(Ke);Y&&C.appendChild(Y)}let Ce=Hb(e);if(Ce.length>0){let Y=Nb(Ce);Y&&C.appendChild(Y)}if(C.appendChild(W),g&&m==="below"&&e.createdAt){let Y=Lh(e,d);Y.classList.add("persona-mt-1"),C.appendChild(Y)}let Ie=e.role==="assistant"?kb(e.stopReason,(Ze=(be=a==null?void 0:a.widgetConfig)==null?void 0:be.copy)==null?void 0:Ze.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(k&&k.trim()),pe=y.placeholder==="skeleton",Me=pe&&y.buffer==="line"&&Y;if(Y)Me&&C.appendChild(Ns());else if(pe)C.appendChild(Ns());else{let Je=wp("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Je&&C.appendChild(Je)}}if(Ie&&e.stopReason&&!e.streaming&&(E||(W.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 Y=Sp(e,o,n);C.appendChild(Y)}if(!u||e.role==="system")return C;let Te=S("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),We=Ob(c,e.role);return p==="right"||p==="left"&&e.role==="user"?Te.append(C,We):Te.append(We,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Te},Rh=(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}):Ga(e,t,r,o,n,a)};var Ka=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
- `):""},Ih=(e,t)=>{let r=Ka.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=ve(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")},Ap=(e,t)=>{var Ke,Ce,Ie,Ue,Te,We,de,J,le,ge,ue;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=(Ce=(Ke=t==null?void 0:t.features)==null?void 0:Ke.reasoningDisplay)!=null?Ce:{},a=n.expandable!==!1,s=a&&Ka.has(e.id),i=r.status!=="complete",c=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"),p="Thinking...",m=(Ue=t==null?void 0:t.reasoning)!=null?Ue:{},x=String((Te=r.startedAt)!=null?Te:Date.now()),C=()=>{let G=S("span","");return G.setAttribute("data-tool-elapsed",x),G.textContent=Ei(r),G},T=(We=m.renderCollapsedSummary)==null?void 0:We.call(m,{message:e,reasoning:r,defaultSummary:p,previewText:c,isActive:i,config:t!=null?t:{},elapsed:Ei(r),createElapsedElement:C});typeof T=="string"&&T.trim()?(g.textContent=T,u.appendChild(g)):T instanceof HTMLElement?u.appendChild(T):(g.textContent=p,u.appendChild(g));let E=S("span","persona-text-xs persona-text-persona-primary");E.textContent=Dg(r),u.appendChild(E);let M=(de=n.loadingAnimation)!=null?de:"none",P=m.activeTextTemplate,y=m.completeTextTemplate,w=i?P:y,b=T instanceof HTMLElement,A=(G,ce,Be)=>{let ne=Be;for(let ee of ce){let ie=S("span","persona-tool-char");ie.style.setProperty("--char-index",String(ne)),ie.textContent=ee===" "?"\xA0":ee,G.appendChild(ie),ne++}return ne},H=(G,ce)=>{g.textContent="";let Be=ki(G,""),ne=0;for(let ee of Be){let ie=ee.styles.length>0?(()=>{let vt=S("span",ee.styles.map(Lt=>`persona-tool-text-${Lt}`).join(" "));return g.appendChild(vt),vt})():g;if(ee.isDuration&&i)ie.appendChild(C());else{let vt=ee.isDuration?Ei(r):ee.text;ce?ne=A(ie,vt,ne):ie.appendChild(document.createTextNode(vt))}}};if(!b&&w)if(E.style.display="none",g.style.display="",i&&M!=="none"){let G=(J=m.loadingAnimationDuration)!=null?J:2e3;g.setAttribute("data-preserve-animation","true"),M==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),H(w,!1)):(g.classList.add(`persona-tool-loading-${M}`),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),M==="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)),H(w,!0))}else H(w,!1);else if(!b&&i&&M!=="none"){g.style.display="";let G=(le=m.loadingAnimationDuration)!=null?le:2e3;if(g.setAttribute("data-preserve-animation","true"),M==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`);else{g.classList.add(`persona-tool-loading-${M}`),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),M==="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 ce=g.textContent||p;g.textContent="",A(g,ce,0)}r.status==="complete"&&(g.style.display="none")}else b||(r.status==="complete"?g.style.display="none":g.style.display="");let W=null;if(a){W=S("div","persona-flex persona-items-center");let ce=ve(s?"chevron-up":"chevron-down",16,"currentColor",2);ce?W.appendChild(ce):W.textContent=s?"Hide":"Show";let Be=S("div","persona-flex persona-items-center persona-ml-auto");Be.append(W),d.append(u,Be)}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&&c){let G=(ue=(ge=t==null?void 0:t.reasoning)==null?void 0:ge.renderCollapsedPreview)==null?void 0:ue.call(ge,{message:e,reasoning:r,defaultPreview:c,isActive:i,config:t!=null?t:{}});Ub(k,G)||(k.textContent=c),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 q=r.chunks.join(""),Z=S("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=q||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(Z),(()=>{if(d.setAttribute("aria-expanded",s?"true":"false"),W){W.innerHTML="";let ce=ve(s?"chevron-up":"chevron-down",16,"currentColor",2);ce?W.appendChild(ce):W.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 Xa=new Set,Vb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),$b=(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=Na(r.args).trim();return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
29
- `):""},zb=(e,t)=>{var u,g,p,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=$b(e,(p=o==null?void 0:o.previewMaxLines)!=null?p:3),s=r?Fg(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:{},d=s;return n==="tool-name"?d=((x=r.name)==null?void 0:x.trim())||s:n==="tool-preview"&&a&&(d=a),i&&c.activeTextTemplate?d=od(r,c.activeTextTemplate,d):!i&&c.completeTextTemplate&&(d=od(r,c.completeTextTemplate,d)),{summary:d,previewText:a,isActive:i}},Wh=(e,t,r)=>{var u;let o=Xa.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 c=a.querySelector(".persona-ml-auto"),d=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=n.toggleTextColor||n.headerTextColor||"currentColor",p=ve(o?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Mp=(e,t)=>{var q,Z,me,Ke,Ce,Ie,Ue,Te,We;let r=e.toolCall,o=(q=t==null?void 0:t.toolCall)!=null?q:{},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=(me=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?me:{},s=a.expandable!==!1,i=s&&Xa.has(e.id),{summary:c,previewText:d,isActive:u}=zb(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 p=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((Ke=r.startedAt)!=null?Ke:Date.now()),C=()=>{let de=S("span","");return de.setAttribute("data-tool-elapsed",x),de.textContent=Es(r),de},T=(Ie=o.renderCollapsedSummary)==null?void 0:Ie.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:d,collapsedMode:(Ce=a.collapsedMode)!=null?Ce:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Es(r),createElapsedElement:C});typeof T=="string"&&T.trim()?(m.textContent=T,p.appendChild(m)):T instanceof HTMLElement?p.appendChild(T):(m.textContent=c,p.appendChild(m));let E=(Ue=a.loadingAnimation)!=null?Ue:"none",M=o.activeTextTemplate,P=o.completeTextTemplate,y=u?M:P,w=T instanceof HTMLElement,b=(de,J,le)=>{let ge=le;for(let ue of J){let G=S("span","persona-tool-char");G.style.setProperty("--char-index",String(ge)),G.textContent=ue===" "?"\xA0":ue,de.appendChild(G),ge++}return ge},A=(de,J)=>{var G;m.textContent="";let le=((G=r.name)==null?void 0:G.trim())||"tool",ge=ki(de,le),ue=0;for(let ce of ge){let Be=ce.styles.length>0?(()=>{let ne=S("span",ce.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(ne),ne})():m;if(ce.isDuration&&u)Be.appendChild(C());else{let ne=ce.isDuration?Es(r):ce.text;J?ue=b(Be,ne,ue):Be.appendChild(document.createTextNode(ne))}}};if(!w)if(u&&E!=="none"){let de=(Te=o.loadingAnimationDuration)!=null?Te:2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),y&&A(y,!1);else if(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${de}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)A(y,!0);else{let J=m.textContent||c;m.textContent="",b(m,J,0)}}else y&&A(y,!1);let H=null;if(s){H=S("div","persona-flex persona-items-center");let de=o.toggleTextColor||o.headerTextColor||"currentColor",J=ve(i?"chevron-up":"chevron-down",16,de,2);J?H.appendChild(J):H.textContent=i?"Hide":"Show";let le=S("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");le.append(H),g.append(p,le)}else g.append(p);let W=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","tool"),W.style.display="none",W.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&d){let de=(We=o.renderCollapsedPreview)==null?void 0:We.call(o,{message:e,toolCall:r,defaultPreview:d,isActive:u,config:t!=null?t:{}});Vb(W,de)||(W.textContent=d),W.style.display=""}if(!i&&u&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(g,W),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 de=S("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?de.style.color=o.contentTextColor:o.headerTextColor&&(de.style.color=o.headerTextColor),de.textContent=r.name,k.appendChild(de)}if(r.args!==void 0){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Arguments";let le=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=Na(r.args),de.append(J,le),k.appendChild(de)}if(r.chunks&&r.chunks.length){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Activity";let le=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=r.chunks.join(""),de.append(J,le),k.appendChild(de)}if(r.status==="complete"&&r.result!==void 0){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Result";let le=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=Na(r.result),de.append(J,le),k.appendChild(de)}if(r.status==="complete"&&typeof r.duration=="number"){let de=S("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(de.style.color=o.contentTextColor),de.textContent=`Duration: ${r.duration}ms`,k.appendChild(de)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),H){H.innerHTML="";let de=o.toggleTextColor||o.headerTextColor||"currentColor",J=ve(i?"chevron-up":"chevron-down",16,de,2);J?H.appendChild(J):H.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",W.style.display=i?"none":W.textContent||W.childNodes.length?"":"none"})(),n.append(g,W,k),n};var bl=new Map,jb=e=>{let r=(e.startsWith(tn)?e.slice(tn.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)},Hh=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Bh=(e,t)=>{var o,n,a;let r=(n=(o=Hh(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=bl.get(e))!=null?a:r==="expanded"},Dh=(e,t,r)=>{var s,i;let o=Hh(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=ve(t?"chevron-up":"chevron-down",14,"currentColor",2);c&&a.appendChild(c)}},Fh=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=Bh(e,r);Dh(o,a,r),n.style.display=a?"":"none"};var vl=(e,t)=>{var A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de;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=(A=o==null?void 0:o.backgroundColor)!=null?A:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(H=o==null?void 0:o.borderColor)!=null?H:"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 c=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)":(W=o==null?void 0:o.titleColor)!=null?W:"currentColor",u=ve(c,20,d,2);u&&i.appendChild(u);let g=S("div","persona-flex-1 persona-min-w-0"),p=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",p.appendChild(m),!n){let J=S("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");J.setAttribute("data-approval-status",r.status),r.status==="approved"?(J.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",J.style.color="var(--persona-palette-colors-success-700, #15803d)",J.textContent="Approved"):r.status==="denied"?(J.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",J.style.color="var(--persona-palette-colors-error-700, #b91c1c)",J.textContent="Denied"):r.status==="timeout"&&(J.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",J.style.color="var(--persona-palette-colors-warning-700, #b45309)",J.textContent="Timeout"),p.appendChild(J)}g.appendChild(p);let C=r.toolType==="webmcp"||r.toolName.startsWith(tn)?zl(r.toolName):void 0,T=(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}:{}}),E=!r.toolName,M=T||(E?r.description:`The assistant wants to use \u201C${C!=null?C:jb(r.toolName)}\u201D.`),P=S("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(P.style.color=o.descriptionColor),P.textContent=M,g.appendChild(P),r.reason){let J=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");J.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?J.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(J.style.color=o.descriptionColor);let le=S("span","persona-font-medium");le.textContent=`${(q=o==null?void 0:o.reasonLabel)!=null?q:"Agent's stated reason:"} `,J.appendChild(le),J.appendChild(document.createTextNode(r.reason)),g.appendChild(J)}let y=(Z=o==null?void 0:o.detailsDisplay)!=null?Z:"collapsed",w=!!r.description&&!E,b=w||!!r.parameters;if(y!=="hidden"&&b){let J=Bh(e.id,t),le=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");le.type="button",le.setAttribute("data-expand-header","true"),le.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(le.style.color=o.descriptionColor);let ge=S("span");ge.setAttribute("data-approval-details-label","true");let ue=S("span","persona-inline-flex persona-items-center");ue.setAttribute("data-approval-details-chevron","true"),le.append(ge,ue),Dh(le,J,t),g.appendChild(le);let G=S("div");if(G.setAttribute("data-approval-details","true"),G.style.display=J?"":"none",w){let ce=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ce.style.color=o.descriptionColor),ce.textContent=r.description,G.appendChild(ce)}if(r.parameters){let ce=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&&(ce.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ce.style.color=o.parameterTextColor),ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",ce.textContent=Na(r.parameters),G.appendChild(ce)}g.appendChild(G)}if(n){let J=S("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");let le=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");le.type="button",le.style.backgroundColor=(me=o==null?void 0:o.approveButtonColor)!=null?me:"var(--persona-approval-approve-bg, #22c55e)",le.style.color=(Ke=o==null?void 0:o.approveButtonTextColor)!=null?Ke:"#ffffff",le.setAttribute("data-approval-action","approve");let ge=ve("shield-check",14,(Ce=o==null?void 0:o.approveButtonTextColor)!=null?Ce:"#ffffff",2);ge&&(ge.style.marginRight="4px",le.appendChild(ge));let ue=document.createTextNode((Ie=o==null?void 0:o.approveLabel)!=null?Ie:"Approve");le.appendChild(ue);let G=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");G.type="button",G.style.backgroundColor=(Ue=o==null?void 0:o.denyButtonColor)!=null?Ue:"transparent",G.style.color=(Te=o==null?void 0:o.denyButtonTextColor)!=null?Te:"var(--persona-feedback-error, #dc2626)",G.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,G.setAttribute("data-approval-action","deny");let ce=ve("shield-x",14,(We=o==null?void 0:o.denyButtonTextColor)!=null?We:"var(--persona-feedback-error, #dc2626)",2);ce&&(ce.style.marginRight="4px",G.appendChild(ce));let Be=document.createTextNode((de=o==null?void 0:o.denyLabel)!=null?de:"Deny");G.appendChild(Be),J.append(le,G),g.appendChild(J)}return s.append(i,g),a.appendChild(s),a};var Nh=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,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(T=>T.role==="user"))return;let g=document.createDocumentFragment(),p=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=p,c!=null&&c.fontFamily&&(C.style.fontFamily=m(c.fontFamily)),c!=null&&c.fontWeight&&(C.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(C.style.paddingLeft=c.paddingX,C.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(C.style.paddingTop=c.paddingY,C.style.paddingBottom=c.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 qs=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 Vs=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"]),Qb=new Set(["step_complete","agent_turn_complete"]),Jb=new Set(["flow_complete","agent_complete"]),Oh=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Uh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ao=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,fa=(e,t)=>{let r=e[t];return Uh(r)?r:void 0};function Tp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Cl(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 _h(e){var o,n,a,s,i;let t=fa(e,"result"),r=[fa(e,"tokens"),fa(e,"totalTokens"),t?fa(t,"tokens"):void 0,fa(e,"usage"),t?fa(t,"usage"):void 0];for(let c of r){if(!c)continue;let d=(n=(o=ao(c.output))!=null?o:ao(c.outputTokens))!=null?n:ao(c.completionTokens);if(d!==void 0)return d}return(i=(a=ao(e.outputTokens))!=null?a:ao(e.completionTokens))!=null?i:t?(s=ao(t.outputTokens))!=null?s:ao(t.completionTokens):void 0}function tv(e){var r,o,n,a,s;let t=fa(e,"result");return(s=(n=(o=(r=ao(e.executionTime))!=null?r:ao(e.executionTimeMs))!=null?o:ao(e.execution_time))!=null?n:ao(e.duration))!=null?s:t?(a=ao(t.executionTime))!=null?a:ao(t.executionTimeMs):void 0}function rv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var $s=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:Cl(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(!Uh(r)){Oh.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 c=i.exactOutputTokens+Tp(i.visibleCharCount),d=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Cl(c,d),outputTokens:c,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Qb.has(o)){if(!this.run)return;let s=this.run,i=_h(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,d=s.exactOutputTokens+Tp(s.visibleCharCount),u=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:Cl(d,u),outputTokens:d,durationMs:u,source:c?"usage":"estimate"};return}if(Jb.has(o)){if(!this.run)return;let s=this.run,i=_h(r),c=i!=null?i:s.exactOutputTokens+Tp(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:Cl(c,u),outputTokens:c,durationMs:u,source:d},this.run=null;return}if(Oh.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 Qa(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 cv(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 pv(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]"),c=S("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 Ep(e,t,r,o,n,a,s,i){var p;let c=n.has(e.id),d=S("div","persona-border-b persona-border-persona-divider persona-text-xs");Qa(d,(p=o.classNames)==null?void 0:p.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:c,onToggleExpand:()=>a(e.id)});if(m)return d.appendChild(m),d}return d.appendChild(g()),d;function g(){var q,Z;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"),T=ve(c?"chevron-down":"chevron-right","14px","currentColor",2);T&&C.appendChild(T);let E=S("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(q=o.timestampFormat)!=null?q:"relative";E.textContent=M==="relative"?lv(e.timestamp,r):dv(e.timestamp);let P=null;o.showSequenceNumbers!==!1&&(P=S("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let 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=(Z=o.descriptionFields)!=null?Z:av,A=cv(e.payload,b),H=null;A&&(H=S("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),H.textContent=A);let W=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=ve("clipboard","12px","currentColor",1.5);return N&&k.appendChild(N),k.addEventListener("click",async me=>{me.stopPropagation(),await pv(uv(e)),k.innerHTML="";let Ke=ve("check","12px","currentColor",1.5);Ke&&k.appendChild(Ke),setTimeout(()=>{k.innerHTML="";let Ce=ve("clipboard","12px","currentColor",1.5);Ce&&k.appendChild(Ce)},1500)}),x.appendChild(C),x.appendChild(E),P&&x.appendChild(P),x.appendChild(w),H&&x.appendChild(H),x.appendChild(W),x.appendChild(k),m.appendChild(x),c&&m.appendChild(gv(e,s,i)),m}}function qh(e){var x,C,T,E,M;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,d=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",u=(T=i==null?void 0:i.label)!=null?T:"",g=(M=(E=n==null?void 0:n.features)==null?void 0:E.eventStream)!=null?M:{},p=a.find(P=>P.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&n){let P=p.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return m();function m(){let P=g.classNames,y=S("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Qa(y,P==null?void 0:P.panel);let w=[],b="",A="",H=null,W=[],k={},N=0,q=ol(),Z=0,me=0,Ke=!1,Ce=null,Ie=!1,Ue=0,Te=new Set,We=new Map,de="",J="",le=null,ge,ue,G,ce,Be,ne=null,ee=null,ie=null;function vt(){let oe=S("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),we=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");Qa(we,P==null?void 0:P.headerBar);let De=S("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(De.textContent="Events",ge=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"),ge.textContent="0",s){ee=S("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let so=S("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");so.textContent="Throughput",ne=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"),ne.textContent="-- tok/s",ie=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"),ie.style.display="none",ie.style.pointerEvents="none";let Rr=ee,ir=ie,Ur=()=>{if(!ir.textContent)return;let yt=Rr.getBoundingClientRect(),jr=oe.getBoundingClientRect();ir.style.left=`${yt.left-jr.left}px`,ir.style.top=`${yt.bottom-jr.top+4}px`,ir.style.display="block"},ko=()=>{ir.style.display="none"};ee.addEventListener("mouseenter",Ur),ee.addEventListener("mouseleave",ko),ee.appendChild(so),ee.appendChild(ne)}let At=S("div","persona-flex-1");ue=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 ar=S("option","");ar.value="",ar.textContent="All events",ue.appendChild(ar),G=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"),G.type="button",G.title="Copy All";let wr=ve("clipboard-copy","12px","currentColor",1.5);wr&&G.appendChild(wr);let Ft=S("span","persona-text-xs");Ft.textContent="Copy All",G.appendChild(Ft),we.appendChild(De),we.appendChild(ge),ee&&we.appendChild(ee),we.appendChild(At),we.appendChild(ue),we.appendChild(G);let ot=S("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Qa(ot,P==null?void 0:P.searchBar);let Dt=ve("search","14px","var(--persona-muted, #9ca3af)",1.5),lt=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");Dt&&lt.appendChild(Dt),ce=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"),Qa(ce,P==null?void 0:P.searchInput),ce.type="text",ce.placeholder="Search event payloads...",Be=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"),Be.type="button",Be.style.display="none";let Yt=ve("x","12px","currentColor",2);return Yt&&Be.appendChild(Yt),ot.appendChild(lt),ot.appendChild(ce),ot.appendChild(Be),oe.appendChild(we),oe.appendChild(ot),ie&&oe.appendChild(ie),oe}let Lt,gt=a.find(oe=>oe.renderEventStreamToolbar);if(gt!=null&&gt.renderEventStreamToolbar&&n){let oe=gt.renderEventStreamToolbar({config:n,defaultRenderer:()=>vt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:we=>{b=we,Wt(),V()},onSearchChange:we=>{A=we,Wt(),V()}});Lt=oe!=null?oe:vt()}else Lt=vt();let _e=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");_e.style.display="none";function be(){if(!s||!ne||!ee)return;let oe=s();ne.textContent=fv(oe);let we=mv(oe);ie&&(ie.textContent=we,we||(ie.style.display="none")),we?ee.setAttribute("aria-label",we):ee.removeAttribute("aria-label")}let Ze=S("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=S("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let pe=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");Qa(pe,P==null?void 0:P.scrollIndicator),pe.style.display="none",pe.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let Me=ve(d,"14px","currentColor",2);Me&&pe.appendChild(Me);let Je=S("span","");Je.textContent=u,pe.appendChild(Je);let Ge=S("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ge.style.display="none",Ze.appendChild(Y),Ze.appendChild(Ge),Ze.appendChild(pe),y.setAttribute("tabindex","0"),y.appendChild(Lt),y.appendChild(_e),y.appendChild(Ze);function ke(){let oe=t.getAll(),we={};for(let Ft of oe)we[Ft.type]=(we[Ft.type]||0)+1;let De=Object.keys(we).sort(),At=De.length!==W.length||!De.every((Ft,ot)=>Ft===W[ot]),ar=!At&&De.some(Ft=>we[Ft]!==k[Ft]),sr=oe.length!==Object.values(k).reduce((Ft,ot)=>Ft+ot,0);if(!At&&!ar&&!sr||(W=De,k=we,!ue))return;let wr=ue.value;if(ue.options[0].textContent="All events",At){for(;ue.options.length>1;)ue.remove(1);for(let Ft of De){let ot=S("option","");ot.value=Ft,ot.textContent=`${Ft} (${we[Ft]||0})`,ue.appendChild(ot)}wr&&De.includes(wr)?ue.value=wr:wr&&(ue.value="",b="")}else for(let Ft=1;Ft<ue.options.length;Ft++){let ot=ue.options[Ft];ot.textContent=`${ot.value} (${we[ot.value]||0})`}}function je(){let oe=t.getAll();if(b&&(oe=oe.filter(we=>we.type===b)),A){let we=A.toLowerCase();oe=oe.filter(De=>De.type.toLowerCase().includes(we)||De.payload.toLowerCase().includes(we))}return oe}function Cr(){return b!==""||A!==""}function Wt(){N=0,Z=0,q.resume(),pe.style.display="none"}function ur(oe){Te.has(oe)?Te.delete(oe):Te.add(oe),le=oe;let we=Y.scrollTop,De=q.isFollowing();Ie=!0,q.pause(),V(),Y.scrollTop=we,De&&q.resume(),Ie=!1}function Eo(){return da(Y,50)}function V(){me=Date.now(),Ke=!1,be(),ke();let oe=t.getEvictedCount();oe>0?(_e.textContent=`${oe.toLocaleString()} older events truncated`,_e.style.display=""):_e.style.display="none",w=je();let we=w.length,De=t.getSize()>0;ge&&(ge.textContent=String(t.getSize())),we===0&&De&&Cr()?(Ge.textContent=A?`No events matching '${A}'`:"No events matching filter",Ge.style.display="",Y.style.display="none"):(Ge.style.display="none",Y.style.display=""),G&&(G.title=Cr()?`Copy Filtered (${we})`:"Copy All"),c&&!q.isFollowing()&&we>N&&(Z+=we-N,Je.textContent=u?`${u}${Z>0?` (${Z})`:""}`:"",pe.style.display=""),N=we;let At=t.getAll(),ar=At.length>0?At[0].timestamp:0,sr=new Set(w.map(ot=>ot.id));for(let ot of Te)sr.has(ot)||Te.delete(ot);let wr=b!==de||A!==J,Ft=We.size===0&&w.length>0;if(wr||Ft||w.length===0){Y.innerHTML="",We.clear();let ot=document.createDocumentFragment();for(let Dt=0;Dt<w.length;Dt++){let lt=Ep(w[Dt],Dt,ar,g,Te,ur,a,n);We.set(w[Dt].id,lt),ot.appendChild(lt)}Y.appendChild(ot),de=b,J=A,le=null}else{if(le!==null){let Dt=We.get(le);if(Dt&&Dt.parentNode===Y){let lt=w.findIndex(Yt=>Yt.id===le);if(lt>=0){let Yt=Ep(w[lt],lt,ar,g,Te,ur,a,n);Y.insertBefore(Yt,Dt),Dt.remove(),We.set(le,Yt)}}le=null}let ot=new Set(w.map(Dt=>Dt.id));for(let[Dt,lt]of We)ot.has(Dt)||(lt.remove(),We.delete(Dt));for(let Dt=0;Dt<w.length;Dt++){let lt=w[Dt];if(!We.has(lt.id)){let Yt=Ep(lt,Dt,ar,g,Te,ur,a,n);We.set(lt.id,Yt),Y.appendChild(Yt)}}}q.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function j(){if(Date.now()-me>=sv){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),V();return}Ke||(Ke=!0,Ce=requestAnimationFrame(()=>{Ce=null,V()}))}let he=(oe,we)=>{if(!G)return;G.innerHTML="";let De=ve(oe,"12px","currentColor",1.5);De&&G.appendChild(De);let At=S("span","persona-text-xs");At.textContent="Copy All",G.appendChild(At),setTimeout(()=>{G.innerHTML="";let ar=ve("clipboard-copy","12px","currentColor",1.5);ar&&G.appendChild(ar);let sr=S("span","persona-text-xs");sr.textContent="Copy All",G.appendChild(sr),G.disabled=!1},we)},Xe=async()=>{if(G){G.disabled=!0;try{let oe;Cr()?oe=w:r?(oe=await r(),oe.length===0&&(oe=t.getAll())):oe=t.getAll();let we=oe.map(De=>{try{return JSON.parse(De.payload)}catch{return De.payload}});await navigator.clipboard.writeText(JSON.stringify(we,null,2)),he("check",1500)}catch{he("x",1500)}}},et=()=>{ue&&(b=ue.value,Wt(),V())},qe=()=>{!ce||!Be||(Be.style.display=ce.value?"":"none",H&&clearTimeout(H),H=setTimeout(()=>{A=ce.value,Wt(),V()},150))},Ne=()=>{!ce||!Be||(ce.value="",A="",Be.style.display="none",H&&clearTimeout(H),Wt(),V())},Pt=()=>{if(Ie)return;let oe=Y.scrollTop,{action:we,nextLastScrollTop:De}=nl({following:q.isFollowing(),currentScrollTop:oe,lastScrollTop:Ue,nearBottom:Eo(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ue=De,we==="resume"?(q.resume(),Z=0,pe.style.display="none"):we==="pause"&&(q.pause(),c&&(Je.textContent=u,pe.style.display=""))},Gt=oe=>{let we=al({following:q.isFollowing(),deltaY:oe.deltaY,nearBottom:Eo(),resumeWhenNearBottom:!0});we==="pause"?(q.pause(),c&&(Je.textContent=u,pe.style.display="")):we==="resume"&&(q.resume(),Z=0,pe.style.display="none")},Jt=()=>{c&&(Y.scrollTop=Y.scrollHeight,q.resume(),Z=0,pe.style.display="none")},Pr=oe=>{let we=oe.target;if(!we||we.closest("button"))return;let De=we.closest("[data-event-id]");if(!De)return;let At=De.getAttribute("data-event-id");At&&ur(At)},z=oe=>{if((oe.metaKey||oe.ctrlKey)&&oe.key==="f"){oe.preventDefault(),ce==null||ce.focus(),ce==null||ce.select();return}oe.key==="Escape"&&(ce&&document.activeElement===ce?(Ne(),ce.blur(),y.focus()):o&&o())};G&&G.addEventListener("click",Xe),ue&&ue.addEventListener("change",et),ce&&ce.addEventListener("input",qe),Be&&Be.addEventListener("click",Ne),Y.addEventListener("scroll",Pt),Y.addEventListener("wheel",Gt,{passive:!0}),Y.addEventListener("click",Pr),pe.addEventListener("click",Jt),y.addEventListener("keydown",z);function Ht(){H&&clearTimeout(H),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ke=!1,We.clear(),G&&G.removeEventListener("click",Xe),ue&&ue.removeEventListener("change",et),ce&&ce.removeEventListener("input",qe),Be&&Be.removeEventListener("click",Ne),Y.removeEventListener("scroll",Pt),Y.removeEventListener("wheel",Gt),Y.removeEventListener("click",Pr),pe.removeEventListener("click",Jt),y.removeEventListener("keydown",z)}return{element:y,update:j,destroy:Ht}}}function Vh(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 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 p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #171717)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(p);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,g.appendChild(m)}else g.textContent=s;if(d.append(u,g),i.append(c,d),n==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${r}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",o),i.append(p)}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",d=typeof e.artifactType=="string"?e.artifactType:"markdown",u=r({artifact:{artifactId:i,title:s,artifactType:d,status:c},config:t.config,defaultRenderer:()=>Vh(e,t)});if(u)return u}return Vh(e,t)};var kp=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)})}},dn=new kp;dn.register("PersonaArtifactCard",$h);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 zh(e,t){var ue,G,ce,Be;let r=(G=(ue=e.features)==null?void 0:ue.artifacts)==null?void 0:G.layout,n=((ce=r==null?void 0:r.toolbarPreset)!=null?ce:"default")==="document",a=(Be=r==null?void 0:r.panePadding)==null?void 0:Be.trim(),s=e.markdown?Zn(e.markdown):null,i=Wa(e.sanitize),c=ne=>{let ee=s?s(ne):qo(ne);return i?i(ee):ee},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 ne;u(),(ne=t.onDismiss)==null||ne.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 p=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");p.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&p.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 ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let C="rendered",T=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=n?yr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):yr({icon:"eye",label:"Rendered view"}),M=n?yr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):yr({icon:"code-2",label:"Source"}),P=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,A=!!(w&&b&&b.length>0),H=null,W,k=null,N=null;if(n&&(y||w)&&!A){if(W=y?Us({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let ne=ve("chevron-down",14,"currentColor",2);ne&&W.appendChild(ne)}}else n&&A?(H=S("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),W=y?Us({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=yr({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"}}),H.append(W,k)):n?W=yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):W=yr({icon:"copy",label:"Copy"});let q=n?yr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):yr({icon:"refresh-cw",label:"Refresh"}),Z=n?yr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):yr({icon:"x",label:"Close"}),me=()=>{var Lt,gt,_e;let ne=(Lt=We.find(be=>be.id===de))!=null?Lt:We[We.length-1],ee=(gt=ne==null?void 0:ne.id)!=null?gt:null,ie=(ne==null?void 0:ne.artifactType)==="markdown"&&(_e=ne.markdown)!=null?_e:"",vt=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:ie,jsonPayload:vt,id:ee}},Ke=async()=>{var Lt;let{markdown:ne,jsonPayload:ee}=me(),ie=(Lt=We.find(gt=>gt.id===de))!=null?Lt:We[We.length-1],vt=(ie==null?void 0:ie.artifactType)==="markdown"?ne:ie?ee:"";try{await navigator.clipboard.writeText(vt)}catch{}};if(W.addEventListener("click",async()=>{let ne=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(ne&&A){let{markdown:ee,jsonPayload:ie,id:vt}=me();try{await ne({actionId:"primary",artifactId:vt,markdown:ee,jsonPayload:ie})}catch{}return}await Ke()}),k&&(b!=null&&b.length)){let ne=()=>{var ie;return(ie=g.closest("[data-persona-root]"))!=null?ie:document.body},ee=()=>{N=Fn({items:b.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:vt,jsonPayload:Lt,id:gt}=me(),_e=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:ie,artifactId:gt,markdown:vt,jsonPayload:Lt}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(vt):ie==="json"||ie==="source"?await navigator.clipboard.writeText(Lt):await navigator.clipboard.writeText(vt||Lt)}catch{}},anchor:H!=null?H:k,position:"bottom-right",portal:ne()})};g.isConnected?ee():requestAnimationFrame(ee),k.addEventListener("click",ie=>{ie.stopPropagation(),N==null||N.toggle()})}q.addEventListener("click",async()=>{var ne;try{await((ne=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:ne.call(r))}catch{}le()}),Z.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let Ce=()=>{n&&(E.setAttribute("aria-pressed",C==="rendered"?"true":"false"),M.setAttribute("aria-pressed",C==="source"?"true":"false"))};E.addEventListener("click",()=>{C="rendered",Ce(),le()}),M.addEventListener("click",()=>{C="source",Ce(),le()});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?(p.replaceChildren(),T.append(E,M),H?P.append(H,q,Z):P.append(W,q,Z),p.append(T,Ie,P),Ce()):(p.appendChild(m),p.appendChild(x)),a&&(p.style.paddingLeft=a,p.style.paddingRight=a);let Ue=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"),Te=S("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(Ue.style.paddingLeft=a,Ue.style.paddingRight=a,Te.style.padding=a),g.appendChild(p),g.appendChild(Ue),g.appendChild(Te);let We=[],de=null,J=!1,le=()=>{var vt,Lt,gt,_e;let ne=n&&We.length<=1;Ue.classList.toggle("persona-hidden",ne),Ue.replaceChildren();for(let be of We){let Ze=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");Ze.type="button",Ze.textContent=be.title||be.id.slice(0,8),be.id===de&&Ze.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ze.addEventListener("click",()=>t.onSelect(be.id)),Ue.appendChild(Ze)}Te.replaceChildren();let ee=de&&We.find(be=>be.id===de)||We[We.length-1];if(!ee)return;if(n){let be=ee.artifactType==="markdown"?"MD":(vt=ee.component)!=null?vt:"Component",Y=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ie.textContent=`${Y} \xB7 ${be}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(n&&C==="source"){let Ze=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ze.textContent=(Lt=ee.markdown)!=null?Lt:"",Te.appendChild(Ze);return}let be=S("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");be.innerHTML=c((gt=ee.markdown)!=null?gt:""),Te.appendChild(be);return}let ie=ee.component?dn.get(ee.component):void 0;if(ie){let Ze={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Y=ie((_e=ee.props)!=null?_e:{},Ze);if(Y){Te.appendChild(Y);return}}catch{}}Te.appendChild(hv(ee))},ge=()=>{var ee;let ne=We.length>0;if(g.classList.toggle("persona-hidden",!ne),d){let ie=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,Lt=((ee=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ne&&Lt&&J?(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(ne){var ee,ie,vt;We=ne.artifacts,de=(vt=(ie=ne.selectedId)!=null?ie:(ee=ne.artifacts[ne.artifacts.length-1])==null?void 0:ee.id)!=null?vt:null,We.length>0&&(J=!0),le(),ge()},setMobileOpen(ne){J=ne,!ne&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):ge()}}}function xo(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 jh(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"),!xo(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 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 wl(e,t){var c,d,u,g,p,m,x,C,T,E;if(!xo(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),jh(e,t);return}let r=(d=(c=t.features)==null?void 0:c.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",(p=r==null?void 0:r.paneMaxWidth)!=null?p:"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=(T=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:T.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"),jh(e,t)}var Gh=["panel","seamless"];function Sl(e,t){var i,c,d,u,g,p;for(let m of Gh)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"),!xo(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(d=r==null?void 0:r.paneAppearance)!=null?d:"panel",n=Gh.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=((p=r.unifiedSplitOuterRadius)==null?void 0:p.trim())||a;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Kh(e,t){var r,o,n;return!t||!xo(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 Xh(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=yv(n,200),i=Cv(t,r,o,200);i=Math.max(s,i);let c=bv(a);return c!==null&&(i=Math.min(i,c)),vv(e,s,i)}var Jh={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"}},Lp=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var x,C,T;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(C=Jh[s])!=null?C:Jh.init;a.classList.add("persona-form-card","persona-space-y-4");let c=S("div","persona-space-y-1"),d=S("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,c.appendChild(d),i.description){let E=S("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,c.appendChild(E)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var b,A;let M=S("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${t.id}-${s}-${E.name}`;let P=S("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=E.label,M.appendChild(P);let y=(b=E.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}-${E.name}`,w.name=E.name,w.placeholder=(A=E.placeholder)!=null?A:"",E.required&&(w.required=!0),M.appendChild(w),u.appendChild(M)});let g=S("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),p=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=(T=i.submitLabel)!=null?T:"Submit",g.appendChild(p),g.appendChild(m),u.appendChild(g),a.replaceChildren(c,u),u.addEventListener("submit",async E=>{var w,b;E.preventDefault();let M=(w=r.formEndpoint)!=null?w:"/form",P=new FormData(u),y={};P.forEach((A,H)=>{y[H]=A}),y.type=s,m.disabled=!0,p.textContent="Submitting\u2026";try{let A=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!A.ok)throw new Error(`Form submission failed (${A.status})`);let H=await A.json();p.textContent=(b=H.message)!=null?b:"Thanks! We'll be in touch soon.",H.success&&H.nextPrompt&&await o.sendMessage(String(H.nextPrompt))}catch(A){p.textContent=A instanceof Error?A.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Pp=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()}},zs=new Pp;var Yh=()=>{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 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},js=({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}},Rp=e=>typeof e=="string"?e:e==null?"":String(e),ma={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Rp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=Rp(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:Rp(r.text)}}},Zh=e=>Array.isArray(e)?e.map(t=>String(t)):[],Gs=e=>{let t=new Set(Zh(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(Zh(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 c={action:i,message:a.message};e.emit("action:detected",c);for(let d of e.handlers)if(d)try{let u=()=>{e.emit("action:resubmit",c)},g=d(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let p=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:p,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"})),Al=(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 Ja=Pa(bi(),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 Ml(){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,Ja.parse)(r,Ja.STR|Ja.OBJ),a=kv(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function ex(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Tl(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=dn.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 tx(){let e=Ml();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function rx(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 El(e){let t=rx(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 kl(e){let t=rx(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 Ll(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: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,p=document.createElement("div");p.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),p.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let b=1;b<=5;b++){let A=document.createElement("button");A.type="button",A.className="persona-feedback-rating-btn persona-feedback-star-btn",A.setAttribute("role","radio"),A.setAttribute("aria-checked","false"),A.setAttribute("aria-label",`${b} star${b>1?"s":""}: ${d[b-1]}`),A.title=d[b-1],A.dataset.rating=String(b),A.innerHTML=`
26
+ `,r.addEventListener("click",t);let o=a=>{var k,y,S,b,M,W,R,L,N,q,Y,me,Ge;let s=(k=a.launcher)!=null?k:{},i=ur(a),c=r.querySelector("[data-role='launcher-title']");if(c){let Ce=(y=s.title)!=null?y:"Chat Assistant";c.textContent=Ce,c.setAttribute("title",Ce)}let d=r.querySelector("[data-role='launcher-subtitle']");if(d){let Ce=(S=s.subtitle)!=null?S:"Here to help you get answers fast";d.textContent=Ce,d.setAttribute("title",Ce)}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 Ce=(b=s.agentIconSize)!=null?b:"40px";if(g.style.height=Ce,g.style.width=Ce,g.innerHTML="",s.agentIconName){let Be=parseFloat(Ce)||24,qe=ve(s.agentIconName,Be*.6,"var(--persona-text-inverse, #ffffff)",2);qe?(g.appendChild(qe),g.style.display=""):(g.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}",g.style.display="")}else s.iconUrl?g.style.display="none":(g.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}",g.style.display="")}let p=r.querySelector("[data-role='launcher-image']");if(p){let Ce=(R=s.agentIconSize)!=null?R:"40px";p.style.height=Ce,p.style.width=Ce,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(p.src=s.iconUrl,p.style.display="block"):p.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ce=(L=s.callToActionIconSize)!=null?L:"32px";m.style.height=Ce,m.style.width=Ce,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 Be=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,Be=(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(Ce)||24,Ee=Math.max(qe-Be,8),De=ve(s.callToActionIconName,Ee,"currentColor",2);De?m.appendChild(De):m.textContent=(N=s.callToActionIconText)!=null?N:"\u2197"}else m.textContent=(q=s.callToActionIconText)!=null?q:"\u2197"}let x=s.position&&Mo[s.position]?Mo[s.position]:Mo["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",T="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?T:`${C} ${x}`,i||(r.style.zIndex=String((Y=s.zIndex)!=null?Y:Rr));let E="1px solid var(--persona-border, #e5e7eb)",w="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:w,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=(Ge=s.collapsedMaxWidth)!=null?Ge:"",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 Ih=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=Lh(e),a=Ph(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},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:c,composer:d,replaceHeader:p=>(c.element.replaceWith(p.header),c.element=p.header,c.iconHolder=p.iconHolder,c.headerTitle=p.headerTitle,c.headerSubtitle=p.headerSubtitle,c.closeButton=p.closeButton,c.closeButtonWrapper=p.closeButtonWrapper,c.clearChatButton=p.clearChatButton,c.clearChatButtonWrapper=p.clearChatButtonWrapper,p),replaceComposer:p=>{d.footer.replaceWith(p),d.footer=p}}},Cp=({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:()=>vp(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=vp(e,r);return{instance:n,element:n.element}};var Pb=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}},Ib=(e,t)=>{if(!e)return null;let r=Pb(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},Rb=(e,t)=>{let r=A("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},Wb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},wp=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(":"))},Sp=320,Wh=320,Hb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Bb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Db=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Fb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Nb=(e,t,r)=>{if(e.length===0)return null;try{let o=A("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 g;let d=A("img");d.alt=((g=i.alt)==null?void 0:g.trim())||`Attached image ${c+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Sp}px`,d.style.maxHeight=`${Wh}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}),Wb(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}},Ob=e=>{if(e.length===0)return null;try{let t=A("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!wp(o.audio))return;let n=A("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${Sp}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},_b=e=>{if(e.length===0)return null;try{let t=A("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!wp(o.video))return;let n=A("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${Sp}px`,n.style.maxHeight=`${Wh}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}},Ub=e=>{if(e.length===0)return null;try{let t=A("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!wp(o.data))return;let n=A("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}},ua=()=>{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},Ap=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:ua};if(t){let n=t(o);if(n!==null)return n}return ua()},qb=(e,t)=>{let r=A("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=A("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},Rh=(e,t,r="div")=>{let o=A(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},Vb=(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},Mp=(e,t,r)=>{var x,C,T,E,w,k,y;let o=(x=t.showCopy)!=null?x:!0,n=(C=t.showUpvote)!=null?C:!0,a=(T=t.showDownvote)!=null?T:!0,s=(E=t.showReadAloud)!=null?E:!1;if(!o&&!n&&!a&&!s){let S=A("div");return S.style.display="none",S.id=`actions-${e.id}`,S.setAttribute("data-actions-for",e.id),S}let i=(w=t.visibility)!=null?w:"hover",c=(k=t.align)!=null?k:"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"}[c],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=A("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${g} ${i==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=(S,b,M)=>{let W=br({icon:S,label:b,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",M),W};return o&&p.appendChild(m("copy","Copy message","copy")),s&&p.appendChild(m("volume-2","Read aloud","read-aloud")),n&&p.appendChild(m("thumbs-up","Upvote","upvote")),a&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},ja=(e,t,r,o,n,a)=>{var le,Q,ie,ge,ue,j,de,Ne,te,Z,ae,wt,Pt,xt,Ue,be,Je;let s=r!=null?r:{},i=(le=s.layout)!=null?le:"bubble",c=s.avatar,d=s.timestamp,u=(Q=c==null?void 0:c.show)!=null?Q:!1,g=(ie=d==null?void 0:d.show)!=null?ie:!1,p=(ge=c==null?void 0:c.position)!=null?ge:"left",m=(ue=d==null?void 0:d.position)!=null?ue:"below",x=Vb(e.role,i),C=A("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 T=Hb(e),E=(de=(j=e.content)==null?void 0:j.trim())!=null?de:"",k=T.length>0&&E===Fi,y=ll((te=(Ne=a==null?void 0:a.widgetConfig)==null?void 0:Ne.features)==null?void 0:te.streamAnimation),S=(wt=(ae=(Z=a==null?void 0:a.widgetConfig)==null?void 0:Z.features)==null?void 0:ae.streamAnimation)==null?void 0:wt.plugins,b=e.role==="assistant"&&y.type!=="none"?Bs(y.type,S):null,M=e.role==="assistant"&&((Pt=b==null?void 0:b.isAnimating)==null?void 0:Pt.call(b,e))===!0,W=e.role==="assistant"&&b!==null&&(!!e.streaming||M);W&&(b!=null&&b.bubbleClass)&&C.classList.add(b.bubbleClass);let R=document.createElement("div");R.classList.add("persona-message-content"),W&&b&&(b.containerClass&&R.classList.add(b.containerClass),R.style.setProperty("--persona-stream-step",`${y.speed}ms`),R.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let L=W?dl((xt=e.content)!=null?xt:"",y.buffer,b,e,!!e.streaming):(Ue=e.content)!=null?Ue:"",N=t({text:L,message:e,streaming:!!e.streaming,raw:e.rawContent}),q=N;W&&(b==null?void 0:b.wrap)==="char"?q=Ds(N,"char",e.id,{skipTags:b.skipTags}):W&&(b==null?void 0:b.wrap)==="word"&&(q=Ds(N,"word",e.id,{skipTags:b.skipTags}));let Y=null;if(k?(Y=document.createElement("div"),Y.innerHTML=q,Y.style.display="none",R.appendChild(Y)):R.innerHTML=q,W&&(b!=null&&b.useCaret)&&!k&&E){let J=cl(),ce=R.querySelectorAll(".persona-stream-char, .persona-stream-word"),Te=ce[ce.length-1];if(Te!=null&&Te.parentNode)Te.parentNode.insertBefore(J,Te.nextSibling);else{let Xe=R.lastElementChild;Xe?Xe.appendChild(J):R.appendChild(J)}}if(g&&m==="inline"&&e.createdAt){let J=Rh(e,d,"span");J.classList.add("persona-timestamp-inline");let ce=R.lastElementChild;ce?ce.appendChild(J):R.appendChild(J)}if(T.length>0){let J=Nb(T,!k&&!!E,()=>{k&&Y&&(Y.style.display="")});J?C.appendChild(J):k&&Y&&(Y.style.display="")}let me=Bb(e);if(me.length>0){let J=Ob(me);J&&C.appendChild(J)}let Ge=Db(e);if(Ge.length>0){let J=_b(Ge);J&&C.appendChild(J)}let Ce=Fb(e);if(Ce.length>0){let J=Ub(Ce);J&&C.appendChild(J)}if(C.appendChild(R),g&&m==="below"&&e.createdAt){let J=Rh(e,d);J.classList.add("persona-mt-1"),C.appendChild(J)}let Be=e.role==="assistant"?Ib(e.stopReason,(Je=(be=a==null?void 0:a.widgetConfig)==null?void 0:be.copy)==null?void 0:Je.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(L&&L.trim()),ce=y.placeholder==="skeleton",Te=ce&&y.buffer==="line"&&J;if(J)Te&&C.appendChild(Fs());else if(ce)C.appendChild(Fs());else{let Xe=Ap("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Xe&&C.appendChild(Xe)}}if(Be&&e.stopReason&&!e.streaming&&(E||(R.style.display="none"),C.appendChild(Rb(e.stopReason,Be))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let J=Mp(e,o,n);C.appendChild(J)}if(!u||e.role==="system")return C;let Ee=A("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),De=qb(c,e.role);return p==="right"||p==="left"&&e.role==="user"?Ee.append(C,De):Ee.append(De,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ee},Hh=(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}):ja(e,t,r,o,n,a)};var Ga=new Set,$b=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zb=(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
+ `):""},Bh=(e,t)=>{let r=Ga.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=ve(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")},Tp=(e,t)=>{var Ge,Ce,Be,qe,Ee,De,le,Q,ie,ge,ue;let r=e.reasoning,o=A("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=(Ce=(Ge=t==null?void 0:t.features)==null?void 0:Ge.reasoningDisplay)!=null?Ce:{},a=n.expandable!==!1,s=a&&Ga.has(e.id),i=r.status!=="complete",c=zb(e,(Be=n.previewMaxLines)!=null?Be:3),d=A("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=A("div","persona-flex persona-flex-col persona-text-left"),g=A("span","persona-text-xs persona-text-persona-primary"),p="Thinking...",m=(qe=t==null?void 0:t.reasoning)!=null?qe:{},x=String((Ee=r.startedAt)!=null?Ee:Date.now()),C=()=>{let j=A("span","");return j.setAttribute("data-tool-elapsed",x),j.textContent=ki(r),j},T=(De=m.renderCollapsedSummary)==null?void 0:De.call(m,{message:e,reasoning:r,defaultSummary:p,previewText:c,isActive:i,config:t!=null?t:{},elapsed:ki(r),createElapsedElement:C});typeof T=="string"&&T.trim()?(g.textContent=T,u.appendChild(g)):T instanceof HTMLElement?u.appendChild(T):(g.textContent=p,u.appendChild(g));let E=A("span","persona-text-xs persona-text-persona-primary");E.textContent=Fg(r),u.appendChild(E);let w=(le=n.loadingAnimation)!=null?le:"none",k=m.activeTextTemplate,y=m.completeTextTemplate,S=i?k:y,b=T instanceof HTMLElement,M=(j,de,Ne)=>{let te=Ne;for(let Z of de){let ae=A("span","persona-tool-char");ae.style.setProperty("--char-index",String(te)),ae.textContent=Z===" "?"\xA0":Z,j.appendChild(ae),te++}return te},W=(j,de)=>{g.textContent="";let Ne=Li(j,""),te=0;for(let Z of Ne){let ae=Z.styles.length>0?(()=>{let wt=A("span",Z.styles.map(Pt=>`persona-tool-text-${Pt}`).join(" "));return g.appendChild(wt),wt})():g;if(Z.isDuration&&i)ae.appendChild(C());else{let wt=Z.isDuration?ki(r):Z.text;de?te=M(ae,wt,te):ae.appendChild(document.createTextNode(wt))}}};if(!b&&S)if(E.style.display="none",g.style.display="",i&&w!=="none"){let j=(Q=m.loadingAnimationDuration)!=null?Q:2e3;g.setAttribute("data-preserve-animation","true"),w==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`),W(S,!1)):(g.classList.add(`persona-tool-loading-${w}`),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`),w==="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)),W(S,!0))}else W(S,!1);else if(!b&&i&&w!=="none"){g.style.display="";let j=(ie=m.loadingAnimationDuration)!=null?ie:2e3;if(g.setAttribute("data-preserve-animation","true"),w==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`);else{g.classList.add(`persona-tool-loading-${w}`),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`),w==="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 de=g.textContent||p;g.textContent="",M(g,de,0)}r.status==="complete"&&(g.style.display="none")}else b||(r.status==="complete"?g.style.display="none":g.style.display="");let R=null;if(a){R=A("div","persona-flex persona-items-center");let de=ve(s?"chevron-up":"chevron-down",16,"currentColor",2);de?R.appendChild(de):R.textContent=s?"Hide":"Show";let Ne=A("div","persona-flex persona-items-center persona-ml-auto");Ne.append(R),d.append(u,Ne)}else d.append(u);let L=A("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(L.setAttribute("data-persona-collapsed-preview","reasoning"),L.style.display="none",L.style.whiteSpace="pre-wrap",!s&&i&&n.activePreview&&c){let j=(ue=(ge=t==null?void 0:t.reasoning)==null?void 0:ge.renderCollapsedPreview)==null?void 0:ue.call(ge,{message:e,reasoning:r,defaultPreview:c,isActive:i,config:t!=null?t:{}});$b(L,j)||(L.textContent=c),L.style.display=""}if(!s&&i&&n.activeMinHeight&&(o.style.minHeight=n.activeMinHeight),!a)return o.append(d,L),o;let N=A("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=s?"":"none";let q=r.chunks.join(""),Y=A("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Y.textContent=q||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(Y),(()=>{if(d.setAttribute("aria-expanded",s?"true":"false"),R){R.innerHTML="";let de=ve(s?"chevron-up":"chevron-down",16,"currentColor",2);de?R.appendChild(de):R.textContent=s?"Hide":"Show"}N.style.display=s?"":"none",L.style.display=s?"none":L.textContent||L.childNodes.length?"":"none"})(),o.append(d,L,N),o};var Ka=new Set,jb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Gb=(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=Fa(r.args).trim();return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
29
+ `):""},Kb=(e,t)=>{var u,g,p,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=Gb(e,(p=o==null?void 0:o.previewMaxLines)!=null?p:3),s=r?Ng(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:{},d=s;return n==="tool-name"?d=((x=r.name)==null?void 0:x.trim())||s:n==="tool-preview"&&a&&(d=a),i&&c.activeTextTemplate?d=ad(r,c.activeTextTemplate,d):!i&&c.completeTextTemplate&&(d=ad(r,c.completeTextTemplate,d)),{summary:d,previewText:a,isActive:i}},Dh=(e,t,r)=>{var u;let o=Ka.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 c=a.querySelector(".persona-ml-auto"),d=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=n.toggleTextColor||n.headerTextColor||"currentColor",p=ve(o?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Ep=(e,t)=>{var q,Y,me,Ge,Ce,Be,qe,Ee,De;let r=e.toolCall,o=(q=t==null?void 0:t.toolCall)!=null?q:{},n=A("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=(Y=t==null?void 0:t.features)==null?void 0:Y.toolCallDisplay)!=null?me:{},s=a.expandable!==!1,i=s&&Ka.has(e.id),{summary:c,previewText:d,isActive:u}=Kb(e,t),g=A("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 p=A("div","persona-flex persona-flex-col persona-text-left"),m=A("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let x=String((Ge=r.startedAt)!=null?Ge:Date.now()),C=()=>{let le=A("span","");return le.setAttribute("data-tool-elapsed",x),le.textContent=Ts(r),le},T=(Be=o.renderCollapsedSummary)==null?void 0:Be.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:d,collapsedMode:(Ce=a.collapsedMode)!=null?Ce:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Ts(r),createElapsedElement:C});typeof T=="string"&&T.trim()?(m.textContent=T,p.appendChild(m)):T instanceof HTMLElement?p.appendChild(T):(m.textContent=c,p.appendChild(m));let E=(qe=a.loadingAnimation)!=null?qe:"none",w=o.activeTextTemplate,k=o.completeTextTemplate,y=u?w:k,S=T instanceof HTMLElement,b=(le,Q,ie)=>{let ge=ie;for(let ue of Q){let j=A("span","persona-tool-char");j.style.setProperty("--char-index",String(ge)),j.textContent=ue===" "?"\xA0":ue,le.appendChild(j),ge++}return ge},M=(le,Q)=>{var j;m.textContent="";let ie=((j=r.name)==null?void 0:j.trim())||"tool",ge=Li(le,ie),ue=0;for(let de of ge){let Ne=de.styles.length>0?(()=>{let te=A("span",de.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return m.appendChild(te),te})():m;if(de.isDuration&&u)Ne.appendChild(C());else{let te=de.isDuration?Ts(r):de.text;Q?ue=b(Ne,te,ue):Ne.appendChild(document.createTextNode(te))}}};if(!S)if(u&&E!=="none"){let le=(Ee=o.loadingAnimationDuration)!=null?Ee:2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${le}ms`),y&&M(y,!1);else if(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${le}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 Q=m.textContent||c;m.textContent="",b(m,Q,0)}}else y&&M(y,!1);let W=null;if(s){W=A("div","persona-flex persona-items-center");let le=o.toggleTextColor||o.headerTextColor||"currentColor",Q=ve(i?"chevron-up":"chevron-down",16,le,2);Q?W.appendChild(Q):W.textContent=i?"Hide":"Show";let ie=A("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ie.append(W),g.append(p,ie)}else g.append(p);let R=A("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","tool"),R.style.display="none",R.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&d){let le=(De=o.renderCollapsedPreview)==null?void 0:De.call(o,{message:e,toolCall:r,defaultPreview:d,isActive:u,config:t!=null?t:{}});jb(R,le)||(R.textContent=d),R.style.display=""}if(!i&&u&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(g,R),n;let L=A("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(L.style.display=i?"":"none",o.contentBackgroundColor&&(L.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(L.style.color=o.contentTextColor),o.contentPaddingX&&(L.style.paddingLeft=o.contentPaddingX,L.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(L.style.paddingTop=o.contentPaddingY,L.style.paddingBottom=o.contentPaddingY),r.name){let le=A("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?le.style.color=o.contentTextColor:o.headerTextColor&&(le.style.color=o.headerTextColor),le.textContent=r.name,L.appendChild(le)}if(r.args!==void 0){let le=A("div","persona-space-y-1"),Q=A("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Q.style.color=o.labelTextColor),Q.textContent="Arguments";let ie=A("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(ie.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(ie.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(ie.style.color=o.codeBlockTextColor),ie.textContent=Fa(r.args),le.append(Q,ie),L.appendChild(le)}if(r.chunks&&r.chunks.length){let le=A("div","persona-space-y-1"),Q=A("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Q.style.color=o.labelTextColor),Q.textContent="Activity";let ie=A("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(ie.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(ie.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(ie.style.color=o.codeBlockTextColor),ie.textContent=r.chunks.join(""),le.append(Q,ie),L.appendChild(le)}if(r.status==="complete"&&r.result!==void 0){let le=A("div","persona-space-y-1"),Q=A("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Q.style.color=o.labelTextColor),Q.textContent="Result";let ie=A("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(ie.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(ie.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(ie.style.color=o.codeBlockTextColor),ie.textContent=Fa(r.result),le.append(Q,ie),L.appendChild(le)}if(r.status==="complete"&&typeof r.duration=="number"){let le=A("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(le.style.color=o.contentTextColor),le.textContent=`Duration: ${r.duration}ms`,L.appendChild(le)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let le=o.toggleTextColor||o.headerTextColor||"currentColor",Q=ve(i?"chevron-up":"chevron-down",16,le,2);Q?W.appendChild(Q):W.textContent=i?"Hide":"Show"}L.style.display=i?"":"none",R.style.display=i?"none":R.textContent||R.childNodes.length?"":"none"})(),n.append(g,R,L),n};var Cl=new Map,Xb=e=>{let r=(e.startsWith(tn)?e.slice(tn.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)},Fh=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Nh=(e,t)=>{var o,n,a;let r=(n=(o=Fh(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=Cl.get(e))!=null?a:r==="expanded"},Oh=(e,t,r)=>{var s,i;let o=Fh(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=ve(t?"chevron-up":"chevron-down",14,"currentColor",2);c&&a.appendChild(c)}},_h=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=Nh(e,r);Oh(o,a,r),n.style.display=a?"":"none"};var wl=(e,t)=>{var M,W,R,L,N,q,Y,me,Ge,Ce,Be,qe,Ee,De,le;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=A("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=(W=o==null?void 0:o.borderColor)!=null?W:"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=A("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=A("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",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)":(R=o==null?void 0:o.titleColor)!=null?R:"currentColor",u=ve(c,20,d,2);u&&i.appendChild(u);let g=A("div","persona-flex-1 persona-min-w-0"),p=A("div","persona-flex persona-items-center persona-gap-2"),m=A("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(L=o==null?void 0:o.title)!=null?L:"Approval Required",p.appendChild(m),!n){let Q=A("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"),p.appendChild(Q)}g.appendChild(p);let C=r.toolType==="webmcp"||r.toolName.startsWith(tn)?Gl(r.toolName):void 0,T=(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}:{}}),E=!r.toolName,w=T||(E?r.description:`The assistant wants to use \u201C${C!=null?C:Xb(r.toolName)}\u201D.`),k=A("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(k.style.color=o.descriptionColor),k.textContent=w,g.appendChild(k),r.reason){let Q=A("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 ie=A("span","persona-font-medium");ie.textContent=`${(q=o==null?void 0:o.reasonLabel)!=null?q:"Agent's stated reason:"} `,Q.appendChild(ie),Q.appendChild(document.createTextNode(r.reason)),g.appendChild(Q)}let y=(Y=o==null?void 0:o.detailsDisplay)!=null?Y:"collapsed",S=!!r.description&&!E,b=S||!!r.parameters;if(y!=="hidden"&&b){let Q=Nh(e.id,t),ie=A("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");ie.type="button",ie.setAttribute("data-expand-header","true"),ie.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(ie.style.color=o.descriptionColor);let ge=A("span");ge.setAttribute("data-approval-details-label","true");let ue=A("span","persona-inline-flex persona-items-center");ue.setAttribute("data-approval-details-chevron","true"),ie.append(ge,ue),Oh(ie,Q,t),g.appendChild(ie);let j=A("div");if(j.setAttribute("data-approval-details","true"),j.style.display=Q?"":"none",S){let de=A("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(de.style.color=o.descriptionColor),de.textContent=r.description,j.appendChild(de)}if(r.parameters){let de=A("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&&(de.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(de.style.color=o.parameterTextColor),de.style.fontSize="0.75rem",de.style.lineHeight="1rem",de.textContent=Fa(r.parameters),j.appendChild(de)}g.appendChild(j)}if(n){let Q=A("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let ie=A("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");ie.type="button",ie.style.backgroundColor=(me=o==null?void 0:o.approveButtonColor)!=null?me:"var(--persona-approval-approve-bg, #22c55e)",ie.style.color=(Ge=o==null?void 0:o.approveButtonTextColor)!=null?Ge:"#ffffff",ie.setAttribute("data-approval-action","approve");let ge=ve("shield-check",14,(Ce=o==null?void 0:o.approveButtonTextColor)!=null?Ce:"#ffffff",2);ge&&(ge.style.marginRight="4px",ie.appendChild(ge));let ue=document.createTextNode((Be=o==null?void 0:o.approveLabel)!=null?Be:"Approve");ie.appendChild(ue);let j=A("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");j.type="button",j.style.backgroundColor=(qe=o==null?void 0:o.denyButtonColor)!=null?qe:"transparent",j.style.color=(Ee=o==null?void 0:o.denyButtonTextColor)!=null?Ee:"var(--persona-feedback-error, #dc2626)",j.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,j.setAttribute("data-approval-action","deny");let de=ve("shield-x",14,(De=o==null?void 0:o.denyButtonTextColor)!=null?De:"var(--persona-feedback-error, #dc2626)",2);de&&(de.style.marginRight="4px",j.appendChild(de));let Ne=document.createTextNode((le=o==null?void 0:o.denyLabel)!=null?le:"Deny");j.appendChild(Ne),Q.append(ie,j),g.appendChild(Q)}return s.append(i,g),a.appendChild(s),a};var Uh=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,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(T=>T.role==="user"))return;let g=document.createDocumentFragment(),p=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=A("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=p,c!=null&&c.fontFamily&&(C.style.fontFamily=m(c.fontFamily)),c!=null&&c.fontWeight&&(C.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(C.style.paddingLeft=c.paddingX,C.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(C.style.paddingTop=c.paddingY,C.style.paddingBottom=c.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 Us=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 qs=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 Qb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Jb=new Set(["step_start","execution_start"]),Yb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Zb=new Set(["step_complete","agent_turn_complete"]),ev=new Set(["flow_complete","agent_complete"]),qh=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),$h=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),so=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,fa=(e,t)=>{let r=e[t];return $h(r)?r:void 0};function kp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Sl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function tv(e,t){return typeof t.type=="string"?t.type:e}function rv(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 ov(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 Vh(e){var o,n,a,s,i;let t=fa(e,"result"),r=[fa(e,"tokens"),fa(e,"totalTokens"),t?fa(t,"tokens"):void 0,fa(e,"usage"),t?fa(t,"usage"):void 0];for(let c of r){if(!c)continue;let d=(n=(o=so(c.output))!=null?o:so(c.outputTokens))!=null?n:so(c.completionTokens);if(d!==void 0)return d}return(i=(a=so(e.outputTokens))!=null?a:so(e.completionTokens))!=null?i:t?(s=so(t.outputTokens))!=null?s:so(t.completionTokens):void 0}function nv(e){var r,o,n,a,s;let t=fa(e,"result");return(s=(n=(o=(r=so(e.executionTime))!=null?r:so(e.executionTimeMs))!=null?o:so(e.execution_time))!=null?n:so(e.duration))!=null?s:t?(a=so(t.executionTime))!=null?a:so(t.executionTimeMs):void 0}function av(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Vs=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:Sl(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(!$h(r)){qh.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=tv(t,r),n=this.now();if(Qb.has(o)){this.startRun(n);return}if(Jb.has(o)){this.run||this.startRun(n);return}if(Yb.has(o)){if(!ov(o,r))return;let s=rv(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+kp(i.visibleCharCount),d=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Sl(c,d),outputTokens:c,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Zb.has(o)){if(!this.run)return;let s=this.run,i=Vh(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,d=s.exactOutputTokens+kp(s.visibleCharCount),u=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:Sl(d,u),outputTokens:d,durationMs:u,source:c?"usage":"estimate"};return}if(ev.has(o)){if(!this.run)return;let s=this.run,i=Vh(r),c=i!=null?i:s.exactOutputTokens+kp(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:Sl(c,u),outputTokens:c,durationMs:u,source:d},this.run=null;return}if(qh.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=nv(r);return a!=null?a:o-t.startedAt}};function Xa(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var sv={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)"}},iv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},lv=["flowName","stepName","reasoningText","text","name","tool","toolName"],dv=100;function cv(e,t){let r={...sv,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return iv}function pv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function uv(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 fv(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 mv(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 gv(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 hv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function xv(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 yv(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=A("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=A("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 Lp(e,t,r,o,n,a,s,i){var p;let c=n.has(e.id),d=A("div","persona-border-b persona-border-persona-divider persona-text-xs");Xa(d,(p=o.classNames)==null?void 0:p.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:c,onToggleExpand:()=>a(e.id)});if(m)return d.appendChild(m),d}return d.appendChild(g()),d;function g(){var q,Y;let m=A("div",""),x=A("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=A("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=ve(c?"chevron-down":"chevron-right","14px","currentColor",2);T&&C.appendChild(T);let E=A("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),w=(q=o.timestampFormat)!=null?q:"relative";E.textContent=w==="relative"?pv(e.timestamp,r):uv(e.timestamp);let k=null;o.showSequenceNumbers!==!1&&(k=A("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let y=cv(e.type,o.badgeColors),S=A("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 b=(Y=o.descriptionFields)!=null?Y:lv,M=fv(e.payload,b),W=null;M&&(W=A("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=M);let R=A("div","persona-flex-1 persona-min-w-0"),L=A("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=ve("clipboard","12px","currentColor",1.5);return N&&L.appendChild(N),L.addEventListener("click",async me=>{me.stopPropagation(),await mv(gv(e)),L.innerHTML="";let Ge=ve("check","12px","currentColor",1.5);Ge&&L.appendChild(Ge),setTimeout(()=>{L.innerHTML="";let Ce=ve("clipboard","12px","currentColor",1.5);Ce&&L.appendChild(Ce)},1500)}),x.appendChild(C),x.appendChild(E),k&&x.appendChild(k),x.appendChild(S),W&&x.appendChild(W),x.appendChild(R),x.appendChild(L),m.appendChild(x),c&&m.appendChild(yv(e,s,i)),m}}function zh(e){var x,C,T,E,w;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,d=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",u=(T=i==null?void 0:i.label)!=null?T:"",g=(w=(E=n==null?void 0:n.features)==null?void 0:E.eventStream)!=null?w:{},p=a.find(k=>k.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&n){let k=p.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return m();function m(){let k=g.classNames,y=A("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Xa(y,k==null?void 0:k.panel);let S=[],b="",M="",W=null,R=[],L={},N=0,q=al(),Y=0,me=0,Ge=!1,Ce=null,Be=!1,qe=0,Ee=new Set,De=new Map,le="",Q="",ie=null,ge,ue,j,de,Ne,te=null,Z=null,ae=null;function wt(){let se=A("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),pe=A("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");Xa(pe,k==null?void 0:k.headerBar);let Ae=A("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ae.textContent="Events",ge=A("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"),ge.textContent="0",s){Z=A("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),Z.style.cursor="help";let io=A("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");io.textContent="Throughput",te=A("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"),te.textContent="-- tok/s",ae=A("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ae.style.display="none",ae.style.pointerEvents="none";let Wr=Z,lr=ae,qr=()=>{if(!lr.textContent)return;let vt=Wr.getBoundingClientRect(),Gr=se.getBoundingClientRect();lr.style.left=`${vt.left-Gr.left}px`,lr.style.top=`${vt.bottom-Gr.top+4}px`,lr.style.display="block"},Eo=()=>{lr.style.display="none"};Z.addEventListener("mouseenter",qr),Z.addEventListener("mouseleave",Eo),Z.appendChild(io),Z.appendChild(te)}let dt=A("div","persona-flex-1");ue=A("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 er=A("option","");er.value="",er.textContent="All events",ue.appendChild(er),j=A("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"),j.type="button",j.title="Copy All";let Sr=ve("clipboard-copy","12px","currentColor",1.5);Sr&&j.appendChild(Sr);let _t=A("span","persona-text-xs");_t.textContent="Copy All",j.appendChild(_t),pe.appendChild(Ae),pe.appendChild(ge),Z&&pe.appendChild(Z),pe.appendChild(dt),pe.appendChild(ue),pe.appendChild(j);let et=A("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Xa(et,k==null?void 0:k.searchBar);let Ot=ve("search","14px","var(--persona-muted, #9ca3af)",1.5),ct=A("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ot&&ct.appendChild(Ot),de=A("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"),Xa(de,k==null?void 0:k.searchInput),de.type="text",de.placeholder="Search event payloads...",Ne=A("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"),Ne.type="button",Ne.style.display="none";let tr=ve("x","12px","currentColor",2);return tr&&Ne.appendChild(tr),et.appendChild(ct),et.appendChild(de),et.appendChild(Ne),se.appendChild(pe),se.appendChild(et),ae&&se.appendChild(ae),se}let Pt,xt=a.find(se=>se.renderEventStreamToolbar);if(xt!=null&&xt.renderEventStreamToolbar&&n){let se=xt.renderEventStreamToolbar({config:n,defaultRenderer:()=>wt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:pe=>{b=pe,Ft(),Tr()},onSearchChange:pe=>{M=pe,Ft(),Tr()}});Pt=se!=null?se:wt()}else Pt=wt();let Ue=A("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");Ue.style.display="none";function be(){if(!s||!te||!Z)return;let se=s();te.textContent=hv(se);let pe=xv(se);ae&&(ae.textContent=pe,pe||(ae.style.display="none")),pe?Z.setAttribute("aria-label",pe):Z.removeAttribute("aria-label")}let Je=A("div","persona-flex-1 persona-min-h-0 persona-relative"),J=A("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ce=A("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");Xa(ce,k==null?void 0:k.scrollIndicator),ce.style.display="none",ce.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let Te=ve(d,"14px","currentColor",2);Te&&ce.appendChild(Te);let Xe=A("span","");Xe.textContent=u,ce.appendChild(Xe);let Kt=A("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Kt.style.display="none",Je.appendChild(J),Je.appendChild(Kt),Je.appendChild(ce),y.setAttribute("tabindex","0"),y.appendChild(Pt),y.appendChild(Ue),y.appendChild(Je);function ke(){let se=t.getAll(),pe={};for(let _t of se)pe[_t.type]=(pe[_t.type]||0)+1;let Ae=Object.keys(pe).sort(),dt=Ae.length!==R.length||!Ae.every((_t,et)=>_t===R[et]),er=!dt&&Ae.some(_t=>pe[_t]!==L[_t]),ir=se.length!==Object.values(L).reduce((_t,et)=>_t+et,0);if(!dt&&!er&&!ir||(R=Ae,L=pe,!ue))return;let Sr=ue.value;if(ue.options[0].textContent="All events",dt){for(;ue.options.length>1;)ue.remove(1);for(let _t of Ae){let et=A("option","");et.value=_t,et.textContent=`${_t} (${pe[_t]||0})`,ue.appendChild(et)}Sr&&Ae.includes(Sr)?ue.value=Sr:Sr&&(ue.value="",b="")}else for(let _t=1;_t<ue.options.length;_t++){let et=ue.options[_t];et.textContent=`${et.value} (${pe[et.value]||0})`}}function Ve(){let se=t.getAll();if(b&&(se=se.filter(pe=>pe.type===b)),M){let pe=M.toLowerCase();se=se.filter(Ae=>Ae.type.toLowerCase().includes(pe)||Ae.payload.toLowerCase().includes(pe))}return se}function rt(){return b!==""||M!==""}function Ft(){N=0,Y=0,q.resume(),ce.style.display="none"}function vr(se){Ee.has(se)?Ee.delete(se):Ee.add(se),ie=se;let pe=J.scrollTop,Ae=q.isFollowing();Be=!0,q.pause(),Tr(),J.scrollTop=pe,Ae&&q.resume(),Be=!1}function To(){return da(J,50)}function Tr(){me=Date.now(),Ge=!1,be(),ke();let se=t.getEvictedCount();se>0?(Ue.textContent=`${se.toLocaleString()} older events truncated`,Ue.style.display=""):Ue.style.display="none",S=Ve();let pe=S.length,Ae=t.getSize()>0;ge&&(ge.textContent=String(t.getSize())),pe===0&&Ae&&rt()?(Kt.textContent=M?`No events matching '${M}'`:"No events matching filter",Kt.style.display="",J.style.display="none"):(Kt.style.display="none",J.style.display=""),j&&(j.title=rt()?`Copy Filtered (${pe})`:"Copy All"),c&&!q.isFollowing()&&pe>N&&(Y+=pe-N,Xe.textContent=u?`${u}${Y>0?` (${Y})`:""}`:"",ce.style.display=""),N=pe;let dt=t.getAll(),er=dt.length>0?dt[0].timestamp:0,ir=new Set(S.map(et=>et.id));for(let et of Ee)ir.has(et)||Ee.delete(et);let Sr=b!==le||M!==Q,_t=De.size===0&&S.length>0;if(Sr||_t||S.length===0){J.innerHTML="",De.clear();let et=document.createDocumentFragment();for(let Ot=0;Ot<S.length;Ot++){let ct=Lp(S[Ot],Ot,er,g,Ee,vr,a,n);De.set(S[Ot].id,ct),et.appendChild(ct)}J.appendChild(et),le=b,Q=M,ie=null}else{if(ie!==null){let Ot=De.get(ie);if(Ot&&Ot.parentNode===J){let ct=S.findIndex(tr=>tr.id===ie);if(ct>=0){let tr=Lp(S[ct],ct,er,g,Ee,vr,a,n);J.insertBefore(tr,Ot),Ot.remove(),De.set(ie,tr)}}ie=null}let et=new Set(S.map(Ot=>Ot.id));for(let[Ot,ct]of De)et.has(Ot)||(ct.remove(),De.delete(Ot));for(let Ot=0;Ot<S.length;Ot++){let ct=S[Ot];if(!De.has(ct.id)){let tr=Lp(ct,Ot,er,g,Ee,vr,a,n);De.set(ct.id,tr),J.appendChild(tr)}}}q.isFollowing()&&(J.scrollTop=J.scrollHeight)}function je(){if(Date.now()-me>=dv){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Tr();return}Ge||(Ge=!0,Ce=requestAnimationFrame(()=>{Ce=null,Tr()}))}let Nt=(se,pe)=>{if(!j)return;j.innerHTML="";let Ae=ve(se,"12px","currentColor",1.5);Ae&&j.appendChild(Ae);let dt=A("span","persona-text-xs");dt.textContent="Copy All",j.appendChild(dt),setTimeout(()=>{j.innerHTML="";let er=ve("clipboard-copy","12px","currentColor",1.5);er&&j.appendChild(er);let ir=A("span","persona-text-xs");ir.textContent="Copy All",j.appendChild(ir),j.disabled=!1},pe)},V=async()=>{if(j){j.disabled=!0;try{let se;rt()?se=S:r?(se=await r(),se.length===0&&(se=t.getAll())):se=t.getAll();let pe=se.map(Ae=>{try{return JSON.parse(Ae.payload)}catch{return Ae.payload}});await navigator.clipboard.writeText(JSON.stringify(pe,null,2)),Nt("check",1500)}catch{Nt("x",1500)}}},Me=()=>{ue&&(b=ue.value,Ft(),Tr())},we=()=>{!de||!Ne||(Ne.style.display=de.value?"":"none",W&&clearTimeout(W),W=setTimeout(()=>{M=de.value,Ft(),Tr()},150))},He=()=>{!de||!Ne||(de.value="",M="",Ne.style.display="none",W&&clearTimeout(W),Ft(),Tr())},nt=()=>{if(Be)return;let se=J.scrollTop,{action:pe,nextLastScrollTop:Ae}=sl({following:q.isFollowing(),currentScrollTop:se,lastScrollTop:qe,nearBottom:To(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});qe=Ae,pe==="resume"?(q.resume(),Y=0,ce.style.display="none"):pe==="pause"&&(q.pause(),c&&(Xe.textContent=u,ce.style.display=""))},lt=se=>{let pe=il({following:q.isFollowing(),deltaY:se.deltaY,nearBottom:To(),resumeWhenNearBottom:!0});pe==="pause"?(q.pause(),c&&(Xe.textContent=u,ce.style.display="")):pe==="resume"&&(q.resume(),Y=0,ce.style.display="none")},ot=()=>{c&&(J.scrollTop=J.scrollHeight,q.resume(),Y=0,ce.style.display="none")},Tt=se=>{let pe=se.target;if(!pe||pe.closest("button"))return;let Ae=pe.closest("[data-event-id]");if(!Ae)return;let dt=Ae.getAttribute("data-event-id");dt&&vr(dt)},z=se=>{if((se.metaKey||se.ctrlKey)&&se.key==="f"){se.preventDefault(),de==null||de.focus(),de==null||de.select();return}se.key==="Escape"&&(de&&document.activeElement===de?(He(),de.blur(),y.focus()):o&&o())};j&&j.addEventListener("click",V),ue&&ue.addEventListener("change",Me),de&&de.addEventListener("input",we),Ne&&Ne.addEventListener("click",He),J.addEventListener("scroll",nt),J.addEventListener("wheel",lt,{passive:!0}),J.addEventListener("click",Tt),ce.addEventListener("click",ot),y.addEventListener("keydown",z);function St(){W&&clearTimeout(W),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ge=!1,De.clear(),j&&j.removeEventListener("click",V),ue&&ue.removeEventListener("change",Me),de&&de.removeEventListener("input",we),Ne&&Ne.removeEventListener("click",He),J.removeEventListener("scroll",nt),J.removeEventListener("wheel",lt),J.removeEventListener("click",Tt),ce.removeEventListener("click",ot),y.removeEventListener("keydown",z)}return{element:y,update:je,destroy:St}}}function jh(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 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 p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #171717)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(p);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,g.appendChild(m)}else g.textContent=s;if(d.append(u,g),i.append(c,d),n==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${r}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",o),i.append(p)}return i}var Gh=(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",d=typeof e.artifactType=="string"?e.artifactType:"markdown",u=r({artifact:{artifactId:i,title:s,artifactType:d,status:c},config:t.config,defaultRenderer:()=>jh(e,t)});if(u)return u}return jh(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)})}},dn=new Pp;dn.register("PersonaArtifactCard",Gh);function bv(e){var n;let t=A("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=A("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let o=A("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 Kh(e,t){var ue,j,de,Ne;let r=(j=(ue=e.features)==null?void 0:ue.artifacts)==null?void 0:j.layout,n=((de=r==null?void 0:r.toolbarPreset)!=null?de:"default")==="document",a=(Ne=r==null?void 0:r.panePadding)==null?void 0:Ne.trim(),s=e.markdown?Zn(e.markdown):null,i=Ra(e.sanitize),c=te=>{let Z=s?s(te):Uo(te);return i?i(Z):Z},d=typeof document!="undefined"?A("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 te;u(),(te=t.onDismiss)==null||te.call(t)});let g=A("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 p=A("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");p.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&p.classList.add("persona-artifact-toolbar-document");let m=A("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=A("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 te;u(),(te=t.onDismiss)==null||te.call(t)});let C="rendered",T=A("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=n?br({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):br({icon:"eye",label:"Rendered view"}),w=n?br({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):br({icon:"code-2",label:"Source"}),k=A("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,b=r==null?void 0:r.documentToolbarCopyMenuItems,M=!!(S&&b&&b.length>0),W=null,R,L=null,N=null;if(n&&(y||S)&&!M){if(R=y?_s({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):br({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),S){let te=ve("chevron-down",14,"currentColor",2);te&&R.appendChild(te)}}else n&&M?(W=A("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),R=y?_s({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):br({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L=br({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"}}),W.append(R,L)):n?R=br({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):R=br({icon:"copy",label:"Copy"});let q=n?br({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):br({icon:"refresh-cw",label:"Refresh"}),Y=n?br({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):br({icon:"x",label:"Close"}),me=()=>{var Pt,xt,Ue;let te=(Pt=De.find(be=>be.id===le))!=null?Pt:De[De.length-1],Z=(xt=te==null?void 0:te.id)!=null?xt:null,ae=(te==null?void 0:te.artifactType)==="markdown"&&(Ue=te.markdown)!=null?Ue:"",wt=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:ae,jsonPayload:wt,id:Z}},Ge=async()=>{var Pt;let{markdown:te,jsonPayload:Z}=me(),ae=(Pt=De.find(xt=>xt.id===le))!=null?Pt:De[De.length-1],wt=(ae==null?void 0:ae.artifactType)==="markdown"?te:ae?Z:"";try{await navigator.clipboard.writeText(wt)}catch{}};if(R.addEventListener("click",async()=>{let te=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(te&&M){let{markdown:Z,jsonPayload:ae,id:wt}=me();try{await te({actionId:"primary",artifactId:wt,markdown:Z,jsonPayload:ae})}catch{}return}await Ge()}),L&&(b!=null&&b.length)){let te=()=>{var ae;return(ae=g.closest("[data-persona-root]"))!=null?ae:document.body},Z=()=>{N=Fn({items:b.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:wt,jsonPayload:Pt,id:xt}=me(),Ue=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{Ue?await Ue({actionId:ae,artifactId:xt,markdown:wt,jsonPayload:Pt}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(wt):ae==="json"||ae==="source"?await navigator.clipboard.writeText(Pt):await navigator.clipboard.writeText(wt||Pt)}catch{}},anchor:W!=null?W:L,position:"bottom-right",portal:te()})};g.isConnected?Z():requestAnimationFrame(Z),L.addEventListener("click",ae=>{ae.stopPropagation(),N==null||N.toggle()})}q.addEventListener("click",async()=>{var te;try{await((te=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:te.call(r))}catch{}ie()}),Y.addEventListener("click",()=>{var te;u(),(te=t.onDismiss)==null||te.call(t)});let Ce=()=>{n&&(E.setAttribute("aria-pressed",C==="rendered"?"true":"false"),w.setAttribute("aria-pressed",C==="source"?"true":"false"))};E.addEventListener("click",()=>{C="rendered",Ce(),ie()}),w.addEventListener("click",()=>{C="source",Ce(),ie()});let Be=A("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?(p.replaceChildren(),T.append(E,w),W?k.append(W,q,Y):k.append(R,q,Y),p.append(T,Be,k),Ce()):(p.appendChild(m),p.appendChild(x)),a&&(p.style.paddingLeft=a,p.style.paddingRight=a);let qe=A("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=A("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(p),g.appendChild(qe),g.appendChild(Ee);let De=[],le=null,Q=!1,ie=()=>{var wt,Pt,xt,Ue;let te=n&&De.length<=1;qe.classList.toggle("persona-hidden",te),qe.replaceChildren();for(let be of De){let Je=A("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");Je.type="button",Je.textContent=be.title||be.id.slice(0,8),be.id===le&&Je.classList.add("persona-bg-persona-container","persona-border-persona-border"),Je.addEventListener("click",()=>t.onSelect(be.id)),qe.appendChild(Je)}Ee.replaceChildren();let Z=le&&De.find(be=>be.id===le)||De[De.length-1];if(!Z)return;if(n){let be=Z.artifactType==="markdown"?"MD":(wt=Z.component)!=null?wt:"Component",J=(Z.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Be.textContent=`${J} \xB7 ${be}`}else m.textContent="Artifacts";if(Z.artifactType==="markdown"){if(n&&C==="source"){let Je=A("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Je.textContent=(Pt=Z.markdown)!=null?Pt:"",Ee.appendChild(Je);return}let be=A("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");be.innerHTML=c((xt=Z.markdown)!=null?xt:""),Ee.appendChild(be);return}let ae=Z.component?dn.get(Z.component):void 0;if(ae){let Je={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let J=ae((Ue=Z.props)!=null?Ue:{},Je);if(J){Ee.appendChild(J);return}}catch{}}Ee.appendChild(bv(Z))},ge=()=>{var Z;let te=De.length>0;if(g.classList.toggle("persona-hidden",!te),d){let ae=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,Pt=((Z=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?Z:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&Pt&&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(te){var Z,ae,wt;De=te.artifacts,le=(wt=(ae=te.selectedId)!=null?ae:(Z=te.artifacts[te.artifacts.length-1])==null?void 0:Z.id)!=null?wt:null,De.length>0&&(Q=!0),ie(),ge()},setMobileOpen(te){Q=te,!te&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):ge()}}}function ho(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 Xh(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"),!ho(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 vv(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 Al(e,t){var c,d,u,g,p,m,x,C,T,E;if(!ho(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"),vv(e),Xh(e,t);return}let r=(d=(c=t.features)==null?void 0:c.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",(p=r==null?void 0:r.paneMaxWidth)!=null?p:"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=(T=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:T.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"),Xh(e,t)}var Qh=["panel","seamless"];function Ml(e,t){var i,c,d,u,g,p;for(let m of Qh)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"),!ho(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(d=r==null?void 0:r.paneAppearance)!=null?d:"panel",n=Qh.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=((p=r.unifiedSplitOuterRadius)==null?void 0:p.trim())||a;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Jh(e,t){var r,o,n;return!t||!ho(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function Cv(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 wv(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 Sv(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function Av(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function Yh(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 Zh(e,t,r,o,n,a){let s=Cv(n,200),i=Av(t,r,o,200);i=Math.max(s,i);let c=wv(a);return c!==null&&(i=Math.min(i,c)),Sv(e,s,i)}var ex={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"}},Ip=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var x,C,T;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(C=ex[s])!=null?C:ex.init;a.classList.add("persona-form-card","persona-space-y-4");let c=A("div","persona-space-y-1"),d=A("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,c.appendChild(d),i.description){let E=A("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,c.appendChild(E)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var b,M;let w=A("label","persona-form-field persona-flex persona-flex-col persona-gap-1");w.htmlFor=`${t.id}-${s}-${E.name}`;let k=A("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=E.label,w.appendChild(k);let y=(b=E.type)!=null?b:"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),w.appendChild(S),u.appendChild(w)});let g=A("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),p=A("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=A("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=(T=i.submitLabel)!=null?T:"Submit",g.appendChild(p),g.appendChild(m),u.appendChild(g),a.replaceChildren(c,u),u.addEventListener("submit",async E=>{var S,b;E.preventDefault();let w=(S=r.formEndpoint)!=null?S:"/form",k=new FormData(u),y={};k.forEach((M,W)=>{y[W]=M}),y.type=s,m.disabled=!0,p.textContent="Submitting\u2026";try{let M=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let W=await M.json();p.textContent=(b=W.message)!=null?b:"Thanks! We'll be in touch soon.",W.success&&W.nextPrompt&&await o.sendMessage(String(W.nextPrompt))}catch(M){p.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Rp=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()}},$s=new Rp;var tx=()=>{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 Mv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Tv=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},zs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Mv(e),r=Tv(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}},Wp=e=>typeof e=="string"?e:e==null?"":String(e),ma={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Wp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=Wp(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:Wp(r.text)}}},rx=e=>Array.isArray(e)?e.map(t=>String(t)):[],js=e=>{let t=new Set(rx(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(rx(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 c={action:i,message:a.message};e.emit("action:detected",c);for(let d of e.handlers)if(d)try{let u=()=>{e.emit("action:resubmit",c)},g=d(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let p=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:p,resubmit:g.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:r}};var Ev=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}},kv=e=>e.map(t=>({...t,streaming:!1})),Lv=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?Ev(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?kv(r.messages):void 0,artifacts:r.artifacts?Lv(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 Qa=La(vi(),1);function Pv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Iv(e,t){if(!Pv(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 El(){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,Qa.parse)(r,Qa.STR|Qa.OBJ),a=Iv(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function ox(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function kl(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=dn.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 nx(){let e=El();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ax(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 Ll(e){let t=ax(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 Pl(e){let t=ax(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 Rv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Il(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:d=Rv}=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,p=document.createElement("div");p.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),p.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let b=1;b<=5;b++){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",`${b} star${b>1?"s":""}: ${d[b-1]}`),M.title=d[b-1],M.dataset.rating=String(b),M.innerHTML=`
30
30
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
31
31
  <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
32
  </svg>
33
- `,A.addEventListener("click",()=>{g=b,E.forEach((H,W)=>{let k=W<b;H.classList.toggle("selected",k),H.setAttribute("aria-checked",W===b-1?"true":"false")})}),E.push(A),T.appendChild(A)}p.appendChild(T);let M=null;if(c){let b=document.createElement("div");b.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"),b.appendChild(M),p.appendChild(b)}let P=document.createElement("div");P.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){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let b=(M==null?void 0:M.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)}}),P.appendChild(y),P.appendChild(w),p.appendChild(P),u.appendChild(p),u}function Pl(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: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 p=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 T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=n,x.appendChild(T),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 M=document.createElement("div");M.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=d;let y=document.createElement("span");y.className="persona-feedback-label-high",y.textContent=u,M.appendChild(P),M.appendChild(y);let w=document.createElement("div");w.className="persona-feedback-numbers";let b=[];for(let N=0;N<=10;N++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${N} out of 10`),q.textContent=String(N),q.dataset.rating=String(N),N<=6?q.classList.add("persona-feedback-detractor"):N<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{p=N,b.forEach((Z,me)=>{Z.classList.toggle("selected",me===N),Z.setAttribute("aria-checked",me===N?"true":"false")})}),b.push(q),w.appendChild(q)}E.appendChild(M),E.appendChild(w),m.appendChild(E);let A=null;if(c){let N=document.createElement("div");N.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"),N.appendChild(A),m.appendChild(N)}let H=document.createElement("div");H.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=i,W.addEventListener("click",()=>{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(p===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=(A==null?void 0:A.value.trim())||void 0;await t(p,N),g.remove()}catch(N){k.disabled=!1,k.textContent=s,console.error("[NPS Feedback] Failed to submit:",N)}}),H.appendChild(W),H.appendChild(k),m.appendChild(H),g.appendChild(m),g}var Ya="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 c=(n=Rv[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 Rl(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,c,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:(c=(i=e.persist)==null?void 0:i.focusInput)!=null?c:!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 Ip=e=>!e||typeof e!="object"?{}:{...e},ox=e=>e.map(t=>({...t,streaming:!1})),nx=(e,t,r)=>{let o=e!=null&&e.markdown?Zn(e.markdown):null,n=Wa(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 d,u,g;let s=(d=a.text)!=null?d:"",i=(u=a.message.rawContent)!=null?u:null;if(t){let p=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});p!==null&&(s=p.text,p.persist||(a.message.__skipPersist=!0),p.resubmit&&!a.streaming&&r&&r())}let c;return e!=null&&e.postprocessMessage?c=e.postprocessMessage({...a,text:s,raw:(g=i!=null?i:a.text)!=null?g:""}):o?c=o(s):c=qo(s),n?n(c):c}};function ax(e){var i,c,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=(c=e==null?void 0:e.iconSize)!=null?c:"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=ve(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 Il=(e,t,r)=>{var 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,$u,zu,ju,Gu,Ku,Xu,Qu,Ju,Yu,Zu,ef,tf,rf,of,nf,af,sf,lf,df;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=Ji(t),n=zs.getForInstance(o.plugins);o.components&&dn.registerAll(o.components);let a=Yh(),i=o.persistState===!1?null:(fu=o.storageAdapter)!=null?fu:Al(),c={},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&&(c=Ip(h.metadata)),(mu=h.messages)!=null&&mu.length&&(o={...o,initialMessages:h.messages}),(gu=h.artifacts)!=null&&gu.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(hu=h.selectedArtifactId)!=null?hu: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:{}});(xu=l.messages)!=null&&xu.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>c,m=l=>{var h;c=(h=l({...c}))!=null?h:{},wa()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[js],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ma.message,ma.messageAndClick],T=Gs({parsers:x,handlers:C,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let E=(bu=(yu=o.launcher)==null?void 0:yu.enabled)!=null?bu:!0,M=(Cu=(vu=o.launcher)==null?void 0:vu.autoExpand)!=null?Cu:!1,P=(wu=o.autoFocusInput)!=null?wu:!1,y=M,w=E,b=(Au=(Su=o.layout)==null?void 0:Su.header)==null?void 0:Au.layout,A=!1,H=()=>Dn(o),W=()=>E||H(),k=H()?!1:E?M:!0,N=!1,q=null,Z=()=>{N=!0,q&&clearTimeout(q),q=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},me=nx(o,T,Z),Ke=(Tu=(Mu=o.features)==null?void 0:Mu.showReasoning)!=null?Tu:!0,Ce=(ku=(Eu=o.features)==null?void 0:Eu.showToolCalls)!=null?ku:!0,Ie=(Pu=(Lu=o.features)==null?void 0:Lu.showEventStreamToggle)!=null?Pu:!1,Ue=(Iu=(Ru=o.features)==null?void 0:Ru.scrollToBottom)!=null?Iu:{},Te=(Hu=(Wu=o.features)==null?void 0:Wu.scrollBehavior)!=null?Hu:{},de=`${(Du=typeof o.persistState=="object"?(Bu=o.persistState)==null?void 0:Bu.keyPrefix:void 0)!=null?Du:"persona-"}event-stream`,J=Ie?new Vs(de):null,le=(Ou=(Nu=(Fu=o.features)==null?void 0:Fu.eventStream)==null?void 0:Nu.maxEvents)!=null?Ou:2e3,ge=Ie?new qs(le,J):null,ue=Ie?new $s:null,G=null,ce=!1,Be=null,ne=0;J==null||J.open().then(()=>ge==null?void 0:ge.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ee={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)}},ie=(_u=o.statusIndicator)!=null?_u:{},vt=l=>{var f,h,v,R;return l==="idle"?(f=ie.idleText)!=null?f:kr.idle:l==="connecting"?(h=ie.connectingText)!=null?h:kr.connecting:l==="connected"?(v=ie.connectedText)!=null?v:kr.connected:l==="error"?(R=ie.errorText)!=null?R:kr.error:kr[l]};function Lt(l,f,h,v){if(v==="idle"&&h.idleLink){l.textContent="";let R=document.createElement("a");R.href=h.idleLink,R.target="_blank",R.rel="noopener noreferrer",R.textContent=f,R.style.color="inherit",R.style.textDecoration="none",l.appendChild(R)}else l.textContent=f}let gt=kh({config:o,showClose:W()}),{wrapper:_e,panel:be,pillRoot:Ze}=gt.shell,Y=gt.panelElements,{container:pe,body:Me,messagesWrapper:Je,suggestions:Ge,textarea:ke,sendButton:je,sendButtonWrapper:Cr,composerForm:Wt,statusText:ur,introTitle:Eo,introSubtitle:V,closeButton:j,iconHolder:he,headerTitle:Xe,headerSubtitle:et,header:qe,footer:Ne,actionsRow:Pt,leftActions:Gt,rightActions:Jt}=Y,Pr=Y.setSendButtonMode,z=Y.micButton,Ht=Y.micButtonWrapper,oe=Y.attachmentButton,we=Y.attachmentButtonWrapper,De=Y.attachmentInput,At=Y.attachmentPreviewsContainer;pe.classList.add("persona-relative"),Me.classList.add("persona-relative");let ar=12,sr=()=>{var l;return(l=Ue.label)!=null?l:""},wr=()=>{var l;return(l=Ue.iconName)!=null?l:"arrow-down"},Ft=()=>Ue.enabled!==!1,ot=()=>{var l;return(l=Te.mode)!=null?l:"follow"},Dt=()=>{var l;return(l=Te.anchorTopOffset)!=null?l:16},lt=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");lt.type="button",lt.style.display="none",lt.setAttribute("data-persona-scroll-to-bottom","true");let Yt=S("span","persona-flex persona-items-center"),so=S("span",""),Rr=S("span","");Rr.setAttribute("data-persona-scroll-to-bottom-count",""),Rr.style.display="none",lt.append(Yt,so,Rr),pe.appendChild(lt);let ir=S("div","persona-stream-anchor-spacer");ir.setAttribute("aria-hidden","true"),ir.setAttribute("data-persona-anchor-spacer",""),ir.style.flexShrink="0",ir.style.pointerEvents="none",ir.style.height="0px",Me.appendChild(ir);let Ur=()=>{let f=Ne.style.display==="none"?0:Ne.offsetHeight;lt.style.bottom=`${f+ar}px`};Ur();let ko=()=>{let l=!!sr();lt.setAttribute("aria-label",sr()||"Jump to latest"),lt.title=sr(),lt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Yt.innerHTML="";let f=ve(wr(),"14px","currentColor",2);f?(Yt.appendChild(f),Yt.style.display=""):Yt.style.display="none",so.textContent=sr(),so.style.display=l?"":"none"};ko();let yt=null,jr=null,Lo=n.find(l=>l.renderHeader);if(Lo!=null&&Lo.renderHeader){let l=Lo.renderHeader({config:o,defaultRenderer:()=>{let f=ln({config:o,showClose:W()});return pa(pe,f,o),f.header},onClose:()=>I(!1,"user")});if(l){let f=pe.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),qe=l,gt.header.element=l)}}let zo=()=>{var f,h,v,R;if(!ge)return;if(ce=!0,!G&&ge&&(G=qh({buffer:ge,getFullHistory:()=>ge.getAllFromStore(),onClose:()=>yo(),config:o,plugins:n,getThroughput:()=>{var F;return(F=ue==null?void 0:ue.getMetric())!=null?F:{status:"idle"}}})),G&&(Me.style.display="none",(f=Ne.parentNode)==null||f.insertBefore(G.element,Ne),G.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${_r.actionIconColor}`;let F=(R=(v=(h=o.features)==null?void 0:h.eventStream)==null?void 0:v.classNames)==null?void 0:R.toggleButtonActive;F&&F.split(/\s+/).forEach($=>$&&ht.classList.add($))}let l=()=>{if(!ce)return;let F=Date.now();F-ne>=200&&(G==null||G.update(),ne=F),Be=requestAnimationFrame(l)};ne=0,Be=requestAnimationFrame(l),$r(),a.emit("eventStream:opened",{timestamp:Date.now()})},yo=()=>{var l,f,h;if(ce){if(ce=!1,G&&G.element.remove(),Me.style.display="",ht){ht.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(R=>R&&ht.classList.remove(R))}Be!==null&&(cancelAnimationFrame(Be),Be=null),$r(),a.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(Ie){let l=(qu=(Uu=o.features)==null?void 0:Uu.eventStream)==null?void 0:qu.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:"");ht=S("button",f),ht.style.width="28px",ht.style.height="28px",ht.style.color=_r.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let h=ve("activity","18px","currentColor",1.5);h&&ht.appendChild(h);let v=Y.clearChatButtonWrapper,R=Y.closeButtonWrapper,F=v||R;F&&F.parentNode===qe?qe.insertBefore(ht,F):qe.appendChild(ht),ht.addEventListener("click",()=>{ce?yo():zo()})}let Nn=l=>{var R,F,$,O,D;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=(R=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?R: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 ae=l.querySelector("[data-persona-composer-form]");ae!=null&&ae.parentNode?ae.parentNode.insertBefore(h,ae):l.insertBefore(h,l.firstChild)}if(!((F=l.querySelector("[data-persona-composer-attachment-input]"))!=null?F:l.querySelector('input[type="file"]'))){let ae=S("input");ae.type="file",ae.setAttribute("data-persona-composer-attachment-input",""),ae.accept=(($=f.allowedTypes)!=null?$:an).join(","),ae.multiple=((O=f.maxFiles)!=null?O:4)>1,ae.style.display="none",ae.setAttribute("aria-label",(D=f.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(ae)}},Po=n.find(l=>l.renderComposer);if(Po!=null&&Po.renderComposer){let l=o.composer,f=Po.renderComposer({config:o,defaultRenderer:()=>ja({config:o}).footer,onSubmit:h=>{var $;if(!_||_.isStreaming())return;let v=h.trim(),R=($=yt==null?void 0:yt.hasAttachments())!=null?$:!1;if(!v&&!R)return;tt();let F;R&&(F=[],F.push(...yt.getContentParts()),v&&F.push(ks(v))),_.sendMessage(v,{contentParts:F}),R&&yt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{De==null||De.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:((Vu=o.voiceRecognition)==null?void 0:Vu.enabled)===!0?()=>{jr==null||jr()}:void 0});f&&(gt.replaceComposer(f),Ne=gt.composer.footer)}let On=l=>{let f=(...se)=>{for(let Q of se){let ye=l.querySelector(Q);if(ye)return ye}return null},h=l.querySelector("[data-persona-composer-form]"),v=l.querySelector("[data-persona-composer-input]"),R=l.querySelector("[data-persona-composer-submit]"),F=l.querySelector("[data-persona-composer-mic]"),$=l.querySelector("[data-persona-composer-status]");h&&(Wt=h),v&&(ke=v),R&&(je=R),F&&(z=F,Ht=F.parentElement),$&&(ur=$);let O=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Ge=O);let D=f("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(oe=D,we=D.parentElement),De=f("[data-persona-composer-attachment-input]",'input[type="file"]'),At=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(Pt=ae)};Nn(Ne),On(Ne);let qr=(Ku=($u=o.layout)==null?void 0:$u.contentMaxWidth)!=null?Ku:H()?(Gu=(ju=(zu=o.launcher)==null?void 0:zu.composerBar)==null?void 0:ju.contentMaxWidth)!=null?Gu:"720px":void 0;if(qr&&(Je.style.maxWidth=qr,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%"),qr&&Wt&&!H()&&(Wt.style.maxWidth=qr,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),qr&&Ge&&!H()&&(Ge.style.maxWidth=qr,Ge.style.marginLeft="auto",Ge.style.marginRight="auto"),qr&&At&&!H()&&(At.style.maxWidth=qr,At.style.marginLeft="auto",At.style.marginRight="auto"),(Xu=o.attachments)!=null&&Xu.enabled&&De&&At){yt=la.fromConfig(o.attachments),yt.setPreviewsContainer(At),De.addEventListener("change",h=>{let v=h.target;yt==null||yt.handleFileSelect(v.files),v.value=""});let l=o.attachments.dropOverlay,f=ax(l);pe.appendChild(f)}(()=>{var v,R;let l=(R=(v=o.layout)==null?void 0:v.slots)!=null?R:{},f=F=>{switch(F){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Je;case"footer-top":return Ge;case"composer":return Wt;case"footer-bottom":return ur;default:return null}},h=(F,$)=>{var O;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")qe.insertBefore($,qe.firstChild);else if(F==="header-right")qe.appendChild($);else{let D=qe.querySelector(".persona-flex-col");D?(O=D.parentNode)==null||O.insertBefore($,D.nextSibling):qe.appendChild($)}break;case"body-top":{let D=Me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith($):Me.insertBefore($,Me.firstChild);break}case"body-bottom":Me.appendChild($);break;case"footer-top":Ge.replaceWith($);break;case"footer-bottom":ur.replaceWith($);break;default:break}};for(let[F,$]of Object.entries(l))if($)try{let O=$({config:o,defaultContent:()=>f(F)});O&&h(F,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,O)}})();let cn=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 R=v.getAttribute("data-message-id");if(!R)return;let F=h.getAttribute("data-bubble-type");if(F==="reasoning")Ka.has(R)?Ka.delete(R):Ka.add(R),Ih(R,v);else if(F==="tool")Xa.has(R)?Xa.delete(R):Xa.add(R),Wh(R,v,o);else if(F==="approval"){let D=o.approval!==!1?o.approval:void 0,ae=(($=D==null?void 0:D.detailsDisplay)!=null?$:"collapsed")==="expanded",se=(O=bl.get(R))!=null?O:ae;bl.set(R,!se),Fh(R,v,o)}Bo.delete(R)};Je.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))}),Je.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))});let jo=new Map,pn=null,un="idle",_n={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Un=(l,f)=>{let{icon:h,label:v}=_n[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 R=ve(h,14,"currentColor",2);R&&(l.innerHTML="",l.appendChild(R))},fn=()=>{Je.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{var F;let h=f.closest("[data-actions-for]"),v=(F=h==null?void 0:h.getAttribute("data-actions-for"))!=null?F:null;Un(f,v&&v===pn?un:"idle")})};Je.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 R=v.getAttribute("data-actions-for");if(!R)return;let F=h.getAttribute("data-action");if(F==="copy"){let D=_.getMessages().find(ae=>ae.id===R);if(D&&ee.onCopy){let ae=D.content||"";navigator.clipboard.writeText(ae).then(()=>{h.classList.add("persona-message-action-success");let se=ve("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Q=ve("copy",14,"currentColor",2);Q&&(h.innerHTML="",h.appendChild(Q))},2e3)}).catch(se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",se)}),ee.onCopy(D)}}else if(F==="read-aloud")_.toggleReadAloud(R);else if(F==="upvote"||F==="downvote"){let D=(($=jo.get(R))!=null?$:null)===F,ae=F==="upvote"?"thumbs-up":"thumbs-down";if(D){jo.delete(R),h.classList.remove("persona-message-action-active");let se=ve(ae,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=F==="upvote"?"downvote":"upvote",Q=v.querySelector(`[data-action="${se}"]`);if(Q){Q.classList.remove("persona-message-action-active");let $e=ve(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);$e&&(Q.innerHTML="",Q.appendChild($e))}jo.set(R,F),h.classList.add("persona-message-action-active");let ye=ve(ae,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ye)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Se=_.getMessages().find(nt=>nt.id===R);Se&&ee.onFeedback&&ee.onFeedback({type:F,messageId:Se.id,message:Se})}}}),Je.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 R=v.getAttribute("data-message-id");if(!R)return;let F=h.getAttribute("data-approval-action");if(!F)return;let $=F==="approve"?"approved":"denied",D=_.getMessages().find(se=>se.id===R);if(!(D!=null&&D.approval))return;let ae=v.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(Q=>{Q.disabled=!0,Q.style.opacity="0.5",Q.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?_.resolveWebMcpApproval(R,$):_.resolveApproval(D.approval,$)});let Ct=null,Gr=null,Kr={artifacts:[],selectedId:null},Ir=!1,Mt={current:null};Je.addEventListener("click",l=>{var Q,ye,He,Se,nt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.getAttribute("data-download-artifact");if(!v||((He=(ye=(Q=o.features)==null?void 0:Q.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:He.call(ye,{type:"download",artifactId:v}))===!0)return;let F=_.getArtifactById(v),$=F==null?void 0:F.markdown,O=(F==null?void 0:F.title)||"artifact";if(!$){let $e=h.closest("[data-open-artifact]"),ut=$e==null?void 0:$e.closest("[data-message-id]"),st=ut==null?void 0:ut.getAttribute("data-message-id");if(st){let Ee=_.getMessages().find(ze=>ze.id===st);if(Ee!=null&&Ee.rawContent)try{let ze=JSON.parse(Ee.rawContent);$=(Se=ze==null?void 0:ze.props)==null?void 0:Se.markdown,O=((nt=ze==null?void 0:ze.props)==null?void 0:nt.title)||O}catch{}}}if(!$)return;let D=new Blob([$],{type:"text/markdown"}),ae=URL.createObjectURL(D),se=document.createElement("a");se.href=ae,se.download=`${O}.md`,se.click(),URL.revokeObjectURL(ae)}),Je.addEventListener("click",l=>{var F,$,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let v=h.getAttribute("data-open-artifact");!v||((O=($=(F=o.features)==null?void 0:F.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:O.call($,{type:"open",artifactId:v}))===!0||(l.preventDefault(),l.stopPropagation(),Ir=!1,_.selectArtifact(v),Jr())}),Je.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;f.hasAttribute("data-open-artifact")&&(l.preventDefault(),f.click())});let io=Y.composerOverlay,lo=(l,f,h)=>{var O,D,ae,se;let v=f.trim();if(!v||!Mt.current)return;let R=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",F=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:R,answer:v,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?v.split(", "):[v],isFreeText:F,source:h.source},bubbles:!0,composed:!0})),Ln(io,R);let $=Mt.current.getMessages().find(Q=>{var ye;return((ye=Q.toolCall)==null?void 0:ye.id)===R});(ae=$==null?void 0:$.agentMetadata)!=null&&ae.awaitingLocalTool?Mt.current.resolveAskUserQuestion($,(se=h.structured)!=null?se:v):Mt.current.sendMessage(v)},Xr=l=>{var R;let f=Mt.current;if(!f)return;let h=(R=l.getAttribute("data-tool-call-id"))!=null?R:"",v=f.getMessages().find(F=>{var $;return(($=F.toolCall)==null?void 0:$.id)===h});v&&f.persistAskUserQuestionProgress(v,{answers:Ci(l,v),currentIndex:ho(l)})},mn=l=>Object.entries(l).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Go=l=>{var R,F,$;if(((F=(R=o.features)==null?void 0:R.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let f=ho(l),h=Da(l);if(f>=h-1)return;let v=($=Mt.current)==null?void 0:$.getMessages().find(O=>{var D;return((D=O.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});v&&(wi(l,v,o,f+1),Xr(l))};io.addEventListener("click",l=>{var F,$,O,D,ae,se,Q,ye,He,Se,nt,$e,ut,st;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 R=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),R==="dismiss"){let Le=(F=v.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Ln(io,Le);let Ee=($=Mt.current)==null?void 0:$.getMessages().find(ze=>{var Qe;return((Qe=ze.toolCall)==null?void 0:Qe.id)===Le});(O=Ee==null?void 0:Ee.agentMetadata)!=null&&O.awaitingLocalTool&&((D=Mt.current)==null||D.markAskUserQuestionResolved(Ee),(ae=Mt.current)==null||ae.resolveAskUserQuestion(Ee,"(dismissed)"));return}if(R==="pick"){let Le=h.getAttribute("data-option-label");if(!Le)return;let Ee=v.getAttribute("data-multi-select")==="true",ze=kn(v);if(ze&&Ee){let Qe=ta(v)[ho(v)],xt=new Set(Array.isArray(Qe)?Qe:[]);xt.has(Le)?xt.delete(Le):xt.add(Le),Pn(v,Array.from(xt)),Xr(v);return}if(ze){Pn(v,Le),Xr(v),Go(v);return}if(Ee){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let xt=v.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=Jl(v).length===0);return}lo(v,Le,{source:"pick",values:[Le]});return}if(R==="submit-multi"){let Le=Jl(v);if(Le.length===0)return;lo(v,Le.join(", "),{source:"multi",values:Le});return}if(R==="open-free-text"){let Le=v.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let Ee=Le.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus()}return}if(R==="focus-free-text"){let Le=v.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(R==="submit-free-text"){let Le=v.querySelector('[data-ask-free-text-input="true"]'),Ee=(se=Le==null?void 0:Le.value)!=null?se:"";if(!Ee.trim())return;if(kn(v)){Pn(v,Ee.trim()),Xr(v),Go(v);return}lo(v,Ee,{source:"free-text"});return}if(R==="next"||R==="back"){if(!Mt.current)return;let Le=(Q=v.getAttribute("data-tool-call-id"))!=null?Q:"",Ee=Mt.current.getMessages().find(Re=>{var Pe;return((Pe=Re.toolCall)==null?void 0:Pe.id)===Le});if(!Ee)return;let ze=v.querySelector('[data-ask-free-text-input="true"]'),Qe=(He=(ye=ze==null?void 0:ze.value)==null?void 0:ye.trim())!=null?He:"";if(Qe){let Re=ta(v)[ho(v)];(typeof Re!="string"||Re!==Qe)&&Pn(v,Qe)}let xt=R==="next"?1:-1,B=ho(v)+xt;wi(v,Ee,o,B),Xr(v);return}if(R==="submit-all"){if(!Mt.current)return;let Le=(Se=v.getAttribute("data-tool-call-id"))!=null?Se:"",Ee=Mt.current.getMessages().find(Re=>{var Pe;return((Pe=Re.toolCall)==null?void 0:Pe.id)===Le});if(!Ee)return;let ze=v.querySelector('[data-ask-free-text-input="true"]'),Qe=($e=(nt=ze==null?void 0:ze.value)==null?void 0:nt.trim())!=null?$e:"";Qe&&Pn(v,Qe);let xt=Ci(v,Ee);Mt.current.persistAskUserQuestionProgress(Ee,{answers:xt,currentIndex:ho(v)});let B=mn(xt);lo(v,B||"(submitted)",{source:"submit-all",structured:xt});return}if(R==="skip"){if(!Mt.current)return;let Le=(ut=v.getAttribute("data-tool-call-id"))!=null?ut:"",Ee=Mt.current.getMessages().find(Pe=>{var fe;return((fe=Pe.toolCall)==null?void 0:fe.id)===Le});if(!Ee)return;let ze=kn(v),Qe=ho(v),xt=Da(v),B=Qe>=xt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Ln(io,Le),(st=Ee.agentMetadata)!=null&&st.awaitingLocalTool&&(Mt.current.markAskUserQuestionResolved(Ee),Mt.current.resolveAskUserQuestion(Ee,"(dismissed)"));return}Pn(v,"");let Re=v.querySelector('[data-ask-free-text-input="true"]');if(Re&&(Re.value=""),B){let Pe=Ci(v,Ee),fe=mn(Pe);lo(v,fe||"(skipped)",{source:"submit-all",structured:Pe});return}wi(v,Ee,o,Qe+1),Xr(v);return}}),io.addEventListener("keydown",l=>{var F;if(l.key!=="Enter")return;let h=l.target;if(!((F=h.matches)!=null&&F.call(h,'[data-ask-free-text-input="true"]')))return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;l.preventDefault();let R=h.value;if(R.trim()){if(kn(v)){Pn(v,R.trim()),Xr(v),Go(v);return}lo(v,R,{source:"free-text"})}});let gn=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=io.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),F=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];F&&(l.preventDefault(),F.click())};document.addEventListener("keydown",gn);let Qr=null,Nt=null,Wr=null,co=null,hn=()=>{};function Ko(){co==null||co(),co=null}let xn=()=>{var $;if(!Qr||!Nt)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){Nt.style.removeProperty("position"),Nt.style.removeProperty("left"),Nt.style.removeProperty("top"),Nt.style.removeProperty("bottom"),Nt.style.removeProperty("width"),Nt.style.removeProperty("z-index");return}let v=Qr.firstElementChild;if(!v||v===Nt)return;let R=10;Nt.style.position="absolute",Nt.style.top="0",Nt.style.bottom="0",Nt.style.width=`${R}px`,Nt.style.zIndex="5";let F=v.offsetWidth-R/2;Nt.style.left=`${Math.max(0,F)}px`},Ro=()=>{},Jr=()=>{var h,v,R,F,$;if(!Ct||!xo(o))return;wl(e,o),Sl(e,o),Ro();let l=(F=(R=(v=(h=o.features)==null?void 0:h.artifacts)==null?void 0:v.layout)==null?void 0:R.narrowHostMaxWidth)!=null?F:520,f=be.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l),Ct.update(Kr),Ir?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),($=Ct.backdrop)==null||$.classList.add("persona-hidden")):Kr.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),hn()};if(xo(o)){be.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(pe),Ct=zh(o,{onSelect:h=>{var v;return(v=Mt.current)==null?void 0:v.selectArtifact(h)},onDismiss:()=>{Ir=!0,Jr()}}),Ct.element.classList.add("persona-hidden"),Qr=f,f.appendChild(l),f.appendChild(Ct.element),Ct.backdrop&&be.appendChild(Ct.backdrop),be.appendChild(f),hn=()=>{var v,R,F,$;if(!Qr||!Ct)return;if(!(((F=(R=(v=o.features)==null?void 0:v.artifacts)==null?void 0:R.layout)==null?void 0:F.resizable)===!0)){Wr==null||Wr(),Wr=null,Ko(),Nt&&(Nt.remove(),Nt=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Nt){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 D=e.ownerDocument,ae=($=D.defaultView)!=null?$:window,se=Q=>{var ut,st;if(!Ct||Q.button!==0||e.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;Q.preventDefault(),Ko();let ye=Q.clientX,He=Ct.element.getBoundingClientRect().width,Se=(st=(ut=o.features)==null?void 0:ut.artifacts)==null?void 0:st.layout,nt=Le=>{let Ee=Qr.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Qe=ze?0:Xh(Qr,ae),xt=ze?0:O.getBoundingClientRect().width||6,B=He-(Le.clientX-ye),Re=Qh(B,Ee,Qe,xt,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);Ct.element.style.width=`${Re}px`,Ct.element.style.maxWidth="none",xn()},$e=()=>{D.removeEventListener("pointermove",nt),D.removeEventListener("pointerup",$e),D.removeEventListener("pointercancel",$e),co=null;try{O.releasePointerCapture(Q.pointerId)}catch{}};co=$e,D.addEventListener("pointermove",nt),D.addEventListener("pointerup",$e),D.addEventListener("pointercancel",$e);try{O.setPointerCapture(Q.pointerId)}catch{}};O.addEventListener("pointerdown",se),Nt=O,Qr.insertBefore(O,Ct.element),Wr=()=>{O.removeEventListener("pointerdown",se)}}if(Nt){let O=Kr.artifacts.length>0&&!Ir;Nt.classList.toggle("persona-hidden",!O),xn()}},Ro=()=>{var ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee,ze,Qe;if(!E||!Ct||((se=(ae=o.launcher)==null?void 0:ae.sidebarMode)!=null?se:!1)||pr(o)&&no(o).reveal==="emerge")return;let v=(Q=e.ownerDocument.defaultView)!=null?Q:window,R=(He=(ye=o.launcher)==null?void 0:ye.mobileFullscreen)!=null?He:!0,F=(nt=(Se=o.launcher)==null?void 0:Se.mobileBreakpoint)!=null?nt:640;if(R&&v.innerWidth<=F||!Kh(o,E))return;let $=(st=(ut=($e=o.launcher)==null?void 0:$e.width)!=null?ut:o.launcherWidth)!=null?st:oo,O=(Qe=(ze=(Ee=(Le=o.features)==null?void 0:Le.artifacts)==null?void 0:Ee.layout)==null?void 0:ze.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Kr.artifacts.length>0&&!Ir?(be.style.width=O,be.style.maxWidth=O):(be.style.width=$,be.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Gr=new ResizeObserver(()=>{Jr()}),Gr.observe(be))}else be.appendChild(pe),H()&&Ze&&(Y.peekBanner&&Ze.appendChild(Y.peekBanner),Ze.appendChild(Ne));e.appendChild(_e),Ze&&e.appendChild(Ze);let xe=()=>{var Re,Pe,fe,Ut,Ot,Kt,bt,zt,eo,or,Ye,Rt,cr,go,to,jn,Gn,ka,La,Xt,Kn,Mn,Tn,en,Xn,wo,rt,gr;if(H()){be.style.width="100%",be.style.maxWidth="100%";let Vt=(Pe=(Re=o.launcher)==null?void 0:Re.composerBar)!=null?Pe:{},qt=_e.dataset.state==="expanded",ft=(fe=Vt.expandedSize)!=null?fe:"anchored";if(!(qt&&ft!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let St=(Ot=(Ut=o.theme)==null?void 0:Ut.components)==null?void 0:Ot.panel,Tr=$a(o),Br=(Fr,Qn)=>{var gs;return Fr==null||Fr===""?Qn:(gs=qa(Tr,Fr))!=null?gs:Fr},Uo="1px solid var(--persona-border)",vr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Dr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Br(St==null?void 0:St.border,Uo),pe.style.borderRadius=Br(St==null?void 0:St.borderRadius,Dr),pe.style.boxShadow=Br(St==null?void 0:St.shadow,vr),pe.style.overflow="hidden";return}let l=pr(o),f=(bt=(Kt=o.launcher)==null?void 0:Kt.sidebarMode)!=null?bt:!1,h=l||f||((eo=(zt=o.launcher)==null?void 0:zt.fullHeight)!=null?eo:!1),v=((or=o.launcher)==null?void 0:or.enabled)===!1,R=(Rt=(Ye=o.theme)==null?void 0:Ye.components)==null?void 0:Rt.panel,F=$a(o),$=(Vt,qt)=>{var ft;return Vt==null||Vt===""?qt:(ft=qa(F,Vt))!=null?ft:Vt},O=(cr=e.ownerDocument.defaultView)!=null?cr:window,D=(to=(go=o.launcher)==null?void 0:go.mobileFullscreen)!=null?to:!0,ae=(Gn=(jn=o.launcher)==null?void 0:jn.mobileBreakpoint)!=null?Gn:640,se=O.innerWidth<=ae,Q=D&&se&&E,ye=(La=(ka=o.launcher)==null?void 0:ka.position)!=null?La:"bottom-left",He=ye==="bottom-left"||ye==="top-left",Se=(Kn=(Xt=o.launcher)==null?void 0:Xt.zIndex)!=null?Kn:Lr,nt=f||Q?"none":"1px solid var(--persona-border)",$e=Q?"none":f?He?"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&&!Q&&($e="none",nt="none");let ut=f||Q?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=$(R==null?void 0:R.border,nt),Le=$(R==null?void 0:R.shadow,$e),Ee=$(R==null?void 0:R.borderRadius,ut),ze=Me.scrollTop;e.style.cssText="",_e.style.cssText="",be.style.cssText="",pe.style.cssText="",Me.style.cssText="",Ne.style.cssText="";let Qe=()=>{var qt;if(ze<=0)return;((qt=Me.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(Me.scrollTop===ze)return;let ft=Me.scrollHeight-Me.clientHeight;ft<=0||(Me.scrollTop=Math.min(ze,ft))})};if(Q){_e.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"),_e.style.cssText=`
33
+ `,M.addEventListener("click",()=>{g=b,E.forEach((W,R)=>{let L=R<b;W.classList.toggle("selected",L),W.setAttribute("aria-checked",R===b-1?"true":"false")})}),E.push(M),T.appendChild(M)}p.appendChild(T);let w=null;if(c){let b=document.createElement("div");b.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=a,w.rows=3,w.setAttribute("aria-label","Additional comments"),b.appendChild(w),p.appendChild(b)}let k=document.createElement("div");k.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 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(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}S.disabled=!0,S.textContent="Submitting...";try{let b=(w==null?void 0:w.value.trim())||void 0;await t(g,b),u.remove()}catch(b){S.disabled=!1,S.textContent=s,console.error("[CSAT Feedback] Failed to submit:",b)}}),k.appendChild(y),k.appendChild(S),p.appendChild(k),u.appendChild(p),u}function Rl(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: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 p=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 T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=n,x.appendChild(T),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 w=document.createElement("div");w.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=d;let y=document.createElement("span");y.className="persona-feedback-label-high",y.textContent=u,w.appendChild(k),w.appendChild(y);let S=document.createElement("div");S.className="persona-feedback-numbers";let b=[];for(let N=0;N<=10;N++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${N} out of 10`),q.textContent=String(N),q.dataset.rating=String(N),N<=6?q.classList.add("persona-feedback-detractor"):N<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{p=N,b.forEach((Y,me)=>{Y.classList.toggle("selected",me===N),Y.setAttribute("aria-checked",me===N?"true":"false")})}),b.push(q),S.appendChild(q)}E.appendChild(w),E.appendChild(S),m.appendChild(E);let M=null;if(c){let N=document.createElement("div");N.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"),N.appendChild(M),m.appendChild(N)}let W=document.createElement("div");W.className="persona-feedback-actions";let R=document.createElement("button");R.type="button",R.className="persona-feedback-btn persona-feedback-btn-skip",R.textContent=i,R.addEventListener("click",()=>{r==null||r(),g.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=s,L.addEventListener("click",async()=>{if(p===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let N=(M==null?void 0:M.value.trim())||void 0;await t(p,N),g.remove()}catch(N){L.disabled=!1,L.textContent=s,console.error("[NPS Feedback] Failed to submit:",N)}}),W.appendChild(R),W.appendChild(L),m.appendChild(W),g.appendChild(m),g}var Ja="persona-chat-history",Wv=30*1e3,Hv={"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 Bv(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=Hv[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 Wl(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 Dv(e){var t,r,o,n,a,s,i,c,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:(c=(i=e.persist)==null?void 0:i.focusInput)!=null?c:!0},clearOnChatClear:(d=e.clearOnChatClear)!=null?d:!0}:null}function Fv(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Hp=e=>!e||typeof e!="object"?{}:{...e},sx=e=>e.map(t=>({...t,streaming:!1})),ix=(e,t,r)=>{let o=e!=null&&e.markdown?Zn(e.markdown):null,n=Ra(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 d,u,g;let s=(d=a.text)!=null?d:"",i=(u=a.message.rawContent)!=null?u:null;if(t){let p=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});p!==null&&(s=p.text,p.persist||(a.message.__skipPersist=!0),p.resubmit&&!a.streaming&&r&&r())}let c;return e!=null&&e.postprocessMessage?c=e.postprocessMessage({...a,text:s,raw:(g=i!=null?i:a.text)!=null?g:""}):o?c=o(s):c=Uo(s),n?n(c):c}};function lx(e){var i,c,d,u;let t=A("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=(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=ve(r,o,n,a);if(s&&t.appendChild(s),e!=null&&e.label){let g=A("span","persona-drop-overlay-label");g.textContent=e.label,t.appendChild(g)}return t}var Hl=(e,t,r)=>{var mu,gu,hu,xu,yu,bu,vu,Cu,wu,Su,Au,Mu,Tu,Eu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Fu,Nu,Ou,_u,Uu,qu,Vu,$u,zu,ju,Gu,Ku,Xu,Qu,Ju,Yu,Zu,ef,tf,rf,of,nf,af,sf,lf,df,cf;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=Zi(t),n=$s.getForInstance(o.plugins);o.components&&dn.registerAll(o.components);let a=tx(),i=o.persistState===!1?null:(mu=o.storageAdapter)!=null?mu:Tl(),c={},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&&(c=Hp(h.metadata)),(gu=h.messages)!=null&&gu.length&&(o={...o,initialMessages:h.messages}),(hu=h.artifacts)!=null&&hu.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(xu=h.selectedArtifactId)!=null?xu: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:{}});(yu=l.messages)!=null&&yu.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>c,m=l=>{var h;c=(h=l({...c}))!=null?h:{},wa()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zs],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ma.message,ma.messageAndClick],T=js({parsers:x,handlers:C,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let E=(vu=(bu=o.launcher)==null?void 0:bu.enabled)!=null?vu:!0,w=(wu=(Cu=o.launcher)==null?void 0:Cu.autoExpand)!=null?wu:!1,k=(Su=o.autoFocusInput)!=null?Su:!1,y=w,S=E,b=(Mu=(Au=o.layout)==null?void 0:Au.header)==null?void 0:Mu.layout,M=!1,W=()=>Dn(o),R=()=>E||W(),L=W()?!1:E?w:!0,N=!1,q=null,Y=()=>{N=!0,q&&clearTimeout(q),q=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},me=ix(o,T,Y),Ge=(Eu=(Tu=o.features)==null?void 0:Tu.showReasoning)!=null?Eu:!0,Ce=(Lu=(ku=o.features)==null?void 0:ku.showToolCalls)!=null?Lu:!0,Be=(Iu=(Pu=o.features)==null?void 0:Pu.showEventStreamToggle)!=null?Iu:!1,qe=(Wu=(Ru=o.features)==null?void 0:Ru.scrollToBottom)!=null?Wu:{},Ee=(Bu=(Hu=o.features)==null?void 0:Hu.scrollBehavior)!=null?Bu:{},le=`${(Fu=typeof o.persistState=="object"?(Du=o.persistState)==null?void 0:Du.keyPrefix:void 0)!=null?Fu:"persona-"}event-stream`,Q=Be?new qs(le):null,ie=(_u=(Ou=(Nu=o.features)==null?void 0:Nu.eventStream)==null?void 0:Ou.maxEvents)!=null?_u:2e3,ge=Be?new Us(ie,Q):null,ue=Be?new Vs:null,j=null,de=!1,Ne=null,te=0;Q==null||Q.open().then(()=>ge==null?void 0:ge.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Z={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)}},ae=(Uu=o.statusIndicator)!=null?Uu:{},wt=l=>{var f,h,v,I;return l==="idle"?(f=ae.idleText)!=null?f:Ir.idle:l==="connecting"?(h=ae.connectingText)!=null?h:Ir.connecting:l==="connected"?(v=ae.connectedText)!=null?v:Ir.connected:l==="error"?(I=ae.errorText)!=null?I:Ir.error:Ir[l]};function Pt(l,f,h,v){if(v==="idle"&&h.idleLink){l.textContent="";let I=document.createElement("a");I.href=h.idleLink,I.target="_blank",I.rel="noopener noreferrer",I.textContent=f,I.style.color="inherit",I.style.textDecoration="none",l.appendChild(I)}else l.textContent=f}let xt=Ih({config:o,showClose:R()}),{wrapper:Ue,panel:be,pillRoot:Je}=xt.shell,J=xt.panelElements,{container:ce,body:Te,messagesWrapper:Xe,suggestions:Kt,textarea:ke,sendButton:Ve,sendButtonWrapper:rt,composerForm:Ft,statusText:vr,introTitle:To,introSubtitle:Tr,closeButton:je,iconHolder:Nt,headerTitle:V,headerSubtitle:Me,header:we,footer:He,actionsRow:nt,leftActions:lt,rightActions:ot}=J,Tt=J.setSendButtonMode,z=J.micButton,St=J.micButtonWrapper,se=J.attachmentButton,pe=J.attachmentButtonWrapper,Ae=J.attachmentInput,dt=J.attachmentPreviewsContainer;ce.classList.add("persona-relative"),Te.classList.add("persona-relative");let er=12,ir=()=>{var l;return(l=qe.label)!=null?l:""},Sr=()=>{var l;return(l=qe.iconName)!=null?l:"arrow-down"},_t=()=>qe.enabled!==!1,et=()=>{var l;return(l=Ee.mode)!=null?l:"follow"},Ot=()=>{var l;return(l=Ee.anchorTopOffset)!=null?l:16},ct=A("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");ct.type="button",ct.style.display="none",ct.setAttribute("data-persona-scroll-to-bottom","true");let tr=A("span","persona-flex persona-items-center"),io=A("span",""),Wr=A("span","");Wr.setAttribute("data-persona-scroll-to-bottom-count",""),Wr.style.display="none",ct.append(tr,io,Wr),ce.appendChild(ct);let lr=A("div","persona-stream-anchor-spacer");lr.setAttribute("aria-hidden","true"),lr.setAttribute("data-persona-anchor-spacer",""),lr.style.flexShrink="0",lr.style.pointerEvents="none",lr.style.height="0px",Te.appendChild(lr);let qr=()=>{let f=He.style.display==="none"?0:He.offsetHeight;ct.style.bottom=`${f+er}px`};qr();let Eo=()=>{let l=!!ir();ct.setAttribute("aria-label",ir()||"Jump to latest"),ct.title=ir(),ct.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),tr.innerHTML="";let f=ve(Sr(),"14px","currentColor",2);f?(tr.appendChild(f),tr.style.display=""):tr.style.display="none",io.textContent=ir(),io.style.display=l?"":"none"};Eo();let vt=null,Gr=null,ko=n.find(l=>l.renderHeader);if(ko!=null&&ko.renderHeader){let l=ko.renderHeader({config:o,defaultRenderer:()=>{let f=ln({config:o,showClose:R()});return pa(ce,f,o),f.header},onClose:()=>he(!1,"user")});if(l){let f=ce.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),we=l,xt.header.element=l)}}let $o=()=>{var f,h,v,I;if(!ge)return;if(de=!0,!j&&ge&&(j=zh({buffer:ge,getFullHistory:()=>ge.getAllFromStore(),onClose:()=>xo(),config:o,plugins:n,getThroughput:()=>{var F;return(F=ue==null?void 0:ue.getMetric())!=null?F:{status:"idle"}}})),j&&(Te.style.display="none",(f=He.parentNode)==null||f.insertBefore(j.element,He),j.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Ur.actionIconColor}`;let F=(I=(v=(h=o.features)==null?void 0:h.eventStream)==null?void 0:v.classNames)==null?void 0:I.toggleButtonActive;F&&F.split(/\s+/).forEach($=>$&&yt.classList.add($))}let l=()=>{if(!de)return;let F=Date.now();F-te>=200&&(j==null||j.update(),te=F),Ne=requestAnimationFrame(l)};te=0,Ne=requestAnimationFrame(l),zr(),a.emit("eventStream:opened",{timestamp:Date.now()})},xo=()=>{var l,f,h;if(de){if(de=!1,j&&j.element.remove(),Te.style.display="",yt){yt.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(I=>I&&yt.classList.remove(I))}Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),zr(),a.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(Be){let l=(Vu=(qu=o.features)==null?void 0:qu.eventStream)==null?void 0:Vu.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:"");yt=A("button",f),yt.style.width="28px",yt.style.height="28px",yt.style.color=Ur.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=ve("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let v=J.clearChatButtonWrapper,I=J.closeButtonWrapper,F=v||I;F&&F.parentNode===we?we.insertBefore(yt,F):we.appendChild(yt),yt.addEventListener("click",()=>{de?xo():$o()})}let Nn=l=>{var I,F,$,O,D;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=(I=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?I:l.querySelector(".persona-attachment-previews");if(!h){h=A("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 oe=l.querySelector("[data-persona-composer-form]");oe!=null&&oe.parentNode?oe.parentNode.insertBefore(h,oe):l.insertBefore(h,l.firstChild)}if(!((F=l.querySelector("[data-persona-composer-attachment-input]"))!=null?F:l.querySelector('input[type="file"]'))){let oe=A("input");oe.type="file",oe.setAttribute("data-persona-composer-attachment-input",""),oe.accept=(($=f.allowedTypes)!=null?$:an).join(","),oe.multiple=((O=f.maxFiles)!=null?O:4)>1,oe.style.display="none",oe.setAttribute("aria-label",(D=f.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(oe)}},Lo=n.find(l=>l.renderComposer);if(Lo!=null&&Lo.renderComposer){let l=o.composer,f=Lo.renderComposer({config:o,defaultRenderer:()=>za({config:o}).footer,onSubmit:h=>{var $;if(!_||_.isStreaming())return;let v=h.trim(),I=($=vt==null?void 0:vt.hasAttachments())!=null?$:!1;if(!v&&!I)return;Pe();let F;I&&(F=[],F.push(...vt.getContentParts()),v&&F.push(Es(v))),_.sendMessage(v,{contentParts:F}),I&&vt.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:(($u=o.voiceRecognition)==null?void 0:$u.enabled)===!0?()=>{Gr==null||Gr()}:void 0});f&&(xt.replaceComposer(f),He=xt.composer.footer)}let On=l=>{let f=(...ne)=>{for(let X of ne){let ye=l.querySelector(X);if(ye)return ye}return null},h=l.querySelector("[data-persona-composer-form]"),v=l.querySelector("[data-persona-composer-input]"),I=l.querySelector("[data-persona-composer-submit]"),F=l.querySelector("[data-persona-composer-mic]"),$=l.querySelector("[data-persona-composer-status]");h&&(Ft=h),v&&(ke=v),I&&(Ve=I),F&&(z=F,St=F.parentElement),$&&(vr=$);let O=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Kt=O);let D=f("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(se=D,pe=D.parentElement),Ae=f("[data-persona-composer-attachment-input]",'input[type="file"]'),dt=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let oe=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");oe&&(nt=oe)};Nn(He),On(He);let Vr=(Xu=(zu=o.layout)==null?void 0:zu.contentMaxWidth)!=null?Xu:W()?(Ku=(Gu=(ju=o.launcher)==null?void 0:ju.composerBar)==null?void 0:Gu.contentMaxWidth)!=null?Ku:"720px":void 0;if(Vr&&(Xe.style.maxWidth=Vr,Xe.style.marginLeft="auto",Xe.style.marginRight="auto",Xe.style.width="100%"),Vr&&Ft&&!W()&&(Ft.style.maxWidth=Vr,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),Vr&&Kt&&!W()&&(Kt.style.maxWidth=Vr,Kt.style.marginLeft="auto",Kt.style.marginRight="auto"),Vr&&dt&&!W()&&(dt.style.maxWidth=Vr,dt.style.marginLeft="auto",dt.style.marginRight="auto"),(Qu=o.attachments)!=null&&Qu.enabled&&Ae&&dt){vt=la.fromConfig(o.attachments),vt.setPreviewsContainer(dt),Ae.addEventListener("change",h=>{let v=h.target;vt==null||vt.handleFileSelect(v.files),v.value=""});let l=o.attachments.dropOverlay,f=lx(l);ce.appendChild(f)}(()=>{var v,I;let l=(I=(v=o.layout)==null?void 0:v.slots)!=null?I:{},f=F=>{switch(F){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Xe;case"footer-top":return Kt;case"composer":return Ft;case"footer-bottom":return vr;default:return null}},h=(F,$)=>{var O;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")we.insertBefore($,we.firstChild);else if(F==="header-right")we.appendChild($);else{let D=we.querySelector(".persona-flex-col");D?(O=D.parentNode)==null||O.insertBefore($,D.nextSibling):we.appendChild($)}break;case"body-top":{let D=Te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith($):Te.insertBefore($,Te.firstChild);break}case"body-bottom":Te.appendChild($);break;case"footer-top":Kt.replaceWith($);break;case"footer-bottom":vr.replaceWith($);break;default:break}};for(let[F,$]of Object.entries(l))if($)try{let O=$({config:o,defaultContent:()=>f(F)});O&&h(F,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,O)}})();let cn=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 I=v.getAttribute("data-message-id");if(!I)return;let F=h.getAttribute("data-bubble-type");if(F==="reasoning")Ga.has(I)?Ga.delete(I):Ga.add(I),Bh(I,v);else if(F==="tool")Ka.has(I)?Ka.delete(I):Ka.add(I),Dh(I,v,o);else if(F==="approval"){let D=o.approval!==!1?o.approval:void 0,oe=(($=D==null?void 0:D.detailsDisplay)!=null?$:"collapsed")==="expanded",ne=(O=Cl.get(I))!=null?O:oe;Cl.set(I,!ne),_h(I,v,o)}Ho.delete(I)};Xe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))}),Xe.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))});let zo=new Map,pn=null,un="idle",_n={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Un=(l,f)=>{let{icon:h,label:v}=_n[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 I=ve(h,14,"currentColor",2);I&&(l.innerHTML="",l.appendChild(I))},fn=()=>{Xe.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{var F;let h=f.closest("[data-actions-for]"),v=(F=h==null?void 0:h.getAttribute("data-actions-for"))!=null?F:null;Un(f,v&&v===pn?un:"idle")})};Xe.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 I=v.getAttribute("data-actions-for");if(!I)return;let F=h.getAttribute("data-action");if(F==="copy"){let D=_.getMessages().find(oe=>oe.id===I);if(D&&Z.onCopy){let oe=D.content||"";navigator.clipboard.writeText(oe).then(()=>{h.classList.add("persona-message-action-success");let ne=ve("check",14,"currentColor",2);ne&&(h.innerHTML="",h.appendChild(ne)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let X=ve("copy",14,"currentColor",2);X&&(h.innerHTML="",h.appendChild(X))},2e3)}).catch(ne=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ne)}),Z.onCopy(D)}}else if(F==="read-aloud")_.toggleReadAloud(I);else if(F==="upvote"||F==="downvote"){let D=(($=zo.get(I))!=null?$:null)===F,oe=F==="upvote"?"thumbs-up":"thumbs-down";if(D){zo.delete(I),h.classList.remove("persona-message-action-active");let ne=ve(oe,14,"currentColor",2);ne&&(h.innerHTML="",h.appendChild(ne))}else{let ne=F==="upvote"?"downvote":"upvote",X=v.querySelector(`[data-action="${ne}"]`);if(X){X.classList.remove("persona-message-action-active");let $e=ve(ne==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);$e&&(X.innerHTML="",X.appendChild($e))}zo.set(I,F),h.classList.add("persona-message-action-active");let ye=ve(oe,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ye)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Se=_.getMessages().find(tt=>tt.id===I);Se&&Z.onFeedback&&Z.onFeedback({type:F,messageId:Se.id,message:Se})}}}),Xe.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 I=v.getAttribute("data-message-id");if(!I)return;let F=h.getAttribute("data-approval-action");if(!F)return;let $=F==="approve"?"approved":"denied",D=_.getMessages().find(ne=>ne.id===I);if(!(D!=null&&D.approval))return;let oe=v.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(X=>{X.disabled=!0,X.style.opacity="0.5",X.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?_.resolveWebMcpApproval(I,$):_.resolveApproval(D.approval,$)});let At=null,Kr=null,Xr={artifacts:[],selectedId:null},Hr=!1,Et={current:null};Xe.addEventListener("click",l=>{var X,ye,Fe,Se,tt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.getAttribute("data-download-artifact");if(!v||((Fe=(ye=(X=o.features)==null?void 0:X.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:Fe.call(ye,{type:"download",artifactId:v}))===!0)return;let F=_.getArtifactById(v),$=F==null?void 0:F.markdown,O=(F==null?void 0:F.title)||"artifact";if(!$){let $e=h.closest("[data-open-artifact]"),mt=$e==null?void 0:$e.closest("[data-message-id]"),st=mt==null?void 0:mt.getAttribute("data-message-id");if(st){let Le=_.getMessages().find(ze=>ze.id===st);if(Le!=null&&Le.rawContent)try{let ze=JSON.parse(Le.rawContent);$=(Se=ze==null?void 0:ze.props)==null?void 0:Se.markdown,O=((tt=ze==null?void 0:ze.props)==null?void 0:tt.title)||O}catch{}}}if(!$)return;let D=new Blob([$],{type:"text/markdown"}),oe=URL.createObjectURL(D),ne=document.createElement("a");ne.href=oe,ne.download=`${O}.md`,ne.click(),URL.revokeObjectURL(oe)}),Xe.addEventListener("click",l=>{var F,$,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let v=h.getAttribute("data-open-artifact");!v||((O=($=(F=o.features)==null?void 0:F.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:O.call($,{type:"open",artifactId:v}))===!0||(l.preventDefault(),l.stopPropagation(),Hr=!1,_.selectArtifact(v),Yr())}),Xe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;f.hasAttribute("data-open-artifact")&&(l.preventDefault(),f.click())});let lo=J.composerOverlay,co=(l,f,h)=>{var O,D,oe,ne;let v=f.trim();if(!v||!Et.current)return;let I=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",F=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:I,answer:v,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?v.split(", "):[v],isFreeText:F,source:h.source},bubbles:!0,composed:!0})),Ln(lo,I);let $=Et.current.getMessages().find(X=>{var ye;return((ye=X.toolCall)==null?void 0:ye.id)===I});(oe=$==null?void 0:$.agentMetadata)!=null&&oe.awaitingLocalTool?Et.current.resolveAskUserQuestion($,(ne=h.structured)!=null?ne:v):Et.current.sendMessage(v)},Qr=l=>{var I;let f=Et.current;if(!f)return;let h=(I=l.getAttribute("data-tool-call-id"))!=null?I:"",v=f.getMessages().find(F=>{var $;return(($=F.toolCall)==null?void 0:$.id)===h});v&&f.persistAskUserQuestionProgress(v,{answers:wi(l,v),currentIndex:go(l)})},mn=l=>Object.entries(l).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),jo=l=>{var I,F,$;if(((F=(I=o.features)==null?void 0:I.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let f=go(l),h=Ba(l);if(f>=h-1)return;let v=($=Et.current)==null?void 0:$.getMessages().find(O=>{var D;return((D=O.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});v&&(Si(l,v,o,f+1),Qr(l))};lo.addEventListener("click",l=>{var F,$,O,D,oe,ne,X,ye,Fe,Se,tt,$e,mt,st;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 I=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),I==="dismiss"){let Ie=(F=v.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Ln(lo,Ie);let Le=($=Et.current)==null?void 0:$.getMessages().find(ze=>{var Ke;return((Ke=ze.toolCall)==null?void 0:Ke.id)===Ie});(O=Le==null?void 0:Le.agentMetadata)!=null&&O.awaitingLocalTool&&((D=Et.current)==null||D.markAskUserQuestionResolved(Le),(oe=Et.current)==null||oe.resolveAskUserQuestion(Le,"(dismissed)"));return}if(I==="pick"){let Ie=h.getAttribute("data-option-label");if(!Ie)return;let Le=v.getAttribute("data-multi-select")==="true",ze=kn(v);if(ze&&Le){let Ke=ta(v)[go(v)],bt=new Set(Array.isArray(Ke)?Ke:[]);bt.has(Ie)?bt.delete(Ie):bt.add(Ie),Pn(v,Array.from(bt)),Qr(v);return}if(ze){Pn(v,Ie),Qr(v),jo(v);return}if(Le){let Ke=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ke?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ke);let bt=v.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=Zl(v).length===0);return}co(v,Ie,{source:"pick",values:[Ie]});return}if(I==="submit-multi"){let Ie=Zl(v);if(Ie.length===0)return;co(v,Ie.join(", "),{source:"multi",values:Ie});return}if(I==="open-free-text"){let Ie=v.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Le=Ie.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(I==="focus-free-text"){let Ie=v.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(I==="submit-free-text"){let Ie=v.querySelector('[data-ask-free-text-input="true"]'),Le=(ne=Ie==null?void 0:Ie.value)!=null?ne:"";if(!Le.trim())return;if(kn(v)){Pn(v,Le.trim()),Qr(v),jo(v);return}co(v,Le,{source:"free-text"});return}if(I==="next"||I==="back"){if(!Et.current)return;let Ie=(X=v.getAttribute("data-tool-call-id"))!=null?X:"",Le=Et.current.getMessages().find(We=>{var Re;return((Re=We.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let ze=v.querySelector('[data-ask-free-text-input="true"]'),Ke=(Fe=(ye=ze==null?void 0:ze.value)==null?void 0:ye.trim())!=null?Fe:"";if(Ke){let We=ta(v)[go(v)];(typeof We!="string"||We!==Ke)&&Pn(v,Ke)}let bt=I==="next"?1:-1,B=go(v)+bt;Si(v,Le,o,B),Qr(v);return}if(I==="submit-all"){if(!Et.current)return;let Ie=(Se=v.getAttribute("data-tool-call-id"))!=null?Se:"",Le=Et.current.getMessages().find(We=>{var Re;return((Re=We.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let ze=v.querySelector('[data-ask-free-text-input="true"]'),Ke=($e=(tt=ze==null?void 0:ze.value)==null?void 0:tt.trim())!=null?$e:"";Ke&&Pn(v,Ke);let bt=wi(v,Le);Et.current.persistAskUserQuestionProgress(Le,{answers:bt,currentIndex:go(v)});let B=mn(bt);co(v,B||"(submitted)",{source:"submit-all",structured:bt});return}if(I==="skip"){if(!Et.current)return;let Ie=(mt=v.getAttribute("data-tool-call-id"))!=null?mt:"",Le=Et.current.getMessages().find(Re=>{var fe;return((fe=Re.toolCall)==null?void 0:fe.id)===Ie});if(!Le)return;let ze=kn(v),Ke=go(v),bt=Ba(v),B=Ke>=bt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Ln(lo,Ie),(st=Le.agentMetadata)!=null&&st.awaitingLocalTool&&(Et.current.markAskUserQuestionResolved(Le),Et.current.resolveAskUserQuestion(Le,"(dismissed)"));return}Pn(v,"");let We=v.querySelector('[data-ask-free-text-input="true"]');if(We&&(We.value=""),B){let Re=wi(v,Le),fe=mn(Re);co(v,fe||"(skipped)",{source:"submit-all",structured:Re});return}Si(v,Le,o,Ke+1),Qr(v);return}}),lo.addEventListener("keydown",l=>{var F;if(l.key!=="Enter")return;let h=l.target;if(!((F=h.matches)!=null&&F.call(h,'[data-ask-free-text-input="true"]')))return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;l.preventDefault();let I=h.value;if(I.trim()){if(kn(v)){Pn(v,I.trim()),Qr(v),jo(v);return}co(v,I,{source:"free-text"})}});let gn=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=lo.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),F=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];F&&(l.preventDefault(),F.click())};document.addEventListener("keydown",gn);let Jr=null,Ut=null,Br=null,po=null,hn=()=>{};function Go(){po==null||po(),po=null}let xn=()=>{var $;if(!Jr||!Ut)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){Ut.style.removeProperty("position"),Ut.style.removeProperty("left"),Ut.style.removeProperty("top"),Ut.style.removeProperty("bottom"),Ut.style.removeProperty("width"),Ut.style.removeProperty("z-index");return}let v=Jr.firstElementChild;if(!v||v===Ut)return;let I=10;Ut.style.position="absolute",Ut.style.top="0",Ut.style.bottom="0",Ut.style.width=`${I}px`,Ut.style.zIndex="5";let F=v.offsetWidth-I/2;Ut.style.left=`${Math.max(0,F)}px`},Po=()=>{},Yr=()=>{var h,v,I,F,$;if(!At||!ho(o))return;Al(e,o),Ml(e,o),Po();let l=(F=(I=(v=(h=o.features)==null?void 0:h.artifacts)==null?void 0:v.layout)==null?void 0:I.narrowHostMaxWidth)!=null?F:520,f=be.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l),At.update(Xr),Hr?(At.setMobileOpen(!1),At.element.classList.add("persona-hidden"),($=At.backdrop)==null||$.classList.add("persona-hidden")):Xr.artifacts.length>0&&(At.element.classList.remove("persona-hidden"),At.setMobileOpen(!0)),hn()};if(ho(o)){be.style.position="relative";let l=A("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=A("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ce),At=Kh(o,{onSelect:h=>{var v;return(v=Et.current)==null?void 0:v.selectArtifact(h)},onDismiss:()=>{Hr=!0,Yr()}}),At.element.classList.add("persona-hidden"),Jr=f,f.appendChild(l),f.appendChild(At.element),At.backdrop&&be.appendChild(At.backdrop),be.appendChild(f),hn=()=>{var v,I,F,$;if(!Jr||!At)return;if(!(((F=(I=(v=o.features)==null?void 0:v.artifacts)==null?void 0:I.layout)==null?void 0:F.resizable)===!0)){Br==null||Br(),Br=null,Go(),Ut&&(Ut.remove(),Ut=null),At.element.style.removeProperty("width"),At.element.style.removeProperty("maxWidth");return}if(!Ut){let O=A("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 D=e.ownerDocument,oe=($=D.defaultView)!=null?$:window,ne=X=>{var mt,st;if(!At||X.button!==0||e.classList.contains("persona-artifact-narrow-host")||oe.innerWidth<=640)return;X.preventDefault(),Go();let ye=X.clientX,Fe=At.element.getBoundingClientRect().width,Se=(st=(mt=o.features)==null?void 0:mt.artifacts)==null?void 0:st.layout,tt=Ie=>{let Le=Jr.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Ke=ze?0:Yh(Jr,oe),bt=ze?0:O.getBoundingClientRect().width||6,B=Fe-(Ie.clientX-ye),We=Zh(B,Le,Ke,bt,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);At.element.style.width=`${We}px`,At.element.style.maxWidth="none",xn()},$e=()=>{D.removeEventListener("pointermove",tt),D.removeEventListener("pointerup",$e),D.removeEventListener("pointercancel",$e),po=null;try{O.releasePointerCapture(X.pointerId)}catch{}};po=$e,D.addEventListener("pointermove",tt),D.addEventListener("pointerup",$e),D.addEventListener("pointercancel",$e);try{O.setPointerCapture(X.pointerId)}catch{}};O.addEventListener("pointerdown",ne),Ut=O,Jr.insertBefore(O,At.element),Br=()=>{O.removeEventListener("pointerdown",ne)}}if(Ut){let O=Xr.artifacts.length>0&&!Hr;Ut.classList.toggle("persona-hidden",!O),xn()}},Po=()=>{var oe,ne,X,ye,Fe,Se,tt,$e,mt,st,Ie,Le,ze,Ke;if(!E||!At||((ne=(oe=o.launcher)==null?void 0:oe.sidebarMode)!=null?ne:!1)||ur(o)&&ao(o).reveal==="emerge")return;let v=(X=e.ownerDocument.defaultView)!=null?X:window,I=(Fe=(ye=o.launcher)==null?void 0:ye.mobileFullscreen)!=null?Fe:!0,F=(tt=(Se=o.launcher)==null?void 0:Se.mobileBreakpoint)!=null?tt:640;if(I&&v.innerWidth<=F||!Jh(o,E))return;let $=(st=(mt=($e=o.launcher)==null?void 0:$e.width)!=null?mt:o.launcherWidth)!=null?st:no,O=(Ke=(ze=(Le=(Ie=o.features)==null?void 0:Ie.artifacts)==null?void 0:Le.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";Xr.artifacts.length>0&&!Hr?(be.style.width=O,be.style.maxWidth=O):(be.style.width=$,be.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Kr=new ResizeObserver(()=>{Yr()}),Kr.observe(be))}else be.appendChild(ce),W()&&Je&&(J.peekBanner&&Je.appendChild(J.peekBanner),Je.appendChild(He));e.appendChild(Ue),Je&&e.appendChild(Je);let xe=()=>{var We,Re,fe,zt,Vt,Jt,Ct,Xt,to,ar,Qe,Wt,pr,mo,ro,jn,Gn,Ea,ka,Yt,Kn,Mn,Tn,en,Xn,Co,Ze,hr;if(W()){be.style.width="100%",be.style.maxWidth="100%";let Gt=(Re=(We=o.launcher)==null?void 0:We.composerBar)!=null?Re:{},jt=Ue.dataset.state==="expanded",gt=(fe=Gt.expandedSize)!=null?fe:"anchored";if(!(jt&&gt!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let Mt=(Vt=(zt=o.theme)==null?void 0:zt.components)==null?void 0:Vt.panel,Lr=Va(o),Dr=(Nr,Qn)=>{var ms;return Nr==null||Nr===""?Qn:(ms=Ua(Lr,Nr))!=null?ms:Nr},_o="1px solid var(--persona-border)",wr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Fr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=Dr(Mt==null?void 0:Mt.border,_o),ce.style.borderRadius=Dr(Mt==null?void 0:Mt.borderRadius,Fr),ce.style.boxShadow=Dr(Mt==null?void 0:Mt.shadow,wr),ce.style.overflow="hidden";return}let l=ur(o),f=(Ct=(Jt=o.launcher)==null?void 0:Jt.sidebarMode)!=null?Ct:!1,h=l||f||((to=(Xt=o.launcher)==null?void 0:Xt.fullHeight)!=null?to:!1),v=((ar=o.launcher)==null?void 0:ar.enabled)===!1,I=(Wt=(Qe=o.theme)==null?void 0:Qe.components)==null?void 0:Wt.panel,F=Va(o),$=(Gt,jt)=>{var gt;return Gt==null||Gt===""?jt:(gt=Ua(F,Gt))!=null?gt:Gt},O=(pr=e.ownerDocument.defaultView)!=null?pr:window,D=(ro=(mo=o.launcher)==null?void 0:mo.mobileFullscreen)!=null?ro:!0,oe=(Gn=(jn=o.launcher)==null?void 0:jn.mobileBreakpoint)!=null?Gn:640,ne=O.innerWidth<=oe,X=D&&ne&&E,ye=(ka=(Ea=o.launcher)==null?void 0:Ea.position)!=null?ka:"bottom-left",Fe=ye==="bottom-left"||ye==="top-left",Se=(Kn=(Yt=o.launcher)==null?void 0:Yt.zIndex)!=null?Kn:Rr,tt=f||X?"none":"1px solid var(--persona-border)",$e=X?"none":f?Fe?"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&&!X&&($e="none",tt="none");let mt=f||X?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=$(I==null?void 0:I.border,tt),Ie=$(I==null?void 0:I.shadow,$e),Le=$(I==null?void 0:I.borderRadius,mt),ze=Te.scrollTop;e.style.cssText="",Ue.style.cssText="",be.style.cssText="",ce.style.cssText="",Te.style.cssText="",He.style.cssText="";let Ke=()=>{var jt;if(ze<=0)return;((jt=Te.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(Te.scrollTop===ze)return;let gt=Te.scrollHeight-Te.clientHeight;gt<=0||(Te.scrollTop=Math.min(ze,gt))})};if(X){Ue.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"),Ue.style.cssText=`
34
34
  position: fixed !important;
35
35
  inset: 0 !important;
36
36
  width: 100% !important;
@@ -55,7 +55,7 @@ _Details: ${r.message}_`:o}var Rs=e=>({isError:!0,content:[{type:"text",text:e}]
55
55
  padding: 0 !important;
56
56
  box-shadow: none !important;
57
57
  border-radius: 0 !important;
58
- `,pe.style.cssText=`
58
+ `,ce.style.cssText=`
59
59
  display: flex !important;
60
60
  flex-direction: column !important;
61
61
  flex: 1 1 0% !important;
@@ -66,11 +66,11 @@ _Details: ${r.message}_`:o}var Rs=e=>({isError:!0,content:[{type:"text",text:e}]
66
66
  overflow: hidden !important;
67
67
  border-radius: 0 !important;
68
68
  border: none !important;
69
- `,Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",Ne.style.flexShrink="0",A=!0,Qe();return}let xt=(Tn=(Mn=o==null?void 0:o.launcher)==null?void 0:Mn.width)!=null?Tn:o==null?void 0:o.launcherWidth,B=xt!=null?xt:oo;if(!f&&!l)v&&h?(be.style.width="100%",be.style.maxWidth="100%"):(be.style.width=B,be.style.maxWidth=B);else if(l)if(no(o).reveal==="emerge"){let qt=no(o).width;be.style.width=qt,be.style.maxWidth=qt}else be.style.width="100%",be.style.maxWidth="100%";if(Ro(),be.style.boxShadow=Le,be.style.borderRadius=Ee,pe.style.border=st,pe.style.borderRadius=Ee,l&&!Q&&(R==null?void 0:R.border)===void 0&&(pe.style.border="none",no(o).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.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%"),_e.style.display="flex",_e.style.flexDirection="column",_e.style.flex="1 1 0%",_e.style.minHeight="0",_e.style.maxHeight="100%",_e.style.height="100%",v&&(_e.style.overflow="hidden"),be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.height="100%",be.style.overflow="hidden",pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.overflow="hidden",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",Ne.style.flexShrink="0"),_e.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&&((en=To[ye])!=null?en:To["bottom-right"]).split(" ").forEach(qt=>_e.classList.add(qt)),f){let Vt=(wo=(Xn=o.launcher)==null?void 0:Xn.sidebarWidth)!=null?wo:"420px";_e.style.cssText=`
69
+ `,Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.overflowY="auto",He.style.flexShrink="0",M=!0,Ke();return}let bt=(Tn=(Mn=o==null?void 0:o.launcher)==null?void 0:Mn.width)!=null?Tn:o==null?void 0:o.launcherWidth,B=bt!=null?bt:no;if(!f&&!l)v&&h?(be.style.width="100%",be.style.maxWidth="100%"):(be.style.width=B,be.style.maxWidth=B);else if(l)if(ao(o).reveal==="emerge"){let jt=ao(o).width;be.style.width=jt,be.style.maxWidth=jt}else be.style.width="100%",be.style.maxWidth="100%";if(Po(),be.style.boxShadow=Ie,be.style.borderRadius=Le,ce.style.border=st,ce.style.borderRadius=Le,l&&!X&&(I==null?void 0:I.border)===void 0&&(ce.style.border="none",ao(o).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.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%"),Ue.style.display="flex",Ue.style.flexDirection="column",Ue.style.flex="1 1 0%",Ue.style.minHeight="0",Ue.style.maxHeight="100%",Ue.style.height="100%",v&&(Ue.style.overflow="hidden"),be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.height="100%",be.style.overflow="hidden",ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.overflow="hidden",Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.overflowY="auto",He.style.flexShrink="0"),Ue.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&&((en=Mo[ye])!=null?en:Mo["bottom-right"]).split(" ").forEach(jt=>Ue.classList.add(jt)),f){let Gt=(Co=(Xn=o.launcher)==null?void 0:Xn.sidebarWidth)!=null?Co:"420px";Ue.style.cssText=`
70
70
  position: fixed !important;
71
71
  top: 0 !important;
72
72
  bottom: 0 !important;
73
- width: ${Vt} !important;
73
+ width: ${Gt} !important;
74
74
  height: 100vh !important;
75
75
  max-height: 100vh !important;
76
76
  margin: 0 !important;
@@ -78,7 +78,7 @@ _Details: ${r.message}_`:o}var Rs=e=>({isError:!0,content:[{type:"text",text:e}]
78
78
  display: flex !important;
79
79
  flex-direction: column !important;
80
80
  z-index: ${Se} !important;
81
- ${He?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
81
+ ${Fe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
82
82
  `,be.style.cssText=`
83
83
  position: relative !important;
84
84
  display: flex !important;
@@ -90,9 +90,9 @@ _Details: ${r.message}_`:o}var Rs=e=>({isError:!0,content:[{type:"text",text:e}]
90
90
  min-height: 0 !important;
91
91
  margin: 0 !important;
92
92
  padding: 0 !important;
93
- box-shadow: ${Le} !important;
94
- border-radius: ${Ee} !important;
95
- `,be.style.setProperty("width","100%","important"),be.style.setProperty("max-width","100%","important"),pe.style.cssText=`
93
+ box-shadow: ${Ie} !important;
94
+ border-radius: ${Le} !important;
95
+ `,be.style.setProperty("width","100%","important"),be.style.setProperty("max-width","100%","important"),ce.style.cssText=`
96
96
  display: flex !important;
97
97
  flex-direction: column !important;
98
98
  flex: 1 1 0% !important;
@@ -101,29 +101,29 @@ _Details: ${r.message}_`:o}var Rs=e=>({isError:!0,content:[{type:"text",text:e}]
101
101
  min-height: 0 !important;
102
102
  max-height: 100% !important;
103
103
  overflow: hidden !important;
104
- border-radius: ${Ee} !important;
104
+ border-radius: ${Le} !important;
105
105
  border: ${st} !important;
106
- `,Ne.style.cssText=`
106
+ `,He.style.cssText=`
107
107
  flex-shrink: 0 !important;
108
108
  border-top: none !important;
109
109
  padding: 8px 16px 12px 16px !important;
110
- `}if(!v&&!l){let Vt="max-height: -moz-available !important; max-height: stretch !important;",qt=f?"":"padding-top: 1.25em !important;",ft=f?"":`z-index: ${(gr=(rt=o.launcher)==null?void 0:rt.zIndex)!=null?gr:Lr} !important;`;_e.style.cssText+=Vt+qt+ft}Qe()};xe(),Wn(e,o),wl(e,o),Sl(e,o);let dt=[];dt.push(()=>{document.removeEventListener("keydown",gn)});let tr=null,fr=null;dt.push(()=>{tr==null||tr(),tr=null,fr==null||fr(),fr=null}),Gr&&dt.push(()=>{Gr==null||Gr.disconnect(),Gr=null}),dt.push(()=>{Wr==null||Wr(),Wr=null,Ko(),Nt&&(Nt.remove(),Nt=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Ie&&dt.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),G==null||G.destroy(),G=null,ge==null||ge.destroy(),ge=null,J=null});let Io=null,es=()=>{Io&&(Io(),Io=null),o.colorScheme==="auto"&&(Io=el(()=>{Wn(e,o)}))};es(),dt.push(()=>{Io&&(Io(),Io=null)});let Xo=(Qu=o.features)==null?void 0:Qu.streamAnimation;if(Xo!=null&&Xo.type&&Xo.type!=="none"){let l=Ds(Xo.type,Xo.plugins);l&&(up(l,e),dt.push(()=>wh(e)))}let qn=Nh(Ge),Wo=null,_,ha=l=>{var v,R;if(!_)return;let f=l!=null?l:_.getMessages(),h=((R=(v=o.features)==null?void 0:v.suggestReplies)==null?void 0:R.enabled)!==!1?Ai(f):null;h?qn.render(h,_,ke,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(F=>F.role==="user")?qn.render([],_,ke,f):qn.render(o.suggestionChips,_,ke,f,o.suggestionChipsConfig)},Ho=!1,Bo=fh(),Qo=new Map,Do=new Map,bo=new Map,xa=0,Qs=Ia()!==null,Yr=ol(),Zr=0,vo=null,Co=!1,Vn=!1,Jo=0,Mr=null,Fo=null,ya=!1,$n=!1,ba=null,Js=4,va=24,Ys=80,Ca=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ts=(Yu=(Ju=o.voiceRecognition)==null?void 0:Ju.autoResume)!=null?Yu:!1,po=l=>{a.emit("voice:state",{active:mt.active,source:l,timestamp:Date.now()})},Vr=()=>{m(l=>({...l,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},Zs=()=>{var v,R;if(((v=o.voiceRecognition)==null?void 0:v.enabled)===!1)return;let l=Ip(c.voiceState),f=!!l.active,h=Number((R=l.timestamp)!=null?R:0);mt.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-h<Pv&&setTimeout(()=>{var F,$;mt.active||(mt.manuallyDeactivated=!1,(($=(F=o.voiceRecognition)==null?void 0:F.provider)==null?void 0:$.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("restore"),_.isVoiceActive()&&Ta()}):di("restore"))},1e3)},ei=()=>_?ox(_.getMessages()).filter(l=>!l.__skipPersist):[];function wa(l){if(!(i!=null&&i.save))return;let h={messages:l?ox(l):_?ei():[],metadata:c,artifacts:Kr.artifacts,selectedArtifactId:Kr.selectedId};try{let v=i.save(h);v instanceof Promise&&v.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",v)}}let Yo=null,rs=()=>_e.querySelector("#persona-scroll-container")||Me,yn=()=>{Yo!==null&&(cancelAnimationFrame(Yo),Yo=null),Co=!1},os=()=>{vo!==null&&(cancelAnimationFrame(vo),vo=null),Vn=!1,yn()},ns=()=>{Jo>0?(Rr.textContent=String(Jo),Rr.style.display="",lt.setAttribute("aria-label",`${sr()||"Jump to latest"} (${Jo} new)`)):(Rr.textContent="",Rr.style.display="none",lt.setAttribute("aria-label",sr()||"Jump to latest"))},as=()=>{Jo!==0&&(Jo=0,ns())},ss=()=>ot()==="follow"?!Yr.isFollowing():!da(Me,va),$r=()=>{if(!Ft()||ce){lt.parentNode&&lt.remove(),lt.style.display="none";return}lt.parentNode!==pe&&pe.appendChild(lt),Ur();let f=sn(Me)>0&&ss();f||as(),lt.style.display=f?"":"none"},Sa=()=>{Yr.pause()&&(os(),$r())},No=()=>{Yr.resume(),as(),$r()},Oo=(l=!1)=>{ot()==="follow"&&Yr.isFollowing()&&(!l&&!Ho||(vo!==null&&(cancelAnimationFrame(vo),vo=null),Vn=!0,vo=requestAnimationFrame(()=>{vo=null,Vn=!1,Yr.isFollowing()&&ti(rs(),l?220:140)})))},is=(l,f,h,v=()=>!0)=>{let R=l.scrollTop,F=f(),$=F-R;yn();let O=performance.now();Co=!0;let D=se=>1-Math.pow(1-se,3),ae=se=>{if(!v()){yn();return}let Q=f();Q!==F&&(F=Q,$=F-R);let ye=se-O,He=Math.min(ye/h,1),Se=D(He),nt=R+$*Se;l.scrollTop=nt,Zr=l.scrollTop,He<1?Yo=requestAnimationFrame(ae):(l.scrollTop=F,Zr=l.scrollTop,Yo=null,Co=!1)};Yo=requestAnimationFrame(ae)},ti=(l,f=500)=>{let h=sn(l)-l.scrollTop;if(Math.abs(h)<1){Zr=l.scrollTop;return}if(Math.abs(h)>=Ys){yn(),Co=!0,l.scrollTop=sn(l),Zr=l.scrollTop,Co=!1;return}is(l,()=>sn(l),f,()=>Yr.isFollowing())},ls=()=>{let l=rs();Co=!0,l.scrollTop=sn(l),Zr=l.scrollTop,Co=!1,$r()},ds=l=>{ir.style.height=`${Math.max(0,Math.round(l))}px`,Mr&&(Mr.spacerHeight=Math.max(0,l))},zn=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null),yn(),Mr=null,ir.style.height="0px"},ri=l=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=requestAnimationFrame(()=>{var ae;Fo=null;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Me.querySelector(`[data-message-id="${f}"]`);if(!h)return;let v=0,R=h;for(;R&&R!==Me;)v+=R.offsetTop,R=R.offsetParent;let F=(ae=Mr==null?void 0:Mr.spacerHeight)!=null?ae:0,$=Me.scrollHeight-F,{targetScrollTop:O,spacerHeight:D}=yh({anchorOffsetTop:v,topOffset:Dt(),viewportHeight:Me.clientHeight,contentHeight:$});Mr={initialSpacerHeight:D,contentHeightAtAnchor:$,spacerHeight:D},ds(D),is(Me,()=>O,220)})},oi=()=>{if(ot()==="follow"){if(!Yr.isFollowing()||da(Me,1))return;Oo(!Ho);return}if(Mr&&Mr.initialSpacerHeight>0){let l=Me.scrollHeight-Mr.spacerHeight,f=bh({initialSpacerHeight:Mr.initialSpacerHeight,contentHeightAtAnchor:Mr.contentHeightAtAnchor,currentContentHeight:l});f!==Mr.spacerHeight&&ds(f)}$r()},ni=l=>{let f=ot();f==="follow"?(No(),Oo(!0)):f==="anchor-top"&&ri(l)},ai=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),!$n&&ot()!=="anchor-top"&&ss()&&(Jo+=1,ns(),$r())),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)})},si=(l,f,h)=>{var st,Le,Ee,ze,Qe,xt;let v=document.createElement("div"),F=(()=>{var Re;let B=n.find(Pe=>Pe.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Re=o.loadingIndicator)!=null&&Re.render)return o.loadingIndicator.render})(),$=(B,Re)=>Re==null?!1:typeof Re=="string"?(B.textContent=Re,!0):(B.appendChild(Re),!0),O=new Set,D=new Set,ae=n.some(B=>B.renderAskUserQuestion),se=[],Q=[],ye=o.enableComponentStreaming!==!1,He=n.some(B=>B.renderApproval)&&o.approval!==!1,Se=[];if(f.forEach(B=>{var Ye,Rt,cr,go,to,jn,Gn,ka,La,Xt,Kn,Mn,Tn,en,Xn,wo;O.add(B.id);let Re=ae&&rn(B),Pe=He&&B.variant==="approval"&&!!B.approval,fe=!Re&&B.role==="assistant"&&!B.variant&&ye&&El(B);if(!Pe&&bo.has(B.id)){let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),bo.delete(B.id)}if(!fe&&Do.has(B.id)){let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),Do.delete(B.id)}let Ut=rn(B)?`:${(Ye=B.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Rt=B.agentMetadata)!=null&&Rt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=uh(B,xa)+Ut,Kt=Re||Pe||fe?null:mh(Bo,B.id,Ot);if(Kt){v.appendChild(Kt.cloneNode(!0)),rn(B)&&((cr=B.toolCall)!=null&&cr.id)&&((go=B.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((to=B.agentMetadata)!=null&&to.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Fa(B,o,Y.composerOverlay));return}let bt=null,zt=n.find(rt=>!!(B.variant==="reasoning"&&rt.renderReasoning||B.variant==="tool"&&rt.renderToolCall||!B.variant&&rt.renderMessage)),eo=(jn=o.layout)==null?void 0:jn.messages;if(rn(B)&&((Gn=B.agentMetadata)==null?void 0:Gn.askUserQuestionAnswered)===!0){Qo.delete(B.id);let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(As(B)&&((La=(ka=o.features)==null?void 0:ka.suggestReplies)==null?void 0:La.enabled)!==!1)return;if(rn(B)&&((Kn=(Xt=o.features)==null?void 0:Xt.askUserQuestion)==null?void 0:Kn.enabled)!==!1){let rt=n.find(gr=>typeof gr.renderAskUserQuestion=="function");if(rt&&Mt.current){let gr=Qo.get(B.id),Vt=gr!==Ot,qt=null;if(Vt){let{payload:St,complete:Tr}=on(B),Br=B.id,Uo=()=>{var vr;return(vr=Mt.current)==null?void 0:vr.getMessages().find(Dr=>Dr.id===Br)};qt=rt.renderAskUserQuestion({message:B,payload:St,complete:Tr,resolve:vr=>{var Fr;let Dr=Uo();Dr&&((Fr=Mt.current)==null||Fr.resolveAskUserQuestion(Dr,vr))},dismiss:()=>{var Dr,Fr,Qn;let vr=Uo();(Dr=vr==null?void 0:vr.agentMetadata)!=null&&Dr.awaitingLocalTool&&((Fr=Mt.current)==null||Fr.markAskUserQuestionResolved(vr),(Qn=Mt.current)==null||Qn.resolveAskUserQuestion(vr,"(dismissed)"))},config:o})}let ft=gr!=null;if(Vt&&qt===null&&!ft){((Mn=B.agentMetadata)==null?void 0:Mn.awaitingLocalTool)===!0&&!((Tn=B.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Fa(B,o,Y.composerOverlay));return}let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-ask-plugin-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),v.appendChild(Qt),se.push({messageId:B.id,fingerprint:Ot,bubble:qt});return}else{((en=B.agentMetadata)==null?void 0:en.awaitingLocalTool)===!0&&!((Xn=B.agentMetadata)!=null&&Xn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Fa(B,o,Y.composerOverlay));return}}else if(Pe){let rt=n.find(ft=>typeof ft.renderApproval=="function"),Vt=bo.get(B.id)!==Ot,qt=null;if(Vt&&(rt!=null&&rt.renderApproval)){let ft=B.id,Qt=(St,Tr)=>{var Uo,vr,Dr;let Br=(Uo=Mt.current)==null?void 0:Uo.getMessages().find(Fr=>Fr.id===ft);Br!=null&&Br.approval&&(Br.approval.toolType==="webmcp"?(vr=Mt.current)==null||vr.resolveWebMcpApproval(Br.id,St):(Dr=Mt.current)==null||Dr.resolveApproval(Br.approval,St,Tr))};qt=rt.renderApproval({message:B,defaultRenderer:()=>vl(B,o),config:o,approve:St=>Qt("approved",St),deny:St=>Qt("denied",St)})}if(Vt&&qt===null){let ft=l.querySelector(`#wrapper-${B.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),bo.delete(B.id),bt=vl(B,o)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${B.id}`,ft.setAttribute("data-wrapper-id",B.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),v.appendChild(ft),Se.push({messageId:B.id,fingerprint:Ot,bubble:qt});return}}else if(zt)if(B.variant==="reasoning"&&B.reasoning&&zt.renderReasoning){if(!Ke)return;bt=zt.renderReasoning({message:B,defaultRenderer:()=>Ap(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&zt.renderToolCall){if(!Ce)return;bt=zt.renderToolCall({message:B,defaultRenderer:()=>Mp(B,o),config:o})}else zt.renderMessage&&(bt=zt.renderMessage({message:B,defaultRenderer:()=>{let rt=Ga(B,h,eo,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o});return B.role!=="user"&&Lp(rt,B,o,_),rt},config:o}));if(!bt&&fe){let rt=kl(B);if(rt){let gr=Do.get(B.id),Vt=gr!==Ot,qt=o.wrapComponentDirectiveInBubble!==!1,ft=null;if(Vt){let Qt=Tl(rt,{config:o,message:B,transform:h});if(Qt)if(qt){let St=document.createElement("div");if(St.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(" "),St.id=`bubble-${B.id}`,St.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let Tr=document.createElement("div");Tr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Tr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),St.appendChild(Tr)}St.appendChild(Qt),ft=St}else{let St=document.createElement("div");if(St.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",St.id=`bubble-${B.id}`,St.setAttribute("data-message-id",B.id),St.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let Tr=document.createElement("div");Tr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Tr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),St.appendChild(Tr)}St.appendChild(Qt),ft=St}}if(ft||gr!=null){let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-component-directive-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),qt||Qt.classList.add("persona-w-full"),v.appendChild(Qt),Q.push({messageId:B.id,fingerprint:Ot,bubble:ft});return}}}if(!bt)if(B.variant==="reasoning"&&B.reasoning){if(!Ke)return;bt=Ap(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!Ce)return;bt=Mp(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;bt=vl(B,o)}else{let rt=(wo=o.layout)==null?void 0:wo.messages;rt!=null&&rt.renderUserMessage&&B.role==="user"?bt=rt.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):rt!=null&&rt.renderAssistantMessage&&B.role==="assistant"?bt=rt.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):bt=Ga(B,h,rt,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o}),B.role!=="user"&&bt&&Lp(bt,B,o,_)}let or=document.createElement("div");or.className="persona-flex",or.id=`wrapper-${B.id}`,or.setAttribute("data-wrapper-id",B.id),B.role==="user"&&or.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&or.classList.add("persona-w-full"),or.appendChild(bt),gh(Bo,B.id,Ot,or),v.appendChild(or)}),Y.composerOverlay&&Y.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Pe=Re.getAttribute("data-persona-ask-sheet-for");Pe&&!D.has(Pe)&&Ln(Y.composerOverlay,Pe)}),(Le=(st=o.features)==null?void 0:st.toolCallDisplay)!=null&&Le.grouped){let B=[],Re=[];f.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ce){Re.push(Pe);return}Re.length>1&&B.push(Re),Re=[]}),Re.length>1&&B.push(Re),B.forEach((Pe,fe)=>{var Ye,Rt;let Ut=Pe.map(cr=>Array.from(v.children).find(go=>go instanceof HTMLElement&&go.getAttribute("data-wrapper-id")===cr.id)).filter(cr=>!!cr);if(Ut.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${fe}-${Pe[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${fe}-${Pe[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.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 zt=`Called ${Pe.length} tools`,eo=(Rt=(Ye=o.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Rt.call(Ye,{messages:Pe,toolCalls:Pe.map(cr=>cr.toolCall).filter(cr=>!!cr),defaultSummary:zt,config:o});$(bt,eo)||(bt.textContent=zt);let or=document.createElement("div");or.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(bt,or),Ot.appendChild(Kt),Ut[0].before(Ot),Ut.forEach((cr,go)=>{let to=document.createElement("div");to.className="persona-tool-group-item persona-relative",to.setAttribute("data-persona-tool-group-item","true"),go<Ut.length-1&&to.setAttribute("data-persona-tool-group-connector","true"),to.appendChild(cr),or.appendChild(to)})})}hh(Bo,O);let nt=f.some(B=>B.role==="assistant"&&B.streaming),$e=f[f.length-1],ut=($e==null?void 0:$e.role)==="assistant"&&!$e.streaming&&$e.variant!=="approval";if(Ho&&f.some(B=>B.role==="user")&&!nt&&!ut){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ua},Re=n.find(fe=>fe.renderLoadingIndicator),Pe=null;if(Re!=null&&Re.renderLoadingIndicator&&(Pe=Re.renderLoadingIndicator(B)),Pe===null&&((Ee=o.loadingIndicator)!=null&&Ee.render)&&(Pe=o.loadingIndicator.render(B)),Pe===null&&(Pe=ua()),Pe){let fe=document.createElement("div"),Ut=((ze=o.loadingIndicator)==null?void 0:ze.showBubble)!==!1;fe.className=Ut?["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(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Pe);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(fe),v.appendChild(Ot)}}if(!Ho&&f.length>0){let B=f[f.length-1],Re={config:o,lastMessage:B,messageCount:f.length},Pe=n.find(Ut=>Ut.renderIdleIndicator),fe=null;if(Pe!=null&&Pe.renderIdleIndicator&&(fe=Pe.renderIdleIndicator(Re)),fe===null&&((Qe=o.loadingIndicator)!=null&&Qe.renderIdle)&&(fe=o.loadingIndicator.renderIdle(Re)),fe){let Ut=document.createElement("div"),Ot=((xt=o.loadingIndicator)==null?void 0:xt.showBubble)!==!1;Ut.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ut.setAttribute("data-idle-indicator","true"),Ut.appendChild(fe);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Ut),v.appendChild(Kt)}}if(tl(l,v),se.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of se){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),Qo.set(B,Re))}if(Qo.size>0)for(let B of Qo.keys())O.has(B)||Qo.delete(B);if(Q.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of Q){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),Do.set(B,Re))}if(Do.size>0)for(let B of Do.keys())O.has(B)||Do.delete(B);if(Se.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of Se){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),bo.set(B,Re))}if(bo.size>0)for(let B of bo.keys())O.has(B)||bo.delete(B)},bn=(l,f,h)=>{si(l,f,h),fn()},vn=null,ii=()=>{var h;if(vn)return;let l=v=>{let R=v.composedPath();R.includes(_e)||Ze&&R.includes(Ze)||I(!1,"user")};vn=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},cs=()=>{var f;if(!vn)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",vn,!0),vn=null};dt.push(()=>cs());let Cn=null,li=()=>{var h;if(Cn)return;let l=v=>{v.key==="Escape"&&(v.isComposing||I(!1,"user"))};Cn=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},ps=()=>{var f;if(!Cn)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Cn,!0),Cn=null};dt.push(()=>ps());let wn=!1,us=new Set,Aa=()=>{var f,h,v,R;let l=(v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:v.streamAnimation;return l||((R=o.features)==null?void 0:R.streamAnimation)},Ve=()=>{var ut,st,Le,Ee;if(!H())return;let l=Y.peekBanner,f=Y.peekTextNode;if(!l||!f)return;if(k){l.classList.remove("persona-pill-peek--visible");return}let h=(ut=_==null?void 0:_.getMessages())!=null?ut:[],v;for(let ze=h.length-1;ze>=0;ze--){let Qe=h[ze];if(Qe.role==="assistant"&&Qe.content){v=Qe;break}}if(!v){l.classList.remove("persona-pill-peek--visible");return}let R=v.content,F=!!v.streaming,$=Aa(),O=sl($),D=O.type!=="none"?Ds(O.type,$==null?void 0:$.plugins):null,ae=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,v))===!0,se=D!==null&&(F||ae);se&&D&&!us.has(D.name)&&(up(D,e),us.add(D.name));let Q=se&&(D!=null&&D.containerClass)?D.containerClass:null,ye=(Le=f.dataset.personaPeekStreamClass)!=null?Le:null;ye&&ye!==Q&&(f.classList.remove(ye),delete f.dataset.personaPeekStreamClass),Q&&ye!==Q&&(f.classList.add(Q),f.dataset.personaPeekStreamClass=Q),se?(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 He=se?il(R,O.buffer,D,v,F):R;if(se&&O.placeholder==="skeleton"&&F&&(!He||!He.trim())){let ze=document.createElement("div"),Qe=Ns();Qe.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Qe),tl(f,ze)}else{let ze=Math.max(0,He.length-100),Qe=He.length>100?He.slice(-100):He,xt=qo(Qe);if(!se||!D){let B=He.length>100?`\u2026${Qe}`:Qe;f.textContent!==B&&(f.textContent=B)}else{let B=xt;(D.wrap==="char"||D.wrap==="word")&&(B=Fs(xt,D.wrap,`peek-${v.id}`,{skipTags:D.skipTags,startIndex:ze}));let Re=document.createElement("div");if(Re.innerHTML=B,D.useCaret&&Qe.length>0){let Pe=ll(),fe=Re.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ut=fe[fe.length-1];Ut!=null&&Ut.parentNode?Ut.parentNode.insertBefore(Pe,Ut.nextSibling):Re.appendChild(Pe)}tl(f,Re),(Ee=D.onAfterRender)==null||Ee.call(D,{container:f,bubble:l,messageId:v.id,message:v,speed:O.speed,duration:O.duration})}}let $e=Ho||wn;l.classList.toggle("persona-pill-peek--visible",$e)};if(H()){let l=Y.peekBanner;if(l){let v=R=>{R.preventDefault(),R.stopPropagation(),I(!0,"user")};l.addEventListener("pointerdown",v),dt.push(()=>{l.removeEventListener("pointerdown",v)})}let f=()=>{wn||(wn=!0,Ve())},h=()=>{wn&&(wn=!1,Ve())};be.addEventListener("pointerenter",f),be.addEventListener("pointerleave",h),dt.push(()=>{be.removeEventListener("pointerenter",f),be.removeEventListener("pointerleave",h)}),Ze&&(Ze.addEventListener("pointerenter",f),Ze.addEventListener("pointerleave",h),dt.push(()=>{Ze.removeEventListener("pointerenter",f),Ze.removeEventListener("pointerleave",h)}))}let L=l=>{var ye,He,Se,nt,$e,ut,st,Le;let f=(He=(ye=o.launcher)==null?void 0:ye.composerBar)!=null?He:{},h=(Se=f.expandedSize)!=null?Se:"anchored",v=(nt=f.bottomOffset)!=null?nt:"16px",R=f.collapsedMaxWidth,F=($e=f.expandedMaxWidth)!=null?$e:"880px",$=(ut=f.expandedTopOffset)!=null?ut:"5vh",O=(st=f.modalMaxWidth)!=null?st:"880px",D=(Le=f.modalMaxHeight)!=null?Le:"min(90vh, 800px)",ae="calc(100vw - 32px)",se="var(--persona-pill-area-height, 80px)",Q=_e.style;if(Q.left="",Q.right="",Q.top="",Q.bottom="",Q.transform="",Q.width="",Q.maxWidth="",Q.height="",Q.maxHeight="",Ze){let Ee=Ze.style;Ee.bottom=v,Ee.width=R!=null?R:""}if(l&&h!=="fullscreen"){if(h==="modal"){Q.top="50%",Q.left="50%",Q.transform="translate(-50%, -50%)",Q.bottom="auto",Q.right="auto",Q.width=O,Q.maxWidth=ae,Q.maxHeight=D,Q.height=D;return}Q.left="50%",Q.transform="translateX(-50%)",Q.bottom=`calc(${v} + ${se})`,Q.top=$,Q.width=F,Q.maxWidth=ae}},U=()=>{var D,ae,se,Q,ye,He,Se,nt;if(!W())return;if(H()){let ut=(se=((ae=(D=o.launcher)==null?void 0:D.composerBar)!=null?ae:{}).expandedSize)!=null?se:"anchored",st=k?"expanded":"collapsed";_e.dataset.state=st,_e.dataset.expandedSize=ut,Ze&&(Ze.dataset.state=st,Ze.dataset.expandedSize=ut),_e.style.removeProperty("display"),_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),L(k),pe.style.display=k?"flex":"none",xe(),k?(ii(),li()):(cs(),ps()),Ve();return}let l=pr(o),f=(Q=e.ownerDocument.defaultView)!=null?Q:window,h=(He=(ye=o.launcher)==null?void 0:ye.mobileBreakpoint)!=null?He:640,v=(nt=(Se=o.launcher)==null?void 0:Se.mobileFullscreen)!=null?nt:!0,R=f.innerWidth<=h,F=v&&R&&E,$=no(o).reveal;k?(_e.style.removeProperty("display"),_e.style.display=l?"flex":"",_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0"),be.classList.add("persona-scale-100","persona-opacity-100"),rr?rr.element.style.display="none":mr&&(mr.style.display="none")):(l?l&&($==="overlay"||$==="push")&&!F?(_e.style.removeProperty("display"),_e.style.display="flex",_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(_e.style.setProperty("display","none","important"),_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(_e.style.display="",_e.classList.add("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100"),be.classList.add("persona-scale-95","persona-opacity-0")),rr?rr.element.style.display=l?"none":"":mr&&(mr.style.display=l?"none":""))},I=(l,f="user")=>{var F,$;if(!W()||k===l)return;let h=k;k=l,U();let v=(()=>{var Se,nt,$e,ut,st,Le,Ee,ze,Qe,xt;let O=(nt=(Se=o.launcher)==null?void 0:Se.sidebarMode)!=null?nt:!1,D=($e=e.ownerDocument.defaultView)!=null?$e:window,ae=(st=(ut=o.launcher)==null?void 0:ut.mobileFullscreen)!=null?st:!0,se=(Ee=(Le=o.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Ee:640,Q=D.innerWidth<=se,ye=pr(o)&&ae&&Q,He=H()&&((xt=(Qe=(ze=o.launcher)==null?void 0:ze.composerBar)==null?void 0:Qe.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return O||ae&&Q&&E||ye||He})();if(k&&v){if(!tr){let O=e.getRootNode(),D=O instanceof ShadowRoot?O.host:e.closest(".persona-host");D&&(tr=fp(D,($=(F=o.launcher)==null?void 0:F.zIndex)!=null?$:Lr))}fr||(fr=mp(e.ownerDocument))}else k||(tr==null||tr(),tr=null,fr==null||fr(),fr=null);k&&(fs(),ot()==="follow"?Oo(!0):ls());let R={open:k,source:f,timestamp:Date.now()};k&&!h?a.emit("widget:opened",R):!k&&h&&a.emit("widget:closed",R),a.emit("widget:state",{open:k,launcherEnabled:E,voiceActive:mt.active,streaming:_.isStreaming()})},X=l=>{Pr(l?"stop":"send"),z&&(z.disabled=l),qn.buttons.forEach(f=>{f.disabled=l}),Ne.dataset.personaComposerStreaming=l?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},re=()=>{mt.active||ke&&ke.focus()};a.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>re(),200)});let K=()=>{var h,v,R,F,$,O,D,ae,se,Q,ye;Eo.textContent=(v=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?v:"Hello \u{1F44B}",V.textContent=(F=(R=o.copy)==null?void 0:R.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",ke.placeholder=(O=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?O:"How can I help...";let l=Me.querySelector("[data-persona-intro-card]");if(l){let He=((D=o.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=He?"":"none",He?(Me.classList.remove("persona-gap-3"),Me.classList.add("persona-gap-6")):(Me.classList.remove("persona-gap-6"),Me.classList.add("persona-gap-3"))}!((se=(ae=o.sendButton)==null?void 0:ae.useIcon)!=null&&se)&&!(_!=null&&_.isStreaming())&&(je.textContent=(ye=(Q=o.copy)==null?void 0:Q.sendButtonLabel)!=null?ye:"Send"),ke.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ke.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{m(f=>({...f,sessionId:l}))}});let Ae=null,Oe=()=>{Ae==null&&(Ae=setInterval(()=>{let l=Je.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Ae),Ae=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 Ua(o,{onMessagesChanged(l){var v;bn(Je,l,me),Oe(),ha(l),Oo(!Ho),ai(l);let f=[...l].reverse().find(R=>R.role==="user");l.length===0&&zn(),!ya||$n?(ya=!0,ba=(v=f==null?void 0:f.id)!=null?v:null):f&&f.id!==ba&&(ba=f.id,ni(f.id));let h=mt.lastUserMessageId;f&&f.id!==h&&(mt.lastUserMessageId=f.id,a.emit("user:message",f)),mt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),wa(l),Ve()},onStatusChanged(l){var v;let f=(v=o.statusIndicator)!=null?v:{};Lt(ur,(R=>{var F,$,O,D;return R==="idle"?(F=f.idleText)!=null?F:kr.idle:R==="connecting"?($=f.connectingText)!=null?$:kr.connecting:R==="connected"?(O=f.connectedText)!=null?O:kr.connected:R==="error"?(D=f.errorText)!=null?D:kr.error:kr[R]})(l),f,l)},onStreamingChanged(l){Ho=l,X(l),_&&bn(Je,_.getMessages(),me),l||Oo(!0),Ve()},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":Zo(),Ta();break;case"processing":Zo(),$x();break;case"speaking":Zo(),zx();break;default:l==="idle"&&_.isBargeInActive()?(Zo(),Ta(),z==null||z.setAttribute("aria-label","End voice session")):(mt.active=!1,Zo(),po("system"),Vr());break}},onArtifactsState(l){Kr=l,Jr(),wa()}}),Mt.current=_;let at=null;if(_.onReadAloudChange((l,f)=>{var R;pn=l,un=f,fn();let h=l!=null?l:at;l&&(at=l);let v=h&&(R=_.getMessages().find(F=>F.id===h))!=null?R:null;a.emit("message:read-aloud",{messageId:h,message:v,state:f,timestamp:Date.now()}),f==="idle"&&(at=null)}),ya=!0,((ef=(Zu=o.voiceRecognition)==null?void 0:Zu.provider)==null?void 0:ef.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)}),(ge||o.onSSEEvent)&&_.setSSEEventCallback((l,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,l,f),ue==null||ue.processEvent(l,f),ge==null||ge.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&&(c=Ip(l.metadata),T.syncFromMetadata()),(f=l.messages)!=null&&f.length){$n=!0;try{_.hydrateMessages(l.messages)}finally{$n=!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 tt=()=>{var f,h,v;!H()||k||!((v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||v)||I(!0,"auto")},Bt=l=>{var R;if(l.preventDefault(),_.isStreaming()){_.cancel(),ue==null||ue.reset(),G==null||G.update();return}let f=ke.value.trim(),h=(R=yt==null?void 0:yt.hasAttachments())!=null?R:!1;if(!f&&!h)return;tt();let v;h&&(v=[],v.push(...yt.getContentParts()),f&&v.push(ks(f))),ke.value="",ke.style.height="auto",Tt(),_.sendMessage(f,{contentParts:v}),h&&yt.clearAttachments()},$t=()=>{var l;return((l=o.features)==null?void 0:l.composerHistory)!==!1},lr={...rl},wt=!1,Tt=()=>{lr={...rl}},br=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var f;return(f=l.content)!=null?f:""}).filter(l=>l.length>0),Hr=l=>{if(!ke)return;wt=!0,ke.value=l,ke.dispatchEvent(new Event("input",{bubbles:!0})),wt=!1;let f=ke.value.length;ke.setSelectionRange(f,f)},Sr=()=>{wt||Tt()},Zt=l=>{if(ke){if($t()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=ke.selectionStart===0&&ke.selectionEnd===0,h=ph({direction:l.key==="ArrowUp"?"up":"down",history:br(),currentValue:ke.value,atStart:f,state:lr});if(lr=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Hr(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Tt(),l.preventDefault(),je.click()}}},uo=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(pe)&&(_.cancel(),ue==null||ue.reset(),G==null||G.update(),Tt(),l.preventDefault(),l.stopImmediatePropagation())},Xp=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))},fo=null,_o=!1,Ma=null,pt=null,Qp=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,di=(l="user")=>{var F,$,O,D,ae,se,Q;if(_o||_.isStreaming())return;let f=Qp();if(!f)return;fo=new f;let v=($=((F=o.voiceRecognition)!=null?F:{}).pauseDuration)!=null?$:2e3;fo.continuous=!0,fo.interimResults=!0,fo.lang="en-US";let R=ke.value;fo.onresult=ye=>{let He="",Se="";for(let $e=0;$e<ye.results.length;$e++){let ut=ye.results[$e],st=ut[0].transcript;ut.isFinal?He+=st+" ":Se=st}let nt=R+He+Se;ke.value=nt,Ma&&clearTimeout(Ma),(He||Se)&&(Ma=window.setTimeout(()=>{let $e=ke.value.trim();$e&&fo&&_o&&(Sn(),ke.value="",ke.style.height="auto",_.sendMessage($e,{viaVoice:!0}))},v))},fo.onerror=ye=>{ye.error!=="no-speech"&&Sn()},fo.onend=()=>{if(_o){let ye=ke.value.trim();ye&&ye!==R.trim()&&(ke.value="",ke.style.height="auto",_.sendMessage(ye,{viaVoice:!0})),Sn()}};try{if(fo.start(),_o=!0,mt.active=!0,l!=="system"&&(mt.manuallyDeactivated=!1),po(l),Vr(),z){let ye=(O=o.voiceRecognition)!=null?O:{};pt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(D=ye.iconName)!=null?D:"mic",iconSize:parseFloat((Q=(se=ye.iconSize)!=null?se:(ae=o.sendButton)==null?void 0:ae.size)!=null?Q:"40")||24};let He=ye.recordingBackgroundColor,Se=ye.recordingIconColor,nt=ye.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=He!=null?He:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let $e=z.querySelector("svg");$e&&$e.setAttribute("stroke",Se)}nt&&(z.style.borderColor=nt),z.setAttribute("aria-label","Stop voice recognition")}}catch{Sn("system")}},Sn=(l="user")=>{if(_o){if(_o=!1,Ma&&(clearTimeout(Ma),Ma=null),fo){try{fo.stop()}catch{}fo=null}if(mt.active=!1,po(l),Vr(),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 st,Le,Ee,ze,Qe,xt,B,Re,Pe;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),v=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",R=((Le=l==null?void 0:l.provider)==null?void 0:Le.type)==="custom";if(!(h||v||R))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 D=(Ee=l==null?void 0:l.iconName)!=null?Ee:"mic",ae=(ze=f==null?void 0:f.size)!=null?ze:"40px",se=(Qe=l==null?void 0:l.iconSize)!=null?Qe:ae,Q=parseFloat(se)||24,ye=(xt=l==null?void 0:l.backgroundColor)!=null?xt:f==null?void 0:f.backgroundColor,He=(B=l==null?void 0:l.iconColor)!=null?B:f==null?void 0:f.textColor;O.style.width=se,O.style.height=se,O.style.minWidth=se,O.style.minHeight=se,O.style.fontSize="18px",O.style.lineHeight="1",He?O.style.color=He:O.style.color="var(--persona-text, #111827)";let nt=ve(D,Q,He||"currentColor",1.5);nt?O.appendChild(nt):O.textContent="\u{1F3A4}",ye?O.style.backgroundColor=ye: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=(Re=l==null?void 0:l.tooltipText)!=null?Re:"Start voice recognition";if(((Pe=l==null?void 0:l.showTooltip)!=null?Pe:!1)&&$e){let fe=S("div","persona-send-button-tooltip");fe.textContent=$e,$.appendChild(fe)}return{micButton:O,micButtonWrapper:$}},Bl=()=>{var f,h,v,R,F;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((F=(R=l.iconSize)!=null?R:(v=o.sendButton)==null?void 0:v.size)!=null?F:"40")||24}},Dl=(l,f)=>{var F,$,O,D,ae;if(!z)return;let h=z.querySelector("svg");h&&h.remove();let v=(ae=pt==null?void 0:pt.iconSize)!=null?ae:parseFloat((D=(O=(F=o.voiceRecognition)==null?void 0:F.iconSize)!=null?O:($=o.sendButton)==null?void 0:$.size)!=null?D:"40")||24,R=ve(l,v,f,1.5);R&&z.appendChild(R)},ci=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ta=()=>{var R;if(!z)return;Bl();let l=(R=o.voiceRecognition)!=null?R:{},f=l.recordingBackgroundColor,h=l.recordingIconColor,v=l.recordingBorderColor;if(ci(),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 F=z.querySelector("svg");F&&F.setAttribute("stroke",h)}v&&(z.style.borderColor=v),z.setAttribute("aria-label","Stop voice recognition")},$x=()=>{var O,D,ae,se,Q,ye,He,Se;if(!z)return;Bl();let l=(O=o.voiceRecognition)!=null?O:{},f=_.getVoiceInterruptionMode(),h=(D=l.processingIconName)!=null?D:"loader",v=(se=(ae=l.processingIconColor)!=null?ae:pt==null?void 0:pt.color)!=null?se:"",R=(ye=(Q=l.processingBackgroundColor)!=null?Q:pt==null?void 0:pt.backgroundColor)!=null?ye:"",F=(Se=(He=l.processingBorderColor)!=null?He:pt==null?void 0:pt.borderColor)!=null?Se:"";ci(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=R,z.style.borderColor=F;let $=v||"currentColor";z.style.color=$,Dl(h,$),z.setAttribute("aria-label","Processing voice input"),f==="none"&&(z.style.cursor="default")},zx=()=>{var ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee;if(!z)return;Bl();let l=(ae=o.voiceRecognition)!=null?ae:{},f=_.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",v=(se=l.speakingIconName)!=null?se:h,R=(Se=l.speakingIconColor)!=null?Se:f==="barge-in"?(ye=(Q=l.recordingIconColor)!=null?Q:pt==null?void 0:pt.color)!=null?ye:"":(He=pt==null?void 0:pt.color)!=null?He:"",F=(ut=l.speakingBackgroundColor)!=null?ut:f==="barge-in"?(nt=l.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":($e=pt==null?void 0:pt.backgroundColor)!=null?$e:"",$=(Ee=l.speakingBorderColor)!=null?Ee:f==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Le=pt==null?void 0:pt.borderColor)!=null?Le:"";ci(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=F,z.style.borderColor=$;let O=R||"currentColor";z.style.color=O,Dl(v,O);let D=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",D),f==="none"&&(z.style.cursor="default"),f==="barge-in"&&z.classList.add("persona-voice-recording")},Zo=()=>{var l,f,h;z&&(ci(),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:"",Dl(pt.iconName,pt.color||"currentColor"),pt=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},pi=()=>{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(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Vr(),po("user"),Zo()});return}_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),mt.manuallyDeactivated=!_.isVoiceActive(),Vr(),po("user"),_.isVoiceActive()?Ta():Zo()});return}if(_o){let h=ke.value.trim();mt.manuallyDeactivated=!0,Vr(),Sn("user"),h&&(ke.value="",ke.style.height="auto",_.sendMessage(h))}else mt.manuallyDeactivated=!1,Vr(),di("user")};jr=pi,z&&(z.addEventListener("click",pi),dt.push(()=>{var l,f;((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Zo()):Sn("system"),z&&z.removeEventListener("click",pi)}));let jx=a.on("assistant:complete",()=>{ts&&(mt.active||mt.manuallyDeactivated||ts==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var l,f;!mt.active&&!mt.manuallyDeactivated&&(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("auto"),_.isVoiceActive()&&Ta()}):di("auto"))},600))});dt.push(jx);let Gx=a.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(Gx);let Jp=()=>{I(!k,"user")},rr=null,mr=null;if(E&&!H()){let{instance:l,element:f}=bp({config:o,plugins:n,onToggle:Jp});rr=l,l||(mr=f)}rr?e.appendChild(rr.element):mr&&e.appendChild(mr),U(),ha(),K(),X(_.isStreaming()),ot()==="follow"?Oo(!0):ls(),Zs(),P&&(!E||H()?setTimeout(()=>re(),0):k&&setTimeout(()=>re(),200));let fs=()=>{var D,ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee,ze,Qe,xt,B,Re,Pe,fe,Ut,Ot;if(H()){Ur(),U();return}let l=pr(o),f=(ae=(D=o.launcher)==null?void 0:D.sidebarMode)!=null?ae:!1,h=l||f||((Q=(se=o.launcher)==null?void 0:se.fullHeight)!=null?Q:!1),v=(ye=e.ownerDocument.defaultView)!=null?ye:window,R=(Se=(He=o.launcher)==null?void 0:He.mobileFullscreen)!=null?Se:!0,F=($e=(nt=o.launcher)==null?void 0:nt.mobileBreakpoint)!=null?$e:640,$=v.innerWidth<=F,O=R&&$&&E;try{if(O){xe(),Wn(e,o);return}if(A&&(A=!1,xe(),Wn(e,o)),!E&&!l){be.style.height="",be.style.width="";return}if(!f&&!l){let Kt=(st=(ut=o==null?void 0:o.launcher)==null?void 0:ut.width)!=null?st:o==null?void 0:o.launcherWidth,bt=Kt!=null?Kt:oo;be.style.width=bt,be.style.maxWidth=bt}if(Ro(),!h){let Kt=v.innerHeight,bt=64,zt=(Ee=(Le=o.launcher)==null?void 0:Le.heightOffset)!=null?Ee:0,eo=Math.max(200,Kt-bt),or=Math.min(640,eo),Ye=Math.max(200,or-zt);be.style.height=`${Ye}px`}}finally{if(Ur(),U(),k&&E){let bt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((xt=(Qe=o.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?xt:640),zt=(Re=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Re:!1,eo=(fe=(Pe=o.launcher)==null?void 0:Pe.mobileFullscreen)!=null?fe:!0,or=pr(o)&&eo&&bt,Ye=zt||eo&&bt&&E||or;if(Ye&&!fr){let Rt=e.getRootNode(),cr=Rt instanceof ShadowRoot?Rt.host:e.closest(".persona-host");cr&&!tr&&(tr=fp(cr,(Ot=(Ut=o.launcher)==null?void 0:Ut.zIndex)!=null?Ot:Lr)),fr=mp(e.ownerDocument)}else Ye||(tr==null||tr(),tr=null,fr==null||fr(),fr=null)}}};fs();let Yp=(tf=e.ownerDocument.defaultView)!=null?tf:window;if(Yp.addEventListener("resize",fs),dt.push(()=>Yp.removeEventListener("resize",fs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ur()});l.observe(Ne),dt.push(()=>l.disconnect())}Zr=Me.scrollTop;let Zp=sn(Me),Kx=()=>{let l=Me.getRootNode(),f=typeof l.getSelection=="function"?l.getSelection():null;return f!=null?f:Me.ownerDocument.getSelection()},Fl=()=>xh(Kx(),Me),eu=()=>{let l=Me.scrollTop,f=sn(Me),h=f<Zp;if(Zp=f,ot()!=="follow"){Zr=l,$r();return}let{action:v,nextLastScrollTop:R}=nl({following:Yr.isFollowing(),currentScrollTop:l,lastScrollTop:Zr,nearBottom:da(Me,va),userScrollThreshold:Js,isAutoScrolling:Co||Vn||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Zr=R,v==="resume"){Fl()||No();return}v==="pause"&&Sa()};if(Me.addEventListener("scroll",eu,{passive:!0}),dt.push(()=>Me.removeEventListener("scroll",eu)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{oi()});l.observe(Je),l.observe(Me),dt.push(()=>l.disconnect())}let tu=()=>{ot()==="follow"&&Yr.isFollowing()&&Fl()&&Sa()},ru=Me.ownerDocument;ru.addEventListener("selectionchange",tu),dt.push(()=>{ru.removeEventListener("selectionchange",tu)});let ou=l=>{if(ot()!=="follow")return;let f=al({following:Yr.isFollowing(),deltaY:l.deltaY,nearBottom:da(Me,va),resumeWhenNearBottom:!0});f==="pause"?Sa():f==="resume"&&!Fl()&&No()};Me.addEventListener("wheel",ou,{passive:!0}),dt.push(()=>Me.removeEventListener("wheel",ou)),lt.addEventListener("click",()=>{zn(),Me.scrollTop=Me.scrollHeight,Zr=Me.scrollTop,No(),Oo(!0),$r()}),dt.push(()=>lt.remove()),dt.push(()=>{os(),zn()});let nu=()=>{j&&(Wo&&(j.removeEventListener("click",Wo),Wo=null),W()?(j.style.display="",Wo=()=>{I(!1,"user")},j.addEventListener("click",Wo)):j.style.display="none")};nu(),(()=>{let{clearChatButton:l}=Y;l&&l.addEventListener("click",()=>{_.clearMessages(),Bo.clear(),No(),Ln(Y.composerOverlay);try{localStorage.removeItem(Ya),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ya}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ya)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)}c={},T.syncFromMetadata(),ge==null||ge.clear(),ue==null||ue.reset(),G==null||G.update()})})(),Wt&&Wt.addEventListener("submit",Bt),ke==null||ke.addEventListener("keydown",Zt),ke==null||ke.addEventListener("input",Sr),ke==null||ke.addEventListener("paste",Xp);let au=(rf=e.ownerDocument)!=null?rf:document;au.addEventListener("keydown",uo,!0);let su="persona-attachment-drop-active",ms=0,Nl=()=>{ms=0,pe.classList.remove(su)},Ea=()=>{var l;return((l=o.attachments)==null?void 0:l.enabled)===!0&&yt!==null},iu=l=>{!Rl(l.dataTransfer)||!Ea()||(ms++,ms===1&&pe.classList.add(su))},lu=l=>{!Rl(l.dataTransfer)||!Ea()||(ms--,ms<=0&&Nl())},du=l=>{!Rl(l.dataTransfer)||!Ea()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},cu=l=>{var h;if(!Rl(l.dataTransfer)||!Ea())return;l.preventDefault(),l.stopPropagation(),Nl();let f=Array.from((h=l.dataTransfer.files)!=null?h:[]);f.length!==0&&yt.handleFiles(f)},An=!0;pe.addEventListener("dragenter",iu,An),pe.addEventListener("dragleave",lu,An),e.addEventListener("dragover",du,An),e.addEventListener("drop",cu,An);let ui=e.ownerDocument,pu=l=>{Ea()&&l.preventDefault()},uu=l=>{Ea()&&l.preventDefault()};ui.addEventListener("dragover",pu),ui.addEventListener("drop",uu),dt.push(()=>{Wt&&Wt.removeEventListener("submit",Bt),ke==null||ke.removeEventListener("keydown",Zt),ke==null||ke.removeEventListener("input",Sr),ke==null||ke.removeEventListener("paste",Xp),au.removeEventListener("keydown",uo,!0)}),dt.push(()=>{pe.removeEventListener("dragenter",iu,An),pe.removeEventListener("dragleave",lu,An),e.removeEventListener("dragover",du,An),e.removeEventListener("drop",cu,An),ui.removeEventListener("dragover",pu),ui.removeEventListener("drop",uu),Nl()}),dt.push(()=>{_.cancel()}),rr?dt.push(()=>{rr==null||rr.destroy()}):mr&&dt.push(()=>{mr==null||mr.remove()});let dr={update(l){var Tr,Br,Uo,vr,Dr,Fr,Qn,gs,cf,pf,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,$f,zf,jf,Gf,Kf,Xf,Qf,Jf,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,Wm,Hm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,Vm,$m,zm,jm,Gm,Km,Xm,Qm,Jm,Ym,Zm,eg,tg,rg,og,ng,ag,sg,ig,lg;let f=o.toolCall,h=o.messageActions,v=(Tr=o.layout)==null?void 0:Tr.messages,R=o.colorScheme,F=o.loadingIndicator,$=o.iterationDisplay,O=(Br=o.features)==null?void 0:Br.showReasoning,D=(Uo=o.features)==null?void 0:Uo.showToolCalls,ae=(vr=o.features)==null?void 0:vr.toolCallDisplay,se=(Dr=o.features)==null?void 0:Dr.reasoningDisplay;o={...o,...l},xe(),Wn(e,o),wl(e,o),Sl(e,o),Jr(),o.colorScheme!==R&&es();let Q=zs.getForInstance(o.plugins);n.length=0,n.push(...Q),E=(Qn=(Fr=o.launcher)==null?void 0:Fr.enabled)!=null?Qn:!0,M=(cf=(gs=o.launcher)==null?void 0:gs.autoExpand)!=null?cf:!1,Ke=(uf=(pf=o.features)==null?void 0:pf.showReasoning)!=null?uf:!0,Ce=(mf=(ff=o.features)==null?void 0:ff.showToolCalls)!=null?mf:!0,Ue=(hf=(gf=o.features)==null?void 0:gf.scrollToBottom)!=null?hf:{};let ye=ot();Te=(yf=(xf=o.features)==null?void 0:xf.scrollBehavior)!=null?yf:{},ye!==ot()&&(zn(),No()),ko(),$r();let He=Ie;if(Ie=(vf=(bf=o.features)==null?void 0:bf.showEventStreamToggle)!=null?vf:!1,Ie&&!He){if(ge||(J=new Vs(de),ge=new qs(le,J),ue=ue!=null?ue:new $s,J.open().then(()=>ge==null?void 0:ge.restore()).catch(()=>{}),_.setSSEEventCallback((te,Et)=>{var jt;(jt=o.onSSEEvent)==null||jt.call(o,te,Et),ue==null||ue.processEvent(te,Et),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!ht&&qe){let te=(wf=(Cf=o.features)==null?void 0:Cf.eventStream)==null?void 0:wf.classNames,Et="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:"");ht=S("button",Et),ht.style.width="28px",ht.style.height="28px",ht.style.color=_r.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let jt=ve("activity","18px","currentColor",1.5);jt&&ht.appendChild(jt);let it=Y.clearChatButtonWrapper,It=Y.closeButtonWrapper,hr=it||It;hr&&hr.parentNode===qe?qe.insertBefore(ht,hr):qe.appendChild(ht),ht.addEventListener("click",()=>{ce?yo():zo()})}}else!Ie&&He&&(yo(),ht&&(ht.remove(),ht=null),ge==null||ge.clear(),J==null||J.destroy(),ge=null,J=null,ue==null||ue.reset(),ue=null);if(((Sf=o.launcher)==null?void 0:Sf.enabled)===!1&&rr&&(rr.destroy(),rr=null),((Af=o.launcher)==null?void 0:Af.enabled)===!1&&mr&&(mr.remove(),mr=null),((Mf=o.launcher)==null?void 0:Mf.enabled)!==!1&&!rr&&!mr){let{instance:te,element:Et}=bp({config:o,plugins:n,onToggle:Jp});rr=te,te||(mr=Et),e.appendChild(Et)}rr&&rr.update(o),Xe&&((Tf=o.launcher)==null?void 0:Tf.title)!==void 0&&(Xe.textContent=o.launcher.title),et&&((Ef=o.launcher)==null?void 0:Ef.subtitle)!==void 0&&(et.textContent=o.launcher.subtitle);let Se=(kf=o.layout)==null?void 0:kf.header;if((Se==null?void 0:Se.layout)!==b&&qe){let te=Se?za(o,Se,{showClose:W(),onClose:()=>I(!1,"user")}):ln({config:o,showClose:W(),onClose:()=>I(!1,"user")});gt.replaceHeader(te),qe=gt.header.element,he=gt.header.iconHolder,Xe=gt.header.headerTitle,et=gt.header.headerSubtitle,j=gt.header.closeButton,b=Se==null?void 0:Se.layout}else if(Se&&(he&&(he.style.display=Se.showIcon===!1?"none":""),Xe&&(Xe.style.display=Se.showTitle===!1?"none":""),et&&(et.style.display=Se.showSubtitle===!1?"none":""),j&&(j.style.display=Se.showCloseButton===!1?"none":""),Y.clearChatButtonWrapper)){let te=Se.showClearChat;if(te!==void 0){Y.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Et}=Y;Et&&!Et.classList.contains("persona-absolute")&&(te?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let $e=((Lf=o.layout)==null?void 0:Lf.showHeader)!==!1;qe&&(qe.style.display=$e?"":"none");let ut=((Pf=o.layout)==null?void 0:Pf.showFooter)!==!1;Ne&&(Ne.style.display=ut?"":"none"),Ur(),$r(),E!==w?E?I(M,"auto"):(k=!0,U()):M!==y&&I(M,"auto"),y=M,w=E,fs(),nu();let Ee=JSON.stringify(l.toolCall)!==JSON.stringify(f),ze=JSON.stringify(o.messageActions)!==JSON.stringify(h),Qe=JSON.stringify((Rf=o.layout)==null?void 0:Rf.messages)!==JSON.stringify(v),xt=((If=o.loadingIndicator)==null?void 0:If.render)!==(F==null?void 0:F.render)||((Wf=o.loadingIndicator)==null?void 0:Wf.renderIdle)!==(F==null?void 0:F.renderIdle)||((Hf=o.loadingIndicator)==null?void 0:Hf.showBubble)!==(F==null?void 0:F.showBubble),B=o.iterationDisplay!==$,Re=((Df=(Bf=o.features)==null?void 0:Bf.showReasoning)!=null?Df:!0)!==(O!=null?O:!0)||((Nf=(Ff=o.features)==null?void 0:Ff.showToolCalls)!=null?Nf:!0)!==(D!=null?D:!0)||JSON.stringify((Of=o.features)==null?void 0:Of.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify((_f=o.features)==null?void 0:_f.reasoningDisplay)!==JSON.stringify(se);(Ee||ze||Qe||xt||B||Re)&&_&&(xa++,bn(Je,_.getMessages(),me));let fe=(Uf=o.launcher)!=null?Uf:{},Ut=(qf=fe.headerIconHidden)!=null?qf:!1,Ot=($f=(Vf=o.layout)==null?void 0:Vf.header)==null?void 0:$f.showIcon,Kt=Ut||Ot===!1,bt=fe.headerIconName,zt=(zf=fe.headerIconSize)!=null?zf:"48px";if(he){let te=pe.querySelector(".persona-border-b-persona-divider"),Et=te==null?void 0:te.querySelector(".persona-flex-col");if(Kt)he.style.display="none",te&&Et&&!te.contains(Et)&&te.insertBefore(Et,te.firstChild);else{if(he.style.display="",he.style.height=zt,he.style.width=zt,te&&Et&&(te.contains(he)?he.nextSibling!==Et&&(he.remove(),te.insertBefore(he,Et)):te.insertBefore(he,Et)),bt){let it=parseFloat(zt)||24,It=ve(bt,it*.6,"currentColor",1);It?he.replaceChildren(It):he.textContent=(jf=fe.agentIconText)!=null?jf:"\u{1F4AC}"}else if(fe.iconUrl){let it=he.querySelector("img");if(it)it.src=fe.iconUrl,it.style.height=zt,it.style.width=zt;else{let It=document.createElement("img");It.src=fe.iconUrl,It.alt="",It.className="persona-rounded-xl persona-object-cover",It.style.height=zt,It.style.width=zt,he.replaceChildren(It)}}else{let it=he.querySelector("svg"),It=he.querySelector("img");(it||It)&&he.replaceChildren(),he.textContent=(Gf=fe.agentIconText)!=null?Gf:"\u{1F4AC}"}let jt=he.querySelector("img");jt&&(jt.style.height=zt,jt.style.width=zt)}}let eo=(Xf=(Kf=o.layout)==null?void 0:Kf.header)==null?void 0:Xf.showTitle,or=(Jf=(Qf=o.layout)==null?void 0:Qf.header)==null?void 0:Jf.showSubtitle;if(Xe&&(Xe.style.display=eo===!1?"none":""),et&&(et.style.display=or===!1?"none":""),j){((Zf=(Yf=o.layout)==null?void 0:Yf.header)==null?void 0:Zf.showCloseButton)===!1?j.style.display="none":j.style.display="";let Et=(em=fe.closeButtonSize)!=null?em:"32px",jt=(tm=fe.closeButtonPlacement)!=null?tm:"inline";j.style.height=Et,j.style.width=Et;let{closeButtonWrapper:it}=Y,It=jt==="top-right",hr=it==null?void 0:it.classList.contains("persona-absolute");if(it&&It!==hr)if(it.remove(),It)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(it);else{let ct=(om=(rm=fe.clearChat)==null?void 0:rm.placement)!=null?om:"inline",xr=(am=(nm=fe.clearChat)==null?void 0:nm.enabled)!=null?am:!0;it.className=xr&&ct==="inline"?"":"persona-ml-auto";let zr=pe.querySelector(".persona-border-b-persona-divider");zr&&zr.appendChild(it)}if(j.style.color=fe.closeButtonColor||_r.actionIconColor,fe.closeButtonBackgroundColor?(j.style.backgroundColor=fe.closeButtonBackgroundColor,j.classList.remove("hover:persona-bg-gray-100")):(j.style.backgroundColor="",j.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let ct=fe.closeButtonBorderWidth||"0px",xr=fe.closeButtonBorderColor||"transparent";j.style.border=`${ct} solid ${xr}`,j.classList.remove("persona-border-none")}else j.style.border="",j.classList.add("persona-border-none");fe.closeButtonBorderRadius?(j.style.borderRadius=fe.closeButtonBorderRadius,j.classList.remove("persona-rounded-full")):(j.style.borderRadius="",j.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(j.style.paddingLeft=fe.closeButtonPaddingX,j.style.paddingRight=fe.closeButtonPaddingX):(j.style.paddingLeft="",j.style.paddingRight=""),fe.closeButtonPaddingY?(j.style.paddingTop=fe.closeButtonPaddingY,j.style.paddingBottom=fe.closeButtonPaddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Er=(sm=fe.closeButtonIconName)!=null?sm:"x",So=(im=fe.closeButtonIconText)!=null?im:"\xD7";j.innerHTML="";let Nr=ve(Er,"28px","currentColor",1);Nr?j.appendChild(Nr):j.textContent=So;let er=(lm=fe.closeButtonTooltipText)!=null?lm:"Close chat",ro=(dm=fe.closeButtonShowTooltip)!=null?dm:!0;if(j.setAttribute("aria-label",er),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),ro&&er)){let ct=null,xr=()=>{if(ct||!j)return;let Jn=j.ownerDocument,hs=Jn.body;if(!hs)return;ct=Vo(Jn,"div","persona-clear-chat-tooltip"),ct.textContent=er;let xs=Vo(Jn,"div");xs.className="persona-clear-chat-tooltip-arrow",ct.appendChild(xs);let Yn=j.getBoundingClientRect();ct.style.position="fixed",ct.style.zIndex=String(Hn),ct.style.left=`${Yn.left+Yn.width/2}px`,ct.style.top=`${Yn.top-8}px`,ct.style.transform="translate(-50%, -100%)",hs.appendChild(ct)},zr=()=>{ct&&ct.parentNode&&(ct.parentNode.removeChild(ct),ct=null)};it.addEventListener("mouseenter",xr),it.addEventListener("mouseleave",zr),j.addEventListener("focus",xr),j.addEventListener("blur",zr),it._cleanupTooltip=()=>{zr(),it&&(it.removeEventListener("mouseenter",xr),it.removeEventListener("mouseleave",zr)),j&&(j.removeEventListener("focus",xr),j.removeEventListener("blur",zr))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Rt}=Y;if(Ye){let te=(cm=fe.clearChat)!=null?cm:{},Et=(pm=te.enabled)!=null?pm:!0,jt=(fm=(um=o.layout)==null?void 0:um.header)==null?void 0:fm.showClearChat,it=jt!==void 0?jt:Et,It=(mm=te.placement)!=null?mm:"inline";if(Rt){Rt.style.display=it?"":"none";let{closeButtonWrapper:hr}=Y;!H()&&hr&&!hr.classList.contains("persona-absolute")&&(it?hr.classList.remove("persona-ml-auto"):hr.classList.add("persona-ml-auto"));let Er=It==="top-right",So=Rt.classList.contains("persona-absolute");if(!H()&&Er!==So&&it){if(Rt.remove(),Er)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",pe.style.position="relative",pe.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let er=pe.querySelector(".persona-border-b-persona-divider"),ro=Y.closeButtonWrapper;er&&ro&&ro.parentElement===er?er.insertBefore(Rt,ro):er&&er.appendChild(Rt)}let Nr=Y.closeButtonWrapper;Nr&&!Nr.classList.contains("persona-absolute")&&(Er?Nr.classList.add("persona-ml-auto"):Nr.classList.remove("persona-ml-auto"))}}if(it){if(!H()){let ct=(gm=te.size)!=null?gm:"32px";Ye.style.height=ct,Ye.style.width=ct}let hr=(hm=te.iconName)!=null?hm:"refresh-cw",Er=(xm=te.iconColor)!=null?xm:"";Ye.style.color=Er||_r.actionIconColor,Ye.innerHTML="";let So=H()?"14px":"20px",Nr=ve(hr,So,"currentColor",2);if(Nr&&Ye.appendChild(Nr),te.backgroundColor?(Ye.style.backgroundColor=te.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let ct=te.borderWidth||"0px",xr=te.borderColor||"transparent";Ye.style.border=`${ct} solid ${xr}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");te.borderRadius?(Ye.style.borderRadius=te.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),te.paddingX?(Ye.style.paddingLeft=te.paddingX,Ye.style.paddingRight=te.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),te.paddingY?(Ye.style.paddingTop=te.paddingY,Ye.style.paddingBottom=te.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let er=(ym=te.tooltipText)!=null?ym:"Clear chat",ro=(bm=te.showTooltip)!=null?bm:!0;if(Ye.setAttribute("aria-label",er),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),ro&&er)){let ct=null,xr=()=>{if(ct||!Ye)return;let Jn=Ye.ownerDocument,hs=Jn.body;if(!hs)return;ct=Vo(Jn,"div","persona-clear-chat-tooltip"),ct.textContent=er;let xs=Vo(Jn,"div");xs.className="persona-clear-chat-tooltip-arrow",ct.appendChild(xs);let Yn=Ye.getBoundingClientRect();ct.style.position="fixed",ct.style.zIndex=String(Hn),ct.style.left=`${Yn.left+Yn.width/2}px`,ct.style.top=`${Yn.top-8}px`,ct.style.transform="translate(-50%, -100%)",hs.appendChild(ct)},zr=()=>{ct&&ct.parentNode&&(ct.parentNode.removeChild(ct),ct=null)};Rt.addEventListener("mouseenter",xr),Rt.addEventListener("mouseleave",zr),Ye.addEventListener("focus",xr),Ye.addEventListener("blur",zr),Rt._cleanupTooltip=()=>{zr(),Rt&&(Rt.removeEventListener("mouseenter",xr),Rt.removeEventListener("mouseleave",zr)),Ye&&(Ye.removeEventListener("focus",xr),Ye.removeEventListener("blur",zr))}}}}let cr=o.actionParsers&&o.actionParsers.length?o.actionParsers:[js],go=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ma.message,ma.messageAndClick];T=Gs({parsers:cr,handlers:go,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),me=nx(o,T,Z),_.updateConfig(o),bn(Je,_.getMessages(),me),ha(),K(),X(_.isStreaming());let to=((vm=o.voiceRecognition)==null?void 0:vm.enabled)===!0,jn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Gn=((wm=(Cm=o.voiceRecognition)==null?void 0:Cm.provider)==null?void 0:wm.type)==="runtype";if(to&&(jn||Gn))if(!z||!Ht){let te=Vx(o.voiceRecognition,o.sendButton);te&&(z=te.micButton,Ht=te.micButtonWrapper,Jt.insertBefore(Ht,Cr),z.addEventListener("click",pi),z.disabled=_.isStreaming())}else{let te=(Sm=o.voiceRecognition)!=null?Sm:{},Et=(Am=o.sendButton)!=null?Am:{},jt=(Mm=te.iconName)!=null?Mm:"mic",it=(Tm=Et.size)!=null?Tm:"40px",It=(Em=te.iconSize)!=null?Em:it,hr=parseFloat(It)||24;z.style.width=It,z.style.height=It,z.style.minWidth=It,z.style.minHeight=It;let Er=(Lm=(km=te.iconColor)!=null?km:Et.textColor)!=null?Lm:"currentColor";z.innerHTML="";let So=ve(jt,hr,Er,2);So?z.appendChild(So):z.textContent="\u{1F3A4}";let Nr=(Pm=te.backgroundColor)!=null?Pm:Et.backgroundColor;Nr?z.style.backgroundColor=Nr:z.style.backgroundColor="",Er?z.style.color=Er:z.style.color="var(--persona-text, #111827)",te.borderWidth?(z.style.borderWidth=te.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),te.borderColor?z.style.borderColor=te.borderColor:z.style.borderColor="",te.paddingX?(z.style.paddingLeft=te.paddingX,z.style.paddingRight=te.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),te.paddingY?(z.style.paddingTop=te.paddingY,z.style.paddingBottom=te.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let er=Ht==null?void 0:Ht.querySelector(".persona-send-button-tooltip"),ro=(Rm=te.tooltipText)!=null?Rm:"Start voice recognition";if(((Im=te.showTooltip)!=null?Im:!1)&&ro)if(er)er.textContent=ro,er.style.display="";else{let xr=document.createElement("div");xr.className="persona-send-button-tooltip",xr.textContent=ro,Ht==null||Ht.insertBefore(xr,z)}else er&&(er.style.display="none");Ht.style.display="",z.disabled=_.isStreaming()}else z&&Ht&&(Ht.style.display="none",((Hm=(Wm=o.voiceRecognition)==null?void 0:Wm.provider)==null?void 0:Hm.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():_o&&Sn());if(((Bm=o.attachments)==null?void 0:Bm.enabled)===!0)if(!we||!oe){let te=(Dm=o.attachments)!=null?Dm:{},jt=(Nm=((Fm=o.sendButton)!=null?Fm:{}).size)!=null?Nm:"40px";At||(At=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),At.style.display="none",Wt.insertBefore(At,ke)),De||(De=document.createElement("input"),De.type="file",De.accept=((Om=te.allowedTypes)!=null?Om:an).join(","),De.multiple=((_m=te.maxFiles)!=null?_m:4)>1,De.style.display="none",De.setAttribute("aria-label","Attach files"),Wt.insertBefore(De,ke)),we=S("div","persona-send-button-wrapper"),oe=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),oe.type="button",oe.setAttribute("aria-label",(Um=te.buttonTooltipText)!=null?Um:"Attach file");let it=(qm=te.buttonIconName)!=null?qm:"paperclip",It=jt,hr=parseFloat(It)||40,Er=Math.round(hr*.6);oe.style.width=It,oe.style.height=It,oe.style.minWidth=It,oe.style.minHeight=It,oe.style.fontSize="18px",oe.style.lineHeight="1",oe.style.backgroundColor="transparent",oe.style.color="var(--persona-primary, #111827)",oe.style.border="none",oe.style.borderRadius="6px",oe.style.transition="background-color 0.15s ease",oe.addEventListener("mouseenter",()=>{oe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),oe.addEventListener("mouseleave",()=>{oe.style.backgroundColor="transparent"});let So=ve(it,Er,"currentColor",1.5);So?oe.appendChild(So):oe.textContent="\u{1F4CE}",oe.addEventListener("click",ro=>{ro.preventDefault(),De==null||De.click()}),we.appendChild(oe);let Nr=(Vm=te.buttonTooltipText)!=null?Vm:"Attach file",er=S("div","persona-send-button-tooltip");er.textContent=Nr,we.appendChild(er),Gt.append(we),!yt&&De&&At&&(yt=la.fromConfig(te),yt.setPreviewsContainer(At),De.addEventListener("change",async()=>{yt&&(De!=null&&De.files)&&(await yt.handleFileSelect(De.files),De.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(ax(te.dropOverlay))}else{we.style.display="";let te=($m=o.attachments)!=null?$m:{};De&&(De.accept=((zm=te.allowedTypes)!=null?zm:an).join(","),De.multiple=((jm=te.maxFiles)!=null?jm:4)>1),yt&&yt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else we&&(we.style.display="none"),yt&&yt.clearAttachments(),(Gm=pe.querySelector(".persona-attachment-drop-overlay"))==null||Gm.remove();let Xt=(Km=o.sendButton)!=null?Km:{},Kn=(Xm=Xt.useIcon)!=null?Xm:!1,Mn=(Qm=Xt.iconText)!=null?Qm:"\u2191",Tn=Xt.iconName,en=(Jm=Xt.tooltipText)!=null?Jm:"Send message",Xn=(Ym=Xt.showTooltip)!=null?Ym:!1,wo=(Zm=Xt.size)!=null?Zm:"40px",rt=Xt.backgroundColor,gr=Xt.textColor;if(Kn){if(je.style.width=wo,je.style.height=wo,je.style.minWidth=wo,je.style.minHeight=wo,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",gr?je.style.color=gr:je.style.color="var(--persona-button-primary-fg, #ffffff)",Tn){let te=parseFloat(wo)||24,Et=(gr==null?void 0:gr.trim())||"currentColor",jt=ve(Tn,te,Et,2);jt?je.appendChild(jt):je.textContent=Mn}else je.textContent=Mn;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rt?(je.style.backgroundColor=rt,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(tg=(eg=o.copy)==null?void 0:eg.sendButtonLabel)!=null?tg:"Send",je.style.width="",je.style.height="",je.style.minWidth="",je.style.minHeight="",je.style.fontSize="",je.style.lineHeight="",je.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",rt?(je.style.backgroundColor=rt,je.classList.remove("persona-bg-persona-accent")):je.classList.add("persona-bg-persona-accent"),gr?je.style.color=gr:je.classList.add("persona-text-white");Xt.borderWidth?(je.style.borderWidth=Xt.borderWidth,je.style.borderStyle="solid"):(je.style.borderWidth="",je.style.borderStyle=""),Xt.borderColor?je.style.borderColor=Xt.borderColor:je.style.borderColor="",Xt.paddingX?(je.style.paddingLeft=Xt.paddingX,je.style.paddingRight=Xt.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Xt.paddingY?(je.style.paddingTop=Xt.paddingY,je.style.paddingBottom=Xt.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let Vt=Cr==null?void 0:Cr.querySelector(".persona-send-button-tooltip");if(Xn&&en)if(Vt)Vt.textContent=en,Vt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=en,Cr==null||Cr.insertBefore(te,je)}else Vt&&(Vt.style.display="none");let qt=(sg=(rg=o.layout)==null?void 0:rg.contentMaxWidth)!=null?sg:H()?(ag=(ng=(og=o.launcher)==null?void 0:og.composerBar)==null?void 0:ng.contentMaxWidth)!=null?ag:"720px":void 0;qt?(Je.style.maxWidth=qt,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%",Wt&&(Wt.style.maxWidth=qt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Ge&&(Ge.style.maxWidth=qt,Ge.style.marginLeft="auto",Ge.style.marginRight="auto")):(Je.style.maxWidth="",Je.style.marginLeft="",Je.style.marginRight="",Je.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Ge&&(Ge.style.maxWidth="",Ge.style.marginLeft="",Ge.style.marginRight=""));let ft=(ig=o.statusIndicator)!=null?ig:{},Qt=(lg=ft.visible)!=null?lg:!0;if(ur.style.display=Qt?"":"none",_){let te=_.getStatus();Lt(ur,(jt=>{var it,It,hr,Er;return jt==="idle"?(it=ft.idleText)!=null?it:kr.idle:jt==="connecting"?(It=ft.connectingText)!=null?It:kr.connecting:jt==="connected"?(hr=ft.connectedText)!=null?hr:kr.connected:jt==="error"?(Er=ft.errorText)!=null?Er:kr.error:kr[jt]})(te),ft,te)}ur.classList.remove("persona-text-left","persona-text-center","persona-text-right");let St=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";ur.classList.add(St)},open(){W()&&I(!0,"api")},close(){W()&&I(!1,"api")},toggle(){W()&&I(!k,"api")},clearChat(){Ir=!1,_.clearMessages(),Bo.clear(),No();try{localStorage.removeItem(Ya),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ya}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ya)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)}c={},T.syncFromMetadata(),ge==null||ge.clear(),ue==null||ue.reset(),G==null||G.update()},setMessage(l){return!ke||_.isStreaming()?!1:(!k&&W()&&I(!0,"system"),ke.value=l,ke.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let f=(l==null?void 0:l.trim())||ke.value.trim();return f?(!k&&W()&&I(!0,"system"),ke.value="",ke.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&&W()&&I(!0,"system"),mt.manuallyDeactivated=!1,Vr(),_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("user"),_.isVoiceActive()&&Ta()})),!0):_o?!0:Qp()?(!k&&W()&&I(!0,"system"),mt.manuallyDeactivated=!1,Vr(),di("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(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Vr(),po("user"),Zo()}),!0):!1:_o?(mt.manuallyDeactivated=!0,Vr(),Sn("user"),!0):!1},injectMessage(l){return!k&&W()&&I(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!k&&W()&&I(!0,"system");let f=_.injectAssistantMessage(l);return N&&(N=!1,q&&(clearTimeout(q),q=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),f},injectUserMessage(l){return!k&&W()&&I(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!k&&W()&&I(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!k&&W()&&I(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!k&&W()&&I(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!k&&W()&&I(!0,"system"),_.injectTestEvent(l)},async connectStream(l,f){return _.connectStream(l,f)},__pushEventStreamEvent(l){ge&&(ue==null||ue.processEvent(l.type,l.payload),ge.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||!ge||zo()},hideEventStream(){ce&&yo()},isEventStreamVisible(){return ce},showArtifacts(){xo(o)&&(Ir=!1,Jr(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){xo(o)&&(Ir=!0,Jr())},upsertArtifact(l){return xo(o)?(Ir=!1,_.upsertArtifact(l)):null},selectArtifact(l){xo(o)&&_.selectArtifact(l)},clearArtifacts(){xo(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 E&&!k&&!H()||!ke?!1:(ke.focus(),!0)},async resolveApproval(l,f,h){let R=_.getMessages().find(F=>{var $;return F.variant==="approval"&&(($=F.approval)==null?void 0:$.id)===l});if(!(R!=null&&R.approval))throw new Error(`Approval not found: ${l}`);if(R.approval.toolType==="webmcp"){_.resolveWebMcpApproval(R.id,f);return}return _.resolveApproval(R.approval,f,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){m(l)},on(l,f){return a.on(l,f)},off(l,f){a.off(l,f)},isOpen(){return W()&&k},isVoiceActive(){return mt.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:W()&&k,launcherEnabled:E,voiceActive:mt.active,streaming:_.isStreaming()}},showCSATFeedback(l){!k&&W()&&I(!0,"system");let f=Je.querySelector(".persona-feedback-container");f&&f.remove();let h=Ll({onSubmit:async(v,R)=>{var F;_.isClientTokenMode()&&await _.submitCSATFeedback(v,R),(F=l==null?void 0:l.onSubmit)==null||F.call(l,v,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&W()&&I(!0,"system");let f=Je.querySelector(".persona-feedback-container");f&&f.remove();let h=Pl({onSubmit:async(v,R)=>{var F;_.isClientTokenMode()&&await _.submitNPSFeedback(v,R),(F=l==null?void 0:l.onSubmit)==null||F.call(l,v,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Je.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(){Ae!=null&&(clearInterval(Ae),Ae=null),dt.forEach(l=>l()),_e.remove(),Ze==null||Ze.remove(),rr==null||rr.destroy(),mr==null||mr.remove(),Wo&&j.removeEventListener("click",Wo)}};if((((of=r==null?void 0:r.debugTools)!=null?of:!1)||!!o.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,f={controller:dr,getMessages:dr.getMessages,getStatus:dr.getStatus,getMetadata:dr.getPersistentMetadata,updateMetadata:dr.updatePersistentMetadata,clearHistory:()=>dr.clearChat(),setVoiceActive:h=>h?dr.startVoiceRecognition():dr.stopVoiceRecognition()};window.AgentWidgetBrowser=f,dt.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 D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.focusInput()};if(window.addEventListener("persona:focusInput",f),dt.push(()=>{window.removeEventListener("persona:focusInput",f)}),Ie){let O=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&dr.showEventStream()},D=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&dr.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",D),dt.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",D)})}let h=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.showArtifacts()},v=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.hideArtifacts()},R=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&dr.upsertArtifact(D.artifact)},F=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&dr.selectArtifact(D.id)},$=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",$),dt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",$)})}let mo=Wv(o.persistState);if(mo&&W()){let l=Hv(mo.storage),f=`${mo.keyPrefix}widget-open`,h=`${mo.keyPrefix}widget-voice`,v=`${mo.keyPrefix}widget-voice-mode`;if(l){let R=((nf=mo.persist)==null?void 0:nf.openState)&&l.getItem(f)==="true",F=((af=mo.persist)==null?void 0:af.voiceState)&&l.getItem(h)==="true",$=((sf=mo.persist)==null?void 0:sf.voiceState)&&l.getItem(v)==="true";if(R&&setTimeout(()=>{dr.open(),setTimeout(()=>{var O;if(F||$)dr.startVoiceRecognition();else if((O=mo.persist)!=null&&O.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(lf=mo.persist)!=null&&lf.openState&&(a.on("widget:opened",()=>{l.setItem(f,"true")}),a.on("widget:closed",()=>{l.setItem(f,"false")})),(df=mo.persist)!=null&&df.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")})),mo.clearOnChatClear){let O=()=>{l.removeItem(f),l.removeItem(h),l.removeItem(v)},D=()=>O();window.addEventListener("persona:clear-chat",D),dt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return u&&W()&&setTimeout(()=>{dr.open()},0),Ve(),Qs||mi().then(()=>{_&&(xa++,Bo.clear(),bn(Je,_.getMessages(),me))}).catch(()=>{}),dr};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.")},sx=(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"},Dp=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=""},ix=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Dp(e)},Wp=e=>{e.style.transition=""},Hp=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=""},Bp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Wl=(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)},lx=(e,t,r,o,n,a,s)=>{var x,C,T,E,M,P;let i=no(a),c=i.reveal==="push";Ov(e,t,r,o,c),_v(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 d=e.ownerDocument.defaultView,u=(C=(x=a==null?void 0:a.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,g=(E=(T=a==null?void 0:a.launcher)==null?void 0:T.mobileBreakpoint)!=null?E:640,p=d!=null?d.innerWidth<=g:!1;if(u&&p&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Hp(t),Wp(o),ix(o),Bp(r),Wl(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((P=(M=a==null?void 0:a.launcher)==null?void 0:M.zIndex)!=null?P:Lr),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"),ix(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",Hp(t),Wp(o),Bp(r),Wl(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",Wp(o),Dp(o),Wl(n,o);let y=Bv(i.width,e.clientWidth),w=Math.max(0,e.clientWidth),b=i.animate?"margin-left 180ms ease":"none",A=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=`${A}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="",Hp(t),Dp(o),Bp(r),Wl(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",A=!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||A?"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 sx(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){sx(r,o)},destroy(){r.remove()}}},qv=(e,t)=>{var P,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"),c=r.createElement("div"),d=r.createElement("aside"),u=r.createElement("div"),g=(y=(P=t==null?void 0:t.launcher)==null?void 0:P.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",c.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",d.appendChild(u),o.insertBefore(s,e),c.appendChild(e);let p=null,m=()=>{p==null||p.disconnect(),p=null},x=()=>{m(),no(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(p=new ResizeObserver(()=>{lx(s,i,c,d,u,t,g)}),p.observe(s))},C=!1,T=()=>{lx(s,i,c,d,u,t,g),x(),g&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,Nv(s,no(t)))},E=s.ownerDocument.defaultView,M=()=>{T()};return E==null||E.addEventListener("resize",M),no(t).reveal==="push"?(i.appendChild(c),i.appendChild(d),s.appendChild(i)):(s.appendChild(c),s.appendChild(d)),T(),{mode:"docked",host:u,shell:s,syncWidgetState(A){let H=A.launcherEnabled?A.open:!0;g!==H&&(g=H,T())},updateConfig(A){var H,W;t=A,((W=(H=t==null?void 0:t.launcher)==null?void 0:H.enabled)!=null?W:!0)===!1&&(g=!0),T()},destroy(){E==null||E.removeEventListener("resize",M),m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Ks=(e,t)=>pr(t)?qv(e,t):Uv(e,t);var Fp={},dx=!1,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},$v=()=>{try{if(typeof Fp!="undefined"&&Fp.url)return new URL("../widget.css",Fp.url).href}catch{}return null},cx=(e,t)=>{let r=$v(),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=>{let t=Vv(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Ks(t,n),s,i=[],c=(T,E)=>{var w,b;let P=!((b=(w=E==null?void 0:E.launcher)==null?void 0:w.enabled)!=null?b:!0)||pr(E),y=o.createElement("div");if(y.setAttribute("data-persona-root","true"),P&&(y.style.height="100%",y.style.display="flex",y.style.flexDirection="column",y.style.flex="1",y.style.minHeight="0"),r){let A=T.attachShadow({mode:"open"});A.appendChild(y),cx(A,o)}else T.appendChild(y),cx(T,o);return t.id&&y.setAttribute("data-persona-instance",t.id),y},d=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},g=()=>{let T=c(a.host,n);s=Il(T,n,{debugTools:e.debugTools}),u()},p=()=>{i.forEach(T=>T()),i=[],s.destroy()};g(),e.onChatReady?e.onChatReady():e.onReady&&(dx||(dx=!0,console.warn("[Persona] `onReady` is deprecated: use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let m=T=>{p(),a.destroy(),a=Ks(t,T),n=T,g()},x={update(T){var b,A,H,W,k,N;let E={...n,...T,launcher:{...(b=n==null?void 0:n.launcher)!=null?b:{},...(A=T==null?void 0:T.launcher)!=null?A:{},dock:{...(W=(H=n==null?void 0:n.launcher)==null?void 0:H.dock)!=null?W:{},...(N=(k=T==null?void 0:T.launcher)==null?void 0:k.dock)!=null?N:{}}}},M=pr(n),P=pr(E),y=Dn(n),w=Dn(E);if(M!==P||y!==w){m(E);return}n=E,a.updateConfig(n),s.update(T),d()},destroy(){p(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},C=new Proxy(x,{get(T,E,M){if(E==="host")return a.host;if(E in T)return Reflect.get(T,E,M);let P=s[E];return typeof P=="function"?P.bind(s):P}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=C),C};var hx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),zv=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"]),Np=/\b(product|card|item|listing|result)\b/i,_p=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Gv=3e3,Kv=100;function xx(e){let t=typeof e.className=="string"?e.className:"";if(Np.test(t)||e.id&&Np.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&Np.test(o.value))return!0}return!1}function yx(e){var t;return _p.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 Xv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ux(e){let t=e.match(_p);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 Qv(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 Jv="commerce-card",Yv="result-card";function mx(e){return!xx(e)||!yx(e)||!bx(e)&&!Xv(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 Up=[{id:Jv,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||_p.test(o)&&o.length<32)}return!0},formatSummary(e,t){var c,d,u;if(mx(e)===0)return null;let{title:r,href:o}=fx(e),n=(u=(d=ux(((c=e.textContent)!=null?c:"").trim()))!=null?d:ux(t.text))!=null?u:"",a=Qv(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 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(`
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,p,m,x,C,T,E,M,P,y,w,b;let t=(u=e.options)!=null?u:{},r=(p=(g=t.maxElements)!=null?g:e.maxElements)!=null?p:80,o=(x=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",n=(T=(C=t.maxTextLength)!=null?C:e.maxTextLength)!=null?T:200,a=(M=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?M:!0,s=(P=t.root)!=null?P:e.root,i=(y=t.mode)!=null?y:"structured",c=(w=t.maxCandidates)!=null?w:Math.max(500,r*10),d=(b=e.rules)!=null?b:Up;return i==="simple"&&e.rules&&e.rules.length>0?(Zv(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:r,maxCandidates:c,excludeSelector:o,maxTextLength:n,visibleOnly:a,root:s,rules:d}}function Op(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"||zv.has(t)||r&&jv.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 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 c=e.getAttribute("role");c&&(t.role=c);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 qp(e){let t=e.tagName.toLowerCase();if(e.id){let n=`#${Op(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}="${Op(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=>Op(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 n0(e){return e==="static"?Kv:Gv}function Cx(e,t){var n;let r=e.tagName.toLowerCase(),o=((n=e.textContent)!=null?n:"").trim().substring(0,t);return{selector:qp(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(hx.has(u)){i=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!vx(d)){i=s.nextNode();continue}let g=Cx(d,e.maxTextLength),p=g.text.length>0,m=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(T=>T==="role");if(!p&&!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,p=u.enriched.interactivity==="static"?1:0;return g!==p?g-p:u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex});let c=[];for(let d of n){if(c.length>=e.maxElements)break;s0(c,d)||c.push(d)}return c.sort((d,u)=>{let g=d.enriched.interactivity==="static"?1:0,p=u.enriched.interactivity==="static"?1:0;return g!==p?g-p:g===1&&u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex}),c.map(d=>{var p;let u;if((p=d.formattingRule)!=null&&p.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 c=a,d=c.tagName.toLowerCase();if(hx.has(d)){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 u=Cx(c,e.maxTextLength),g=u.text.length>0,p=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!g&&!p){a=n.nextNode();continue}o.has(u.selector)||(o.add(u.selector),r.push(u))}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=e0(e),r=(o=t.root)!=null?o:document.body;return r?t.mode==="simple"?l0(t,r):i0(t,r):[]}var Hl=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:
110
+ `}if(!v&&!l){let Gt="max-height: -moz-available !important; max-height: stretch !important;",jt=f?"":"padding-top: 1.25em !important;",gt=f?"":`z-index: ${(hr=(Ze=o.launcher)==null?void 0:Ze.zIndex)!=null?hr:Rr} !important;`;Ue.style.cssText+=Gt+jt+gt}Ke()};xe(),Wn(e,o),Al(e,o),Ml(e,o);let pt=[];pt.push(()=>{document.removeEventListener("keydown",gn)});let or=null,fr=null;pt.push(()=>{or==null||or(),or=null,fr==null||fr(),fr=null}),Kr&&pt.push(()=>{Kr==null||Kr.disconnect(),Kr=null}),pt.push(()=>{Br==null||Br(),Br=null,Go(),Ut&&(Ut.remove(),Ut=null),At==null||At.element.style.removeProperty("width"),At==null||At.element.style.removeProperty("maxWidth")}),Be&&pt.push(()=>{Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),j==null||j.destroy(),j=null,ge==null||ge.destroy(),ge=null,Q=null});let Io=null,Za=()=>{Io&&(Io(),Io=null),o.colorScheme==="auto"&&(Io=rl(()=>{Wn(e,o)}))};Za(),pt.push(()=>{Io&&(Io(),Io=null)});let Ko=(Ju=o.features)==null?void 0:Ju.streamAnimation;if(Ko!=null&&Ko.type&&Ko.type!=="none"){let l=Bs(Ko.type,Ko.plugins);l&&(mp(l,e),pt.push(()=>Mh(e)))}let qn=Uh(Kt),Ro=null,_,ha=l=>{var v,I;if(!_)return;let f=l!=null?l:_.getMessages(),h=((I=(v=o.features)==null?void 0:v.suggestReplies)==null?void 0:I.enabled)!==!1?Mi(f):null;h?qn.render(h,_,ke,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(F=>F.role==="user")?qn.render([],_,ke,f):qn.render(o.suggestionChips,_,ke,f,o.suggestionChipsConfig)},Wo=!1,Ho=hh(),Xo=new Map,Bo=new Map,yo=new Map,xa=0,Xs=Ia()!==null,Zr=al(),eo=0,bo=null,vo=!1,Vn=!1,Qo=0,Er=null,Do=null,ya=!1,$n=!1,ba=null,Qs=4,va=24,Js=80,Ca=new Map,ht={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},es=(Zu=(Yu=o.voiceRecognition)==null?void 0:Yu.autoResume)!=null?Zu:!1,uo=l=>{a.emit("voice:state",{active:ht.active,source:l,timestamp:Date.now()})},$r=()=>{m(l=>({...l,voiceState:{active:ht.active,timestamp:Date.now(),manuallyDeactivated:ht.manuallyDeactivated}}))},Ys=()=>{var v,I;if(((v=o.voiceRecognition)==null?void 0:v.enabled)===!1)return;let l=Hp(c.voiceState),f=!!l.active,h=Number((I=l.timestamp)!=null?I:0);ht.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-h<Wv&&setTimeout(()=>{var F,$;ht.active||(ht.manuallyDeactivated=!1,(($=(F=o.voiceRecognition)==null?void 0:F.provider)==null?void 0:$.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),uo("restore"),_.isVoiceActive()&&Ma()}):ci("restore"))},1e3)},Zs=()=>_?sx(_.getMessages()).filter(l=>!l.__skipPersist):[];function wa(l){if(!(i!=null&&i.save))return;let h={messages:l?sx(l):_?Zs():[],metadata:c,artifacts:Xr.artifacts,selectedArtifactId:Xr.selectedId};try{let v=i.save(h);v instanceof Promise&&v.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)})}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",v)}}let Jo=null,ts=()=>Ue.querySelector("#persona-scroll-container")||Te,yn=()=>{Jo!==null&&(cancelAnimationFrame(Jo),Jo=null),vo=!1},rs=()=>{bo!==null&&(cancelAnimationFrame(bo),bo=null),Vn=!1,yn()},os=()=>{Qo>0?(Wr.textContent=String(Qo),Wr.style.display="",ct.setAttribute("aria-label",`${ir()||"Jump to latest"} (${Qo} new)`)):(Wr.textContent="",Wr.style.display="none",ct.setAttribute("aria-label",ir()||"Jump to latest"))},ns=()=>{Qo!==0&&(Qo=0,os())},as=()=>et()==="follow"?!Zr.isFollowing():!da(Te,va),zr=()=>{if(!_t()||de){ct.parentNode&&ct.remove(),ct.style.display="none";return}ct.parentNode!==ce&&ce.appendChild(ct),qr();let f=sn(Te)>0&&as();f||ns(),ct.style.display=f?"":"none"},Sa=()=>{Zr.pause()&&(rs(),zr())},Fo=()=>{Zr.resume(),ns(),zr()},No=(l=!1)=>{et()==="follow"&&Zr.isFollowing()&&(!l&&!Wo||(bo!==null&&(cancelAnimationFrame(bo),bo=null),Vn=!0,bo=requestAnimationFrame(()=>{bo=null,Vn=!1,Zr.isFollowing()&&ei(ts(),l?220:140)})))},ss=(l,f,h,v=()=>!0)=>{let I=l.scrollTop,F=f(),$=F-I;yn();let O=performance.now();vo=!0;let D=ne=>1-Math.pow(1-ne,3),oe=ne=>{if(!v()){yn();return}let X=f();X!==F&&(F=X,$=F-I);let ye=ne-O,Fe=Math.min(ye/h,1),Se=D(Fe),tt=I+$*Se;l.scrollTop=tt,eo=l.scrollTop,Fe<1?Jo=requestAnimationFrame(oe):(l.scrollTop=F,eo=l.scrollTop,Jo=null,vo=!1)};Jo=requestAnimationFrame(oe)},ei=(l,f=500)=>{let h=sn(l)-l.scrollTop;if(Math.abs(h)<1){eo=l.scrollTop;return}if(Math.abs(h)>=Js){yn(),vo=!0,l.scrollTop=sn(l),eo=l.scrollTop,vo=!1;return}ss(l,()=>sn(l),f,()=>Zr.isFollowing())},is=()=>{let l=ts();vo=!0,l.scrollTop=sn(l),eo=l.scrollTop,vo=!1,zr()},ls=l=>{lr.style.height=`${Math.max(0,Math.round(l))}px`,Er&&(Er.spacerHeight=Math.max(0,l))},zn=()=>{Do!==null&&(cancelAnimationFrame(Do),Do=null),yn(),Er=null,lr.style.height="0px"},ti=l=>{Do!==null&&cancelAnimationFrame(Do),Do=requestAnimationFrame(()=>{var oe;Do=null;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Te.querySelector(`[data-message-id="${f}"]`);if(!h)return;let v=0,I=h;for(;I&&I!==Te;)v+=I.offsetTop,I=I.offsetParent;let F=(oe=Er==null?void 0:Er.spacerHeight)!=null?oe:0,$=Te.scrollHeight-F,{targetScrollTop:O,spacerHeight:D}=Ch({anchorOffsetTop:v,topOffset:Ot(),viewportHeight:Te.clientHeight,contentHeight:$});Er={initialSpacerHeight:D,contentHeightAtAnchor:$,spacerHeight:D},ls(D),ss(Te,()=>O,220)})},ri=()=>{if(et()==="follow"){if(!Zr.isFollowing()||da(Te,1))return;No(!Wo);return}if(Er&&Er.initialSpacerHeight>0){let l=Te.scrollHeight-Er.spacerHeight,f=wh({initialSpacerHeight:Er.initialSpacerHeight,contentHeightAtAnchor:Er.contentHeightAtAnchor,currentContentHeight:l});f!==Er.spacerHeight&&ls(f)}zr()},oi=l=>{let f=et();f==="follow"?(Fo(),No(!0)):f==="anchor-top"&&ti(l)},ni=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),!$n&&et()!=="anchor-top"&&as()&&(Qo+=1,os(),zr())),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)})},ai=(l,f,h)=>{var st,Ie,Le,ze,Ke,bt;let v=document.createElement("div"),F=(()=>{var We;let B=n.find(Re=>Re.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((We=o.loadingIndicator)!=null&&We.render)return o.loadingIndicator.render})(),$=(B,We)=>We==null?!1:typeof We=="string"?(B.textContent=We,!0):(B.appendChild(We),!0),O=new Set,D=new Set,oe=n.some(B=>B.renderAskUserQuestion),ne=[],X=[],ye=o.enableComponentStreaming!==!1,Fe=n.some(B=>B.renderApproval)&&o.approval!==!1,Se=[];if(f.forEach(B=>{var Qe,Wt,pr,mo,ro,jn,Gn,Ea,ka,Yt,Kn,Mn,Tn,en,Xn,Co;O.add(B.id);let We=oe&&rn(B),Re=Fe&&B.variant==="approval"&&!!B.approval,fe=!We&&B.role==="assistant"&&!B.variant&&ye&&Ll(B);if(!Re&&yo.has(B.id)){let Ze=l.querySelector(`#wrapper-${B.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),yo.delete(B.id)}if(!fe&&Bo.has(B.id)){let Ze=l.querySelector(`#wrapper-${B.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),Bo.delete(B.id)}let zt=rn(B)?`:${(Qe=B.agentMetadata)!=null&&Qe.askUserQuestionAnswered?"a":"u"}:${(Wt=B.agentMetadata)!=null&&Wt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Vt=gh(B,xa)+zt,Jt=We||Re||fe?null:xh(Ho,B.id,Vt);if(Jt){v.appendChild(Jt.cloneNode(!0)),rn(B)&&((pr=B.toolCall)!=null&&pr.id)&&((mo=B.agentMetadata)==null?void 0:mo.awaitingLocalTool)===!0&&!((ro=B.agentMetadata)!=null&&ro.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Da(B,o,J.composerOverlay));return}let Ct=null,Xt=n.find(Ze=>!!(B.variant==="reasoning"&&Ze.renderReasoning||B.variant==="tool"&&Ze.renderToolCall||!B.variant&&Ze.renderMessage)),to=(jn=o.layout)==null?void 0:jn.messages;if(rn(B)&&((Gn=B.agentMetadata)==null?void 0:Gn.askUserQuestionAnswered)===!0){Xo.delete(B.id);let Ze=l.querySelector(`#wrapper-${B.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime");return}if(Ss(B)&&((ka=(Ea=o.features)==null?void 0:Ea.suggestReplies)==null?void 0:ka.enabled)!==!1)return;if(rn(B)&&((Kn=(Yt=o.features)==null?void 0:Yt.askUserQuestion)==null?void 0:Kn.enabled)!==!1){let Ze=n.find(hr=>typeof hr.renderAskUserQuestion=="function");if(Ze&&Et.current){let hr=Xo.get(B.id),Gt=hr!==Vt,jt=null;if(Gt){let{payload:Mt,complete:Lr}=on(B),Dr=B.id,_o=()=>{var wr;return(wr=Et.current)==null?void 0:wr.getMessages().find(Fr=>Fr.id===Dr)};jt=Ze.renderAskUserQuestion({message:B,payload:Mt,complete:Lr,resolve:wr=>{var Nr;let Fr=_o();Fr&&((Nr=Et.current)==null||Nr.resolveAskUserQuestion(Fr,wr))},dismiss:()=>{var Fr,Nr,Qn;let wr=_o();(Fr=wr==null?void 0:wr.agentMetadata)!=null&&Fr.awaitingLocalTool&&((Nr=Et.current)==null||Nr.markAskUserQuestionResolved(wr),(Qn=Et.current)==null||Qn.resolveAskUserQuestion(wr,"(dismissed)"))},config:o})}let gt=hr!=null;if(Gt&&jt===null&&!gt){((Mn=B.agentMetadata)==null?void 0:Mn.awaitingLocalTool)===!0&&!((Tn=B.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Da(B,o,J.composerOverlay));return}let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-${B.id}`,Zt.setAttribute("data-wrapper-id",B.id),Zt.setAttribute("data-ask-plugin-stub","true"),Zt.setAttribute("data-preserve-runtime","true"),v.appendChild(Zt),ne.push({messageId:B.id,fingerprint:Vt,bubble:jt});return}else{((en=B.agentMetadata)==null?void 0:en.awaitingLocalTool)===!0&&!((Xn=B.agentMetadata)!=null&&Xn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Da(B,o,J.composerOverlay));return}}else if(Re){let Ze=n.find(gt=>typeof gt.renderApproval=="function"),Gt=yo.get(B.id)!==Vt,jt=null;if(Gt&&(Ze!=null&&Ze.renderApproval)){let gt=B.id,Zt=(Mt,Lr)=>{var _o,wr,Fr;let Dr=(_o=Et.current)==null?void 0:_o.getMessages().find(Nr=>Nr.id===gt);Dr!=null&&Dr.approval&&(Dr.approval.toolType==="webmcp"?(wr=Et.current)==null||wr.resolveWebMcpApproval(Dr.id,Mt):(Fr=Et.current)==null||Fr.resolveApproval(Dr.approval,Mt,Lr))};jt=Ze.renderApproval({message:B,defaultRenderer:()=>wl(B,o),config:o,approve:Mt=>Zt("approved",Mt),deny:Mt=>Zt("denied",Mt)})}if(Gt&&jt===null){let gt=l.querySelector(`#wrapper-${B.id}`);gt==null||gt.removeAttribute("data-preserve-runtime"),yo.delete(B.id),Ct=wl(B,o)}else{let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${B.id}`,gt.setAttribute("data-wrapper-id",B.id),gt.setAttribute("data-approval-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),v.appendChild(gt),Se.push({messageId:B.id,fingerprint:Vt,bubble:jt});return}}else if(Xt)if(B.variant==="reasoning"&&B.reasoning&&Xt.renderReasoning){if(!Ge)return;Ct=Xt.renderReasoning({message:B,defaultRenderer:()=>Tp(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&Xt.renderToolCall){if(!Ce)return;Ct=Xt.renderToolCall({message:B,defaultRenderer:()=>Ep(B,o),config:o})}else Xt.renderMessage&&(Ct=Xt.renderMessage({message:B,defaultRenderer:()=>{let Ze=ja(B,h,to,o.messageActions,Z,{loadingIndicatorRenderer:F,widgetConfig:o});return B.role!=="user"&&Ip(Ze,B,o,_),Ze},config:o}));if(!Ct&&fe){let Ze=Pl(B);if(Ze){let hr=Bo.get(B.id),Gt=hr!==Vt,jt=o.wrapComponentDirectiveInBubble!==!1,gt=null;if(Gt){let Zt=kl(Ze,{config:o,message:B,transform:h});if(Zt)if(jt){let Mt=document.createElement("div");if(Mt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Mt.id=`bubble-${B.id}`,Mt.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let Lr=document.createElement("div");Lr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Lr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Mt.appendChild(Lr)}Mt.appendChild(Zt),gt=Mt}else{let Mt=document.createElement("div");if(Mt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Mt.id=`bubble-${B.id}`,Mt.setAttribute("data-message-id",B.id),Mt.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let Lr=document.createElement("div");Lr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Lr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Mt.appendChild(Lr)}Mt.appendChild(Zt),gt=Mt}}if(gt||hr!=null){let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-${B.id}`,Zt.setAttribute("data-wrapper-id",B.id),Zt.setAttribute("data-component-directive-stub","true"),Zt.setAttribute("data-preserve-runtime","true"),jt||Zt.classList.add("persona-w-full"),v.appendChild(Zt),X.push({messageId:B.id,fingerprint:Vt,bubble:gt});return}}}if(!Ct)if(B.variant==="reasoning"&&B.reasoning){if(!Ge)return;Ct=Tp(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!Ce)return;Ct=Ep(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;Ct=wl(B,o)}else{let Ze=(Co=o.layout)==null?void 0:Co.messages;Ze!=null&&Ze.renderUserMessage&&B.role==="user"?Ct=Ze.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):Ze!=null&&Ze.renderAssistantMessage&&B.role==="assistant"?Ct=Ze.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):Ct=ja(B,h,Ze,o.messageActions,Z,{loadingIndicatorRenderer:F,widgetConfig:o}),B.role!=="user"&&Ct&&Ip(Ct,B,o,_)}let ar=document.createElement("div");ar.className="persona-flex",ar.id=`wrapper-${B.id}`,ar.setAttribute("data-wrapper-id",B.id),B.role==="user"&&ar.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&ar.classList.add("persona-w-full"),ar.appendChild(Ct),yh(Ho,B.id,Vt,ar),v.appendChild(ar)}),J.composerOverlay&&J.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let Re=We.getAttribute("data-persona-ask-sheet-for");Re&&!D.has(Re)&&Ln(J.composerOverlay,Re)}),(Ie=(st=o.features)==null?void 0:st.toolCallDisplay)!=null&&Ie.grouped){let B=[],We=[];f.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&Ce){We.push(Re);return}We.length>1&&B.push(We),We=[]}),We.length>1&&B.push(We),B.forEach((Re,fe)=>{var Qe,Wt;let zt=Re.map(pr=>Array.from(v.children).find(mo=>mo instanceof HTMLElement&&mo.getAttribute("data-wrapper-id")===pr.id)).filter(pr=>!!pr);if(zt.length<2)return;let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id=`wrapper-tool-group-${fe}-${Re[0].id}`,Vt.setAttribute("data-wrapper-id",`tool-group-${fe}-${Re[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Xt=`Called ${Re.length} tools`,to=(Wt=(Qe=o.toolCall)==null?void 0:Qe.renderGroupedSummary)==null?void 0:Wt.call(Qe,{messages:Re,toolCalls:Re.map(pr=>pr.toolCall).filter(pr=>!!pr),defaultSummary:Xt,config:o});$(Ct,to)||(Ct.textContent=Xt);let ar=document.createElement("div");ar.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(Ct,ar),Vt.appendChild(Jt),zt[0].before(Vt),zt.forEach((pr,mo)=>{let ro=document.createElement("div");ro.className="persona-tool-group-item persona-relative",ro.setAttribute("data-persona-tool-group-item","true"),mo<zt.length-1&&ro.setAttribute("data-persona-tool-group-connector","true"),ro.appendChild(pr),ar.appendChild(ro)})})}bh(Ho,O);let tt=f.some(B=>B.role==="assistant"&&B.streaming),$e=f[f.length-1],mt=($e==null?void 0:$e.role)==="assistant"&&!$e.streaming&&$e.variant!=="approval";if(Wo&&f.some(B=>B.role==="user")&&!tt&&!mt){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ua},We=n.find(fe=>fe.renderLoadingIndicator),Re=null;if(We!=null&&We.renderLoadingIndicator&&(Re=We.renderLoadingIndicator(B)),Re===null&&((Le=o.loadingIndicator)!=null&&Le.render)&&(Re=o.loadingIndicator.render(B)),Re===null&&(Re=ua()),Re){let fe=document.createElement("div"),zt=((ze=o.loadingIndicator)==null?void 0:ze.showBubble)!==!1;fe.className=zt?["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(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Re);let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id="wrapper-typing-indicator",Vt.setAttribute("data-wrapper-id","typing-indicator"),Vt.appendChild(fe),v.appendChild(Vt)}}if(!Wo&&f.length>0){let B=f[f.length-1],We={config:o,lastMessage:B,messageCount:f.length},Re=n.find(zt=>zt.renderIdleIndicator),fe=null;if(Re!=null&&Re.renderIdleIndicator&&(fe=Re.renderIdleIndicator(We)),fe===null&&((Ke=o.loadingIndicator)!=null&&Ke.renderIdle)&&(fe=o.loadingIndicator.renderIdle(We)),fe){let zt=document.createElement("div"),Vt=((bt=o.loadingIndicator)==null?void 0:bt.showBubble)!==!1;zt.className=Vt?["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(" "),zt.setAttribute("data-idle-indicator","true"),zt.appendChild(fe);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(zt),v.appendChild(Jt)}}if(ol(l,v),ne.length>0)for(let{messageId:B,fingerprint:We,bubble:Re}of ne){let fe=l.querySelector(`#wrapper-${B}`);fe&&Re!==null&&(fe.replaceChildren(Re),fe.setAttribute("data-bubble-fp",We),Xo.set(B,We))}if(Xo.size>0)for(let B of Xo.keys())O.has(B)||Xo.delete(B);if(X.length>0)for(let{messageId:B,fingerprint:We,bubble:Re}of X){let fe=l.querySelector(`#wrapper-${B}`);fe&&Re!==null&&(fe.replaceChildren(Re),fe.setAttribute("data-bubble-fp",We),Bo.set(B,We))}if(Bo.size>0)for(let B of Bo.keys())O.has(B)||Bo.delete(B);if(Se.length>0)for(let{messageId:B,fingerprint:We,bubble:Re}of Se){let fe=l.querySelector(`#wrapper-${B}`);fe&&Re!==null&&(fe.replaceChildren(Re),fe.setAttribute("data-bubble-fp",We),yo.set(B,We))}if(yo.size>0)for(let B of yo.keys())O.has(B)||yo.delete(B)},bn=(l,f,h)=>{ai(l,f,h),fn()},vn=null,si=()=>{var h;if(vn)return;let l=v=>{let I=v.composedPath();I.includes(Ue)||Je&&I.includes(Je)||he(!1,"user")};vn=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},ds=()=>{var f;if(!vn)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",vn,!0),vn=null};pt.push(()=>ds());let Cn=null,ii=()=>{var h;if(Cn)return;let l=v=>{v.key==="Escape"&&(v.isComposing||he(!1,"user"))};Cn=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},cs=()=>{var f;if(!Cn)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Cn,!0),Cn=null};pt.push(()=>cs());let wn=!1,ps=new Set,li=()=>{var f,h,v,I;let l=(v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:v.streamAnimation;return l||((I=o.features)==null?void 0:I.streamAnimation)},Yo=()=>{var mt,st,Ie,Le;if(!W())return;let l=J.peekBanner,f=J.peekTextNode;if(!l||!f)return;if(L){l.classList.remove("persona-pill-peek--visible");return}let h=(mt=_==null?void 0:_.getMessages())!=null?mt:[],v;for(let ze=h.length-1;ze>=0;ze--){let Ke=h[ze];if(Ke.role==="assistant"&&Ke.content){v=Ke;break}}if(!v){l.classList.remove("persona-pill-peek--visible");return}let I=v.content,F=!!v.streaming,$=li(),O=ll($),D=O.type!=="none"?Bs(O.type,$==null?void 0:$.plugins):null,oe=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,v))===!0,ne=D!==null&&(F||oe);ne&&D&&!ps.has(D.name)&&(mp(D,e),ps.add(D.name));let X=ne&&(D!=null&&D.containerClass)?D.containerClass:null,ye=(Ie=f.dataset.personaPeekStreamClass)!=null?Ie:null;ye&&ye!==X&&(f.classList.remove(ye),delete f.dataset.personaPeekStreamClass),X&&ye!==X&&(f.classList.add(X),f.dataset.personaPeekStreamClass=X),ne?(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 Fe=ne?dl(I,O.buffer,D,v,F):I;if(ne&&O.placeholder==="skeleton"&&F&&(!Fe||!Fe.trim())){let ze=document.createElement("div"),Ke=Fs();Ke.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ke),ol(f,ze)}else{let ze=Math.max(0,Fe.length-100),Ke=Fe.length>100?Fe.slice(-100):Fe,bt=Uo(Ke);if(!ne||!D){let B=Fe.length>100?`\u2026${Ke}`:Ke;f.textContent!==B&&(f.textContent=B)}else{let B=bt;(D.wrap==="char"||D.wrap==="word")&&(B=Ds(bt,D.wrap,`peek-${v.id}`,{skipTags:D.skipTags,startIndex:ze}));let We=document.createElement("div");if(We.innerHTML=B,D.useCaret&&Ke.length>0){let Re=cl(),fe=We.querySelectorAll(".persona-stream-char, .persona-stream-word"),zt=fe[fe.length-1];zt!=null&&zt.parentNode?zt.parentNode.insertBefore(Re,zt.nextSibling):We.appendChild(Re)}ol(f,We),(Le=D.onAfterRender)==null||Le.call(D,{container:f,bubble:l,messageId:v.id,message:v,speed:O.speed,duration:O.duration})}}let $e=Wo||wn;l.classList.toggle("persona-pill-peek--visible",$e)};if(W()){let l=J.peekBanner;if(l){let v=I=>{I.preventDefault(),I.stopPropagation(),he(!0,"user")};l.addEventListener("pointerdown",v),pt.push(()=>{l.removeEventListener("pointerdown",v)})}let f=()=>{wn||(wn=!0,Yo())},h=()=>{wn&&(wn=!1,Yo())};be.addEventListener("pointerenter",f),be.addEventListener("pointerleave",h),pt.push(()=>{be.removeEventListener("pointerenter",f),be.removeEventListener("pointerleave",h)}),Je&&(Je.addEventListener("pointerenter",f),Je.addEventListener("pointerleave",h),pt.push(()=>{Je.removeEventListener("pointerenter",f),Je.removeEventListener("pointerleave",h)}))}let di=l=>{var ye,Fe,Se,tt,$e,mt,st,Ie;let f=(Fe=(ye=o.launcher)==null?void 0:ye.composerBar)!=null?Fe:{},h=(Se=f.expandedSize)!=null?Se:"anchored",v=(tt=f.bottomOffset)!=null?tt:"16px",I=f.collapsedMaxWidth,F=($e=f.expandedMaxWidth)!=null?$e:"880px",$=(mt=f.expandedTopOffset)!=null?mt:"5vh",O=(st=f.modalMaxWidth)!=null?st:"880px",D=(Ie=f.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",oe="calc(100vw - 32px)",ne="var(--persona-pill-area-height, 80px)",X=Ue.style;if(X.left="",X.right="",X.top="",X.bottom="",X.transform="",X.width="",X.maxWidth="",X.height="",X.maxHeight="",Je){let Le=Je.style;Le.bottom=v,Le.width=I!=null?I:""}if(l&&h!=="fullscreen"){if(h==="modal"){X.top="50%",X.left="50%",X.transform="translate(-50%, -50%)",X.bottom="auto",X.right="auto",X.width=O,X.maxWidth=oe,X.maxHeight=D,X.height=D;return}X.left="50%",X.transform="translateX(-50%)",X.bottom=`calc(${v} + ${ne})`,X.top=$,X.width=F,X.maxWidth=oe}},Oo=()=>{var D,oe,ne,X,ye,Fe,Se,tt;if(!R())return;if(W()){let mt=(ne=((oe=(D=o.launcher)==null?void 0:D.composerBar)!=null?oe:{}).expandedSize)!=null?ne:"anchored",st=L?"expanded":"collapsed";Ue.dataset.state=st,Ue.dataset.expandedSize=mt,Je&&(Je.dataset.state=st,Je.dataset.expandedSize=mt),Ue.style.removeProperty("display"),Ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),di(L),ce.style.display=L?"flex":"none",xe(),L?(si(),ii()):(ds(),cs()),Yo();return}let l=ur(o),f=(X=e.ownerDocument.defaultView)!=null?X:window,h=(Fe=(ye=o.launcher)==null?void 0:ye.mobileBreakpoint)!=null?Fe:640,v=(tt=(Se=o.launcher)==null?void 0:Se.mobileFullscreen)!=null?tt:!0,I=f.innerWidth<=h,F=v&&I&&E,$=ao(o).reveal;L?(Ue.style.removeProperty("display"),Ue.style.display=l?"flex":"",Ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0"),be.classList.add("persona-scale-100","persona-opacity-100"),nr?nr.element.style.display="none":gr&&(gr.style.display="none")):(l?l&&($==="overlay"||$==="push")&&!F?(Ue.style.removeProperty("display"),Ue.style.display="flex",Ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ue.style.setProperty("display","none","important"),Ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ue.style.display="",Ue.classList.add("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100"),be.classList.add("persona-scale-95","persona-opacity-0")),nr?nr.element.style.display=l?"none":"":gr&&(gr.style.display=l?"none":""))},he=(l,f="user")=>{var F,$;if(!R()||L===l)return;let h=L;L=l,Oo();let v=(()=>{var Se,tt,$e,mt,st,Ie,Le,ze,Ke,bt;let O=(tt=(Se=o.launcher)==null?void 0:Se.sidebarMode)!=null?tt:!1,D=($e=e.ownerDocument.defaultView)!=null?$e:window,oe=(st=(mt=o.launcher)==null?void 0:mt.mobileFullscreen)!=null?st:!0,ne=(Le=(Ie=o.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Le:640,X=D.innerWidth<=ne,ye=ur(o)&&oe&&X,Fe=W()&&((bt=(Ke=(ze=o.launcher)==null?void 0:ze.composerBar)==null?void 0:Ke.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return O||oe&&X&&E||ye||Fe})();if(L&&v){if(!or){let O=e.getRootNode(),D=O instanceof ShadowRoot?O.host:e.closest(".persona-host");D&&(or=gp(D,($=(F=o.launcher)==null?void 0:F.zIndex)!=null?$:Rr))}fr||(fr=hp(e.ownerDocument))}else L||(or==null||or(),or=null,fr==null||fr(),fr=null);L&&(us(),et()==="follow"?No(!0):is());let I={open:L,source:f,timestamp:Date.now()};L&&!h?a.emit("widget:opened",I):!L&&h&&a.emit("widget:closed",I),a.emit("widget:state",{open:L,launcherEnabled:E,voiceActive:ht.active,streaming:_.isStreaming()})},P=l=>{Tt(l?"stop":"send"),z&&(z.disabled=l),qn.buttons.forEach(f=>{f.disabled=l}),He.dataset.personaComposerStreaming=l?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},U=()=>{ht.active||ke&&ke.focus()};a.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>U(),200)});let H=()=>{var h,v,I,F,$,O,D,oe,ne,X,ye;To.textContent=(v=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?v:"Hello \u{1F44B}",Tr.textContent=(F=(I=o.copy)==null?void 0:I.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",ke.placeholder=(O=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?O:"How can I help...";let l=Te.querySelector("[data-persona-intro-card]");if(l){let Fe=((D=o.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(Te.classList.remove("persona-gap-3"),Te.classList.add("persona-gap-6")):(Te.classList.remove("persona-gap-6"),Te.classList.add("persona-gap-3"))}!((ne=(oe=o.sendButton)==null?void 0:oe.useIcon)!=null&&ne)&&!(_!=null&&_.isStreaming())&&(Ve.textContent=(ye=(X=o.copy)==null?void 0:X.sendButtonLabel)!=null?ye:"Send"),ke.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ke.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{m(f=>({...f,sessionId:l}))}});let G=null,re=()=>{G==null&&(G=setInterval(()=>{let l=Xe.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(G),G=null;return}let f=Date.now();l.forEach(h=>{let v=Number(h.getAttribute("data-tool-elapsed"));v&&(h.textContent=Ei(f-v))})},100))};_=new _a(o,{onMessagesChanged(l){var v;bn(Xe,l,me),re(),ha(l),No(!Wo),ni(l);let f=[...l].reverse().find(I=>I.role==="user");l.length===0&&zn(),!ya||$n?(ya=!0,ba=(v=f==null?void 0:f.id)!=null?v:null):f&&f.id!==ba&&(ba=f.id,oi(f.id));let h=ht.lastUserMessageId;f&&f.id!==h&&(ht.lastUserMessageId=f.id,a.emit("user:message",f)),ht.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),wa(l),Yo()},onStatusChanged(l){var v;let f=(v=o.statusIndicator)!=null?v:{};Pt(vr,(I=>{var F,$,O,D;return I==="idle"?(F=f.idleText)!=null?F:Ir.idle:I==="connecting"?($=f.connectingText)!=null?$:Ir.connecting:I==="connected"?(O=f.connectedText)!=null?O:Ir.connected:I==="error"?(D=f.errorText)!=null?D:Ir.error:Ir[I]})(l),f,l)},onStreamingChanged(l){Wo=l,P(l),_&&bn(Xe,_.getMessages(),me),l||No(!0),Yo()},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":Zo(),Ma();break;case"processing":Zo(),Gx();break;case"speaking":Zo(),Kx();break;default:l==="idle"&&_.isBargeInActive()?(Zo(),Ma(),z==null||z.setAttribute("aria-label","End voice session")):(ht.active=!1,Zo(),uo("system"),$r());break}},onArtifactsState(l){Xr=l,Yr(),wa()}}),Et.current=_;let K=null;if(_.onReadAloudChange((l,f)=>{var I;pn=l,un=f,fn();let h=l!=null?l:K;l&&(K=l);let v=h&&(I=_.getMessages().find(F=>F.id===h))!=null?I:null;a.emit("message:read-aloud",{messageId:h,message:v,state:f,timestamp:Date.now()}),f==="idle"&&(K=null)}),ya=!0,((tf=(ef=o.voiceRecognition)==null?void 0:ef.provider)==null?void 0:tf.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)}),(ge||o.onSSEEvent)&&_.setSSEEventCallback((l,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,l,f),ue==null||ue.processEvent(l,f),ge==null||ge.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&&(c=Hp(l.metadata),T.syncFromMetadata()),(f=l.messages)!=null&&f.length){$n=!0;try{_.hydrateMessages(l.messages)}finally{$n=!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 Pe=()=>{var f,h,v;!W()||L||!((v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||v)||he(!0,"auto")},Oe=l=>{var I;if(l.preventDefault(),_.isStreaming()){_.cancel(),ue==null||ue.reset(),j==null||j.update();return}let f=ke.value.trim(),h=(I=vt==null?void 0:vt.hasAttachments())!=null?I:!1;if(!f&&!h)return;Pe();let v;h&&(v=[],v.push(...vt.getContentParts()),f&&v.push(Es(f))),ke.value="",ke.style.height="auto",qt(),_.sendMessage(f,{contentParts:v}),h&&vt.clearAttachments()},at=()=>{var l;return((l=o.features)==null?void 0:l.composerHistory)!==!1},Ye={...nl},It=!1,qt=()=>{Ye={...nl}},Cr=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var f;return(f=l.content)!=null?f:""}).filter(l=>l.length>0),Rt=l=>{if(!ke)return;It=!0,ke.value=l,ke.dispatchEvent(new Event("input",{bubbles:!0})),It=!1;let f=ke.value.length;ke.setSelectionRange(f,f)},Bt=()=>{It||qt()},mr=l=>{if(ke){if(at()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=ke.selectionStart===0&&ke.selectionEnd===0,h=mh({direction:l.key==="ArrowUp"?"up":"down",history:Cr(),currentValue:ke.value,atStart:f,state:Ye});if(Ye=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Rt(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}qt(),l.preventDefault(),Ve.click()}}},kr=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(ce)&&(_.cancel(),ue==null||ue.reset(),j==null||j.update(),qt(),l.preventDefault(),l.stopImmediatePropagation())},Ar=async l=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!vt)return;let f=Bv(l.clipboardData);f.length!==0&&(l.preventDefault(),await vt.handleFiles(f))},Dt=null,dr=!1,Aa=null,ft=null,Jp=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ci=(l="user")=>{var F,$,O,D,oe,ne,X;if(dr||_.isStreaming())return;let f=Jp();if(!f)return;Dt=new f;let v=($=((F=o.voiceRecognition)!=null?F:{}).pauseDuration)!=null?$:2e3;Dt.continuous=!0,Dt.interimResults=!0,Dt.lang="en-US";let I=ke.value;Dt.onresult=ye=>{let Fe="",Se="";for(let $e=0;$e<ye.results.length;$e++){let mt=ye.results[$e],st=mt[0].transcript;mt.isFinal?Fe+=st+" ":Se=st}let tt=I+Fe+Se;ke.value=tt,Aa&&clearTimeout(Aa),(Fe||Se)&&(Aa=window.setTimeout(()=>{let $e=ke.value.trim();$e&&Dt&&dr&&(Sn(),ke.value="",ke.style.height="auto",_.sendMessage($e,{viaVoice:!0}))},v))},Dt.onerror=ye=>{ye.error!=="no-speech"&&Sn()},Dt.onend=()=>{if(dr){let ye=ke.value.trim();ye&&ye!==I.trim()&&(ke.value="",ke.style.height="auto",_.sendMessage(ye,{viaVoice:!0})),Sn()}};try{if(Dt.start(),dr=!0,ht.active=!0,l!=="system"&&(ht.manuallyDeactivated=!1),uo(l),$r(),z){let ye=(O=o.voiceRecognition)!=null?O:{};ft={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(D=ye.iconName)!=null?D:"mic",iconSize:parseFloat((X=(ne=ye.iconSize)!=null?ne:(oe=o.sendButton)==null?void 0:oe.size)!=null?X:"40")||24};let Fe=ye.recordingBackgroundColor,Se=ye.recordingIconColor,tt=ye.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let $e=z.querySelector("svg");$e&&$e.setAttribute("stroke",Se)}tt&&(z.style.borderColor=tt),z.setAttribute("aria-label","Stop voice recognition")}}catch{Sn("system")}},Sn=(l="user")=>{if(dr){if(dr=!1,Aa&&(clearTimeout(Aa),Aa=null),Dt){try{Dt.stop()}catch{}Dt=null}if(ht.active=!1,uo(l),$r(),z){if(z.classList.remove("persona-voice-recording"),ft){z.style.backgroundColor=ft.backgroundColor,z.style.color=ft.color,z.style.borderColor=ft.borderColor;let f=z.querySelector("svg");f&&f.setAttribute("stroke",ft.color||"currentColor"),ft=null}z.setAttribute("aria-label","Start voice recognition")}}},jx=(l,f)=>{var st,Ie,Le,ze,Ke,bt,B,We,Re;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),v=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",I=((Ie=l==null?void 0:l.provider)==null?void 0:Ie.type)==="custom";if(!(h||v||I))return null;let $=A("div","persona-send-button-wrapper"),O=A("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 D=(Le=l==null?void 0:l.iconName)!=null?Le:"mic",oe=(ze=f==null?void 0:f.size)!=null?ze:"40px",ne=(Ke=l==null?void 0:l.iconSize)!=null?Ke:oe,X=parseFloat(ne)||24,ye=(bt=l==null?void 0:l.backgroundColor)!=null?bt:f==null?void 0:f.backgroundColor,Fe=(B=l==null?void 0:l.iconColor)!=null?B:f==null?void 0:f.textColor;O.style.width=ne,O.style.height=ne,O.style.minWidth=ne,O.style.minHeight=ne,O.style.fontSize="18px",O.style.lineHeight="1",Fe?O.style.color=Fe:O.style.color="var(--persona-text, #111827)";let tt=ve(D,X,Fe||"currentColor",1.5);tt?O.appendChild(tt):O.textContent="\u{1F3A4}",ye?O.style.backgroundColor=ye: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=(We=l==null?void 0:l.tooltipText)!=null?We:"Start voice recognition";if(((Re=l==null?void 0:l.showTooltip)!=null?Re:!1)&&$e){let fe=A("div","persona-send-button-tooltip");fe.textContent=$e,$.appendChild(fe)}return{micButton:O,micButtonWrapper:$}},Fl=()=>{var f,h,v,I,F;if(!z||ft)return;let l=(f=o.voiceRecognition)!=null?f:{};ft={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((F=(I=l.iconSize)!=null?I:(v=o.sendButton)==null?void 0:v.size)!=null?F:"40")||24}},Nl=(l,f)=>{var F,$,O,D,oe;if(!z)return;let h=z.querySelector("svg");h&&h.remove();let v=(oe=ft==null?void 0:ft.iconSize)!=null?oe:parseFloat((D=(O=(F=o.voiceRecognition)==null?void 0:F.iconSize)!=null?O:($=o.sendButton)==null?void 0:$.size)!=null?D:"40")||24,I=ve(l,v,f,1.5);I&&z.appendChild(I)},pi=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ma=()=>{var I;if(!z)return;Fl();let l=(I=o.voiceRecognition)!=null?I:{},f=l.recordingBackgroundColor,h=l.recordingIconColor,v=l.recordingBorderColor;if(pi(),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 F=z.querySelector("svg");F&&F.setAttribute("stroke",h)}v&&(z.style.borderColor=v),z.setAttribute("aria-label","Stop voice recognition")},Gx=()=>{var O,D,oe,ne,X,ye,Fe,Se;if(!z)return;Fl();let l=(O=o.voiceRecognition)!=null?O:{},f=_.getVoiceInterruptionMode(),h=(D=l.processingIconName)!=null?D:"loader",v=(ne=(oe=l.processingIconColor)!=null?oe:ft==null?void 0:ft.color)!=null?ne:"",I=(ye=(X=l.processingBackgroundColor)!=null?X:ft==null?void 0:ft.backgroundColor)!=null?ye:"",F=(Se=(Fe=l.processingBorderColor)!=null?Fe:ft==null?void 0:ft.borderColor)!=null?Se:"";pi(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=I,z.style.borderColor=F;let $=v||"currentColor";z.style.color=$,Nl(h,$),z.setAttribute("aria-label","Processing voice input"),f==="none"&&(z.style.cursor="default")},Kx=()=>{var oe,ne,X,ye,Fe,Se,tt,$e,mt,st,Ie,Le;if(!z)return;Fl();let l=(oe=o.voiceRecognition)!=null?oe:{},f=_.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",v=(ne=l.speakingIconName)!=null?ne:h,I=(Se=l.speakingIconColor)!=null?Se:f==="barge-in"?(ye=(X=l.recordingIconColor)!=null?X:ft==null?void 0:ft.color)!=null?ye:"":(Fe=ft==null?void 0:ft.color)!=null?Fe:"",F=(mt=l.speakingBackgroundColor)!=null?mt:f==="barge-in"?(tt=l.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":($e=ft==null?void 0:ft.backgroundColor)!=null?$e:"",$=(Le=l.speakingBorderColor)!=null?Le:f==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Ie=ft==null?void 0:ft.borderColor)!=null?Ie:"";pi(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=F,z.style.borderColor=$;let O=I||"currentColor";z.style.color=O,Nl(v,O);let D=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",D),f==="none"&&(z.style.cursor="default"),f==="barge-in"&&z.classList.add("persona-voice-recording")},Zo=()=>{var l,f,h;z&&(pi(),ft&&(z.style.backgroundColor=(l=ft.backgroundColor)!=null?l:"",z.style.color=(f=ft.color)!=null?f:"",z.style.borderColor=(h=ft.borderColor)!=null?h:"",Nl(ft.iconName,ft.color||"currentColor"),ft=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},ui=()=>{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(()=>{ht.active=!1,ht.manuallyDeactivated=!0,$r(),uo("user"),Zo()});return}_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),ht.manuallyDeactivated=!_.isVoiceActive(),$r(),uo("user"),_.isVoiceActive()?Ma():Zo()});return}if(dr){let h=ke.value.trim();ht.manuallyDeactivated=!0,$r(),Sn("user"),h&&(ke.value="",ke.style.height="auto",_.sendMessage(h))}else ht.manuallyDeactivated=!1,$r(),ci("user")};Gr=ui,z&&(z.addEventListener("click",ui),pt.push(()=>{var l,f;((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Zo()):Sn("system"),z&&z.removeEventListener("click",ui)}));let Xx=a.on("assistant:complete",()=>{es&&(ht.active||ht.manuallyDeactivated||es==="assistant"&&!ht.lastUserMessageWasVoice||setTimeout(()=>{var l,f;!ht.active&&!ht.manuallyDeactivated&&(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),uo("auto"),_.isVoiceActive()&&Ma()}):ci("auto"))},600))});pt.push(Xx);let Qx=a.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});pt.push(Qx);let Yp=()=>{he(!L,"user")},nr=null,gr=null;if(E&&!W()){let{instance:l,element:f}=Cp({config:o,plugins:n,onToggle:Yp});nr=l,l||(gr=f)}nr?e.appendChild(nr.element):gr&&e.appendChild(gr),Oo(),ha(),H(),P(_.isStreaming()),et()==="follow"?No(!0):is(),Ys(),k&&(!E||W()?setTimeout(()=>U(),0):L&&setTimeout(()=>U(),200));let us=()=>{var D,oe,ne,X,ye,Fe,Se,tt,$e,mt,st,Ie,Le,ze,Ke,bt,B,We,Re,fe,zt,Vt;if(W()){qr(),Oo();return}let l=ur(o),f=(oe=(D=o.launcher)==null?void 0:D.sidebarMode)!=null?oe:!1,h=l||f||((X=(ne=o.launcher)==null?void 0:ne.fullHeight)!=null?X:!1),v=(ye=e.ownerDocument.defaultView)!=null?ye:window,I=(Se=(Fe=o.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Se:!0,F=($e=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?$e:640,$=v.innerWidth<=F,O=I&&$&&E;try{if(O){xe(),Wn(e,o);return}if(M&&(M=!1,xe(),Wn(e,o)),!E&&!l){be.style.height="",be.style.width="";return}if(!f&&!l){let Jt=(st=(mt=o==null?void 0:o.launcher)==null?void 0:mt.width)!=null?st:o==null?void 0:o.launcherWidth,Ct=Jt!=null?Jt:no;be.style.width=Ct,be.style.maxWidth=Ct}if(Po(),!h){let Jt=v.innerHeight,Ct=64,Xt=(Le=(Ie=o.launcher)==null?void 0:Ie.heightOffset)!=null?Le:0,to=Math.max(200,Jt-Ct),ar=Math.min(640,to),Qe=Math.max(200,ar-Xt);be.style.height=`${Qe}px`}}finally{if(qr(),Oo(),L&&E){let Ct=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((bt=(Ke=o.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?bt:640),Xt=(We=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?We:!1,to=(fe=(Re=o.launcher)==null?void 0:Re.mobileFullscreen)!=null?fe:!0,ar=ur(o)&&to&&Ct,Qe=Xt||to&&Ct&&E||ar;if(Qe&&!fr){let Wt=e.getRootNode(),pr=Wt instanceof ShadowRoot?Wt.host:e.closest(".persona-host");pr&&!or&&(or=gp(pr,(Vt=(zt=o.launcher)==null?void 0:zt.zIndex)!=null?Vt:Rr)),fr=hp(e.ownerDocument)}else Qe||(or==null||or(),or=null,fr==null||fr(),fr=null)}}};us();let Zp=(rf=e.ownerDocument.defaultView)!=null?rf:window;if(Zp.addEventListener("resize",us),pt.push(()=>Zp.removeEventListener("resize",us)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{qr()});l.observe(He),pt.push(()=>l.disconnect())}eo=Te.scrollTop;let eu=sn(Te),Jx=()=>{let l=Te.getRootNode(),f=typeof l.getSelection=="function"?l.getSelection():null;return f!=null?f:Te.ownerDocument.getSelection()},Ol=()=>vh(Jx(),Te),tu=()=>{let l=Te.scrollTop,f=sn(Te),h=f<eu;if(eu=f,et()!=="follow"){eo=l,zr();return}let{action:v,nextLastScrollTop:I}=sl({following:Zr.isFollowing(),currentScrollTop:l,lastScrollTop:eo,nearBottom:da(Te,va),userScrollThreshold:Qs,isAutoScrolling:vo||Vn||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(eo=I,v==="resume"){Ol()||Fo();return}v==="pause"&&Sa()};if(Te.addEventListener("scroll",tu,{passive:!0}),pt.push(()=>Te.removeEventListener("scroll",tu)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{ri()});l.observe(Xe),l.observe(Te),pt.push(()=>l.disconnect())}let ru=()=>{et()==="follow"&&Zr.isFollowing()&&Ol()&&Sa()},ou=Te.ownerDocument;ou.addEventListener("selectionchange",ru),pt.push(()=>{ou.removeEventListener("selectionchange",ru)});let nu=l=>{if(et()!=="follow")return;let f=il({following:Zr.isFollowing(),deltaY:l.deltaY,nearBottom:da(Te,va),resumeWhenNearBottom:!0});f==="pause"?Sa():f==="resume"&&!Ol()&&Fo()};Te.addEventListener("wheel",nu,{passive:!0}),pt.push(()=>Te.removeEventListener("wheel",nu)),ct.addEventListener("click",()=>{zn(),Te.scrollTop=Te.scrollHeight,eo=Te.scrollTop,Fo(),No(!0),zr()}),pt.push(()=>ct.remove()),pt.push(()=>{rs(),zn()});let au=()=>{je&&(Ro&&(je.removeEventListener("click",Ro),Ro=null),R()?(je.style.display="",Ro=()=>{he(!1,"user")},je.addEventListener("click",Ro)):je.style.display="none")};au(),(()=>{let{clearChatButton:l}=J;l&&l.addEventListener("click",()=>{_.clearMessages(),Ho.clear(),Fo(),Ln(J.composerOverlay);try{localStorage.removeItem(Ja),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ja}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ja)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)}c={},T.syncFromMetadata(),ge==null||ge.clear(),ue==null||ue.reset(),j==null||j.update()})})(),Ft&&Ft.addEventListener("submit",Oe),ke==null||ke.addEventListener("keydown",mr),ke==null||ke.addEventListener("input",Bt),ke==null||ke.addEventListener("paste",Ar);let su=(of=e.ownerDocument)!=null?of:document;su.addEventListener("keydown",kr,!0);let iu="persona-attachment-drop-active",fs=0,_l=()=>{fs=0,ce.classList.remove(iu)},Ta=()=>{var l;return((l=o.attachments)==null?void 0:l.enabled)===!0&&vt!==null},lu=l=>{!Wl(l.dataTransfer)||!Ta()||(fs++,fs===1&&ce.classList.add(iu))},du=l=>{!Wl(l.dataTransfer)||!Ta()||(fs--,fs<=0&&_l())},cu=l=>{!Wl(l.dataTransfer)||!Ta()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},pu=l=>{var h;if(!Wl(l.dataTransfer)||!Ta())return;l.preventDefault(),l.stopPropagation(),_l();let f=Array.from((h=l.dataTransfer.files)!=null?h:[]);f.length!==0&&vt.handleFiles(f)},An=!0;ce.addEventListener("dragenter",lu,An),ce.addEventListener("dragleave",du,An),e.addEventListener("dragover",cu,An),e.addEventListener("drop",pu,An);let fi=e.ownerDocument,uu=l=>{Ta()&&l.preventDefault()},fu=l=>{Ta()&&l.preventDefault()};fi.addEventListener("dragover",uu),fi.addEventListener("drop",fu),pt.push(()=>{Ft&&Ft.removeEventListener("submit",Oe),ke==null||ke.removeEventListener("keydown",mr),ke==null||ke.removeEventListener("input",Bt),ke==null||ke.removeEventListener("paste",Ar),su.removeEventListener("keydown",kr,!0)}),pt.push(()=>{ce.removeEventListener("dragenter",lu,An),ce.removeEventListener("dragleave",du,An),e.removeEventListener("dragover",cu,An),e.removeEventListener("drop",pu,An),fi.removeEventListener("dragover",uu),fi.removeEventListener("drop",fu),_l()}),pt.push(()=>{_.cancel()}),nr?pt.push(()=>{nr==null||nr.destroy()}):gr&&pt.push(()=>{gr==null||gr.remove()});let cr={update(l){var Lr,Dr,_o,wr,Fr,Nr,Qn,ms,pf,uf,ff,mf,gf,hf,xf,yf,bf,vf,Cf,wf,Sf,Af,Mf,Tf,Ef,kf,Lf,Pf,If,Rf,Wf,Hf,Bf,Df,Ff,Nf,Of,_f,Uf,qf,Vf,$f,zf,jf,Gf,Kf,Xf,Qf,Jf,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,Im,Rm,Wm,Hm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,Vm,$m,zm,jm,Gm,Km,Xm,Qm,Jm,Ym,Zm,eg,tg,rg,og,ng,ag,sg,ig,lg,dg;let f=o.toolCall,h=o.messageActions,v=(Lr=o.layout)==null?void 0:Lr.messages,I=o.colorScheme,F=o.loadingIndicator,$=o.iterationDisplay,O=(Dr=o.features)==null?void 0:Dr.showReasoning,D=(_o=o.features)==null?void 0:_o.showToolCalls,oe=(wr=o.features)==null?void 0:wr.toolCallDisplay,ne=(Fr=o.features)==null?void 0:Fr.reasoningDisplay;o={...o,...l},xe(),Wn(e,o),Al(e,o),Ml(e,o),Yr(),o.colorScheme!==I&&Za();let X=$s.getForInstance(o.plugins);n.length=0,n.push(...X),E=(Qn=(Nr=o.launcher)==null?void 0:Nr.enabled)!=null?Qn:!0,w=(pf=(ms=o.launcher)==null?void 0:ms.autoExpand)!=null?pf:!1,Ge=(ff=(uf=o.features)==null?void 0:uf.showReasoning)!=null?ff:!0,Ce=(gf=(mf=o.features)==null?void 0:mf.showToolCalls)!=null?gf:!0,qe=(xf=(hf=o.features)==null?void 0:hf.scrollToBottom)!=null?xf:{};let ye=et();Ee=(bf=(yf=o.features)==null?void 0:yf.scrollBehavior)!=null?bf:{},ye!==et()&&(zn(),Fo()),Eo(),zr();let Fe=Be;if(Be=(Cf=(vf=o.features)==null?void 0:vf.showEventStreamToggle)!=null?Cf:!1,Be&&!Fe){if(ge||(Q=new qs(le),ge=new Us(ie,Q),ue=ue!=null?ue:new Vs,Q.open().then(()=>ge==null?void 0:ge.restore()).catch(()=>{}),_.setSSEEventCallback((ee,kt)=>{var Qt;(Qt=o.onSSEEvent)==null||Qt.call(o,ee,kt),ue==null||ue.processEvent(ee,kt),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(kt)})})),!yt&&we){let ee=(Sf=(wf=o.features)==null?void 0:wf.eventStream)==null?void 0:Sf.classNames,kt="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:"");yt=A("button",kt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Ur.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let Qt=ve("activity","18px","currentColor",1.5);Qt&&yt.appendChild(Qt);let it=J.clearChatButtonWrapper,Ht=J.closeButtonWrapper,xr=it||Ht;xr&&xr.parentNode===we?we.insertBefore(yt,xr):we.appendChild(yt),yt.addEventListener("click",()=>{de?xo():$o()})}}else!Be&&Fe&&(xo(),yt&&(yt.remove(),yt=null),ge==null||ge.clear(),Q==null||Q.destroy(),ge=null,Q=null,ue==null||ue.reset(),ue=null);if(((Af=o.launcher)==null?void 0:Af.enabled)===!1&&nr&&(nr.destroy(),nr=null),((Mf=o.launcher)==null?void 0:Mf.enabled)===!1&&gr&&(gr.remove(),gr=null),((Tf=o.launcher)==null?void 0:Tf.enabled)!==!1&&!nr&&!gr){let{instance:ee,element:kt}=Cp({config:o,plugins:n,onToggle:Yp});nr=ee,ee||(gr=kt),e.appendChild(kt)}nr&&nr.update(o),V&&((Ef=o.launcher)==null?void 0:Ef.title)!==void 0&&(V.textContent=o.launcher.title),Me&&((kf=o.launcher)==null?void 0:kf.subtitle)!==void 0&&(Me.textContent=o.launcher.subtitle);let Se=(Lf=o.layout)==null?void 0:Lf.header;if((Se==null?void 0:Se.layout)!==b&&we){let ee=Se?$a(o,Se,{showClose:R(),onClose:()=>he(!1,"user")}):ln({config:o,showClose:R(),onClose:()=>he(!1,"user")});xt.replaceHeader(ee),we=xt.header.element,Nt=xt.header.iconHolder,V=xt.header.headerTitle,Me=xt.header.headerSubtitle,je=xt.header.closeButton,b=Se==null?void 0:Se.layout}else if(Se&&(Nt&&(Nt.style.display=Se.showIcon===!1?"none":""),V&&(V.style.display=Se.showTitle===!1?"none":""),Me&&(Me.style.display=Se.showSubtitle===!1?"none":""),je&&(je.style.display=Se.showCloseButton===!1?"none":""),J.clearChatButtonWrapper)){let ee=Se.showClearChat;if(ee!==void 0){J.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:kt}=J;kt&&!kt.classList.contains("persona-absolute")&&(ee?kt.classList.remove("persona-ml-auto"):kt.classList.add("persona-ml-auto"))}}let $e=((Pf=o.layout)==null?void 0:Pf.showHeader)!==!1;we&&(we.style.display=$e?"":"none");let mt=((If=o.layout)==null?void 0:If.showFooter)!==!1;He&&(He.style.display=mt?"":"none"),qr(),zr(),E!==S?E?he(w,"auto"):(L=!0,Oo()):w!==y&&he(w,"auto"),y=w,S=E,us(),au();let Le=JSON.stringify(l.toolCall)!==JSON.stringify(f),ze=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((Rf=o.layout)==null?void 0:Rf.messages)!==JSON.stringify(v),bt=((Wf=o.loadingIndicator)==null?void 0:Wf.render)!==(F==null?void 0:F.render)||((Hf=o.loadingIndicator)==null?void 0:Hf.renderIdle)!==(F==null?void 0:F.renderIdle)||((Bf=o.loadingIndicator)==null?void 0:Bf.showBubble)!==(F==null?void 0:F.showBubble),B=o.iterationDisplay!==$,We=((Ff=(Df=o.features)==null?void 0:Df.showReasoning)!=null?Ff:!0)!==(O!=null?O:!0)||((Of=(Nf=o.features)==null?void 0:Nf.showToolCalls)!=null?Of:!0)!==(D!=null?D:!0)||JSON.stringify((_f=o.features)==null?void 0:_f.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify((Uf=o.features)==null?void 0:Uf.reasoningDisplay)!==JSON.stringify(ne);(Le||ze||Ke||bt||B||We)&&_&&(xa++,bn(Xe,_.getMessages(),me));let fe=(qf=o.launcher)!=null?qf:{},zt=(Vf=fe.headerIconHidden)!=null?Vf:!1,Vt=(zf=($f=o.layout)==null?void 0:$f.header)==null?void 0:zf.showIcon,Jt=zt||Vt===!1,Ct=fe.headerIconName,Xt=(jf=fe.headerIconSize)!=null?jf:"48px";if(Nt){let ee=ce.querySelector(".persona-border-b-persona-divider"),kt=ee==null?void 0:ee.querySelector(".persona-flex-col");if(Jt)Nt.style.display="none",ee&&kt&&!ee.contains(kt)&&ee.insertBefore(kt,ee.firstChild);else{if(Nt.style.display="",Nt.style.height=Xt,Nt.style.width=Xt,ee&&kt&&(ee.contains(Nt)?Nt.nextSibling!==kt&&(Nt.remove(),ee.insertBefore(Nt,kt)):ee.insertBefore(Nt,kt)),Ct){let it=parseFloat(Xt)||24,Ht=ve(Ct,it*.6,"currentColor",1);Ht?Nt.replaceChildren(Ht):Nt.textContent=(Gf=fe.agentIconText)!=null?Gf:"\u{1F4AC}"}else if(fe.iconUrl){let it=Nt.querySelector("img");if(it)it.src=fe.iconUrl,it.style.height=Xt,it.style.width=Xt;else{let Ht=document.createElement("img");Ht.src=fe.iconUrl,Ht.alt="",Ht.className="persona-rounded-xl persona-object-cover",Ht.style.height=Xt,Ht.style.width=Xt,Nt.replaceChildren(Ht)}}else{let it=Nt.querySelector("svg"),Ht=Nt.querySelector("img");(it||Ht)&&Nt.replaceChildren(),Nt.textContent=(Kf=fe.agentIconText)!=null?Kf:"\u{1F4AC}"}let Qt=Nt.querySelector("img");Qt&&(Qt.style.height=Xt,Qt.style.width=Xt)}}let to=(Qf=(Xf=o.layout)==null?void 0:Xf.header)==null?void 0:Qf.showTitle,ar=(Yf=(Jf=o.layout)==null?void 0:Jf.header)==null?void 0:Yf.showSubtitle;if(V&&(V.style.display=to===!1?"none":""),Me&&(Me.style.display=ar===!1?"none":""),je){((em=(Zf=o.layout)==null?void 0:Zf.header)==null?void 0:em.showCloseButton)===!1?je.style.display="none":je.style.display="";let kt=(tm=fe.closeButtonSize)!=null?tm:"32px",Qt=(rm=fe.closeButtonPlacement)!=null?rm:"inline";je.style.height=kt,je.style.width=kt;let{closeButtonWrapper:it}=J,Ht=Qt==="top-right",xr=it==null?void 0:it.classList.contains("persona-absolute");if(it&&Ht!==xr)if(it.remove(),Ht)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(it);else{let ut=(nm=(om=fe.clearChat)==null?void 0:om.placement)!=null?nm:"inline",yr=(sm=(am=fe.clearChat)==null?void 0:am.enabled)!=null?sm:!0;it.className=yr&&ut==="inline"?"":"persona-ml-auto";let jr=ce.querySelector(".persona-border-b-persona-divider");jr&&jr.appendChild(it)}if(je.style.color=fe.closeButtonColor||Ur.actionIconColor,fe.closeButtonBackgroundColor?(je.style.backgroundColor=fe.closeButtonBackgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let ut=fe.closeButtonBorderWidth||"0px",yr=fe.closeButtonBorderColor||"transparent";je.style.border=`${ut} solid ${yr}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");fe.closeButtonBorderRadius?(je.style.borderRadius=fe.closeButtonBorderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(je.style.paddingLeft=fe.closeButtonPaddingX,je.style.paddingRight=fe.closeButtonPaddingX):(je.style.paddingLeft="",je.style.paddingRight=""),fe.closeButtonPaddingY?(je.style.paddingTop=fe.closeButtonPaddingY,je.style.paddingBottom=fe.closeButtonPaddingY):(je.style.paddingTop="",je.style.paddingBottom="");let Pr=(im=fe.closeButtonIconName)!=null?im:"x",wo=(lm=fe.closeButtonIconText)!=null?lm:"\xD7";je.innerHTML="";let Or=ve(Pr,"28px","currentColor",1);Or?je.appendChild(Or):je.textContent=wo;let rr=(dm=fe.closeButtonTooltipText)!=null?dm:"Close chat",oo=(cm=fe.closeButtonShowTooltip)!=null?cm:!0;if(je.setAttribute("aria-label",rr),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),oo&&rr)){let ut=null,yr=()=>{if(ut||!je)return;let Jn=je.ownerDocument,gs=Jn.body;if(!gs)return;ut=qo(Jn,"div","persona-clear-chat-tooltip"),ut.textContent=rr;let hs=qo(Jn,"div");hs.className="persona-clear-chat-tooltip-arrow",ut.appendChild(hs);let Yn=je.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(Hn),ut.style.left=`${Yn.left+Yn.width/2}px`,ut.style.top=`${Yn.top-8}px`,ut.style.transform="translate(-50%, -100%)",gs.appendChild(ut)},jr=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};it.addEventListener("mouseenter",yr),it.addEventListener("mouseleave",jr),je.addEventListener("focus",yr),je.addEventListener("blur",jr),it._cleanupTooltip=()=>{jr(),it&&(it.removeEventListener("mouseenter",yr),it.removeEventListener("mouseleave",jr)),je&&(je.removeEventListener("focus",yr),je.removeEventListener("blur",jr))}}}let{clearChatButton:Qe,clearChatButtonWrapper:Wt}=J;if(Qe){let ee=(pm=fe.clearChat)!=null?pm:{},kt=(um=ee.enabled)!=null?um:!0,Qt=(mm=(fm=o.layout)==null?void 0:fm.header)==null?void 0:mm.showClearChat,it=Qt!==void 0?Qt:kt,Ht=(gm=ee.placement)!=null?gm:"inline";if(Wt){Wt.style.display=it?"":"none";let{closeButtonWrapper:xr}=J;!W()&&xr&&!xr.classList.contains("persona-absolute")&&(it?xr.classList.remove("persona-ml-auto"):xr.classList.add("persona-ml-auto"));let Pr=Ht==="top-right",wo=Wt.classList.contains("persona-absolute");if(!W()&&Pr!==wo&&it){if(Wt.remove(),Pr)Wt.className="persona-absolute persona-top-4 persona-z-50",Wt.style.right="48px",ce.style.position="relative",ce.appendChild(Wt);else{Wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wt.style.right="";let rr=ce.querySelector(".persona-border-b-persona-divider"),oo=J.closeButtonWrapper;rr&&oo&&oo.parentElement===rr?rr.insertBefore(Wt,oo):rr&&rr.appendChild(Wt)}let Or=J.closeButtonWrapper;Or&&!Or.classList.contains("persona-absolute")&&(Pr?Or.classList.add("persona-ml-auto"):Or.classList.remove("persona-ml-auto"))}}if(it){if(!W()){let ut=(hm=ee.size)!=null?hm:"32px";Qe.style.height=ut,Qe.style.width=ut}let xr=(xm=ee.iconName)!=null?xm:"refresh-cw",Pr=(ym=ee.iconColor)!=null?ym:"";Qe.style.color=Pr||Ur.actionIconColor,Qe.innerHTML="";let wo=W()?"14px":"20px",Or=ve(xr,wo,"currentColor",2);if(Or&&Qe.appendChild(Or),ee.backgroundColor?(Qe.style.backgroundColor=ee.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let ut=ee.borderWidth||"0px",yr=ee.borderColor||"transparent";Qe.style.border=`${ut} solid ${yr}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");ee.borderRadius?(Qe.style.borderRadius=ee.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),ee.paddingX?(Qe.style.paddingLeft=ee.paddingX,Qe.style.paddingRight=ee.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),ee.paddingY?(Qe.style.paddingTop=ee.paddingY,Qe.style.paddingBottom=ee.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let rr=(bm=ee.tooltipText)!=null?bm:"Clear chat",oo=(vm=ee.showTooltip)!=null?vm:!0;if(Qe.setAttribute("aria-label",rr),Wt&&(Wt._cleanupTooltip&&(Wt._cleanupTooltip(),delete Wt._cleanupTooltip),oo&&rr)){let ut=null,yr=()=>{if(ut||!Qe)return;let Jn=Qe.ownerDocument,gs=Jn.body;if(!gs)return;ut=qo(Jn,"div","persona-clear-chat-tooltip"),ut.textContent=rr;let hs=qo(Jn,"div");hs.className="persona-clear-chat-tooltip-arrow",ut.appendChild(hs);let Yn=Qe.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(Hn),ut.style.left=`${Yn.left+Yn.width/2}px`,ut.style.top=`${Yn.top-8}px`,ut.style.transform="translate(-50%, -100%)",gs.appendChild(ut)},jr=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};Wt.addEventListener("mouseenter",yr),Wt.addEventListener("mouseleave",jr),Qe.addEventListener("focus",yr),Qe.addEventListener("blur",jr),Wt._cleanupTooltip=()=>{jr(),Wt&&(Wt.removeEventListener("mouseenter",yr),Wt.removeEventListener("mouseleave",jr)),Qe&&(Qe.removeEventListener("focus",yr),Qe.removeEventListener("blur",jr))}}}}let pr=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zs],mo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ma.message,ma.messageAndClick];T=js({parsers:pr,handlers:mo,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),me=ix(o,T,Y),_.updateConfig(o),bn(Xe,_.getMessages(),me),ha(),H(),P(_.isStreaming());let ro=((Cm=o.voiceRecognition)==null?void 0:Cm.enabled)===!0,jn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Gn=((Sm=(wm=o.voiceRecognition)==null?void 0:wm.provider)==null?void 0:Sm.type)==="runtype";if(ro&&(jn||Gn))if(!z||!St){let ee=jx(o.voiceRecognition,o.sendButton);ee&&(z=ee.micButton,St=ee.micButtonWrapper,ot.insertBefore(St,rt),z.addEventListener("click",ui),z.disabled=_.isStreaming())}else{let ee=(Am=o.voiceRecognition)!=null?Am:{},kt=(Mm=o.sendButton)!=null?Mm:{},Qt=(Tm=ee.iconName)!=null?Tm:"mic",it=(Em=kt.size)!=null?Em:"40px",Ht=(km=ee.iconSize)!=null?km:it,xr=parseFloat(Ht)||24;z.style.width=Ht,z.style.height=Ht,z.style.minWidth=Ht,z.style.minHeight=Ht;let Pr=(Pm=(Lm=ee.iconColor)!=null?Lm:kt.textColor)!=null?Pm:"currentColor";z.innerHTML="";let wo=ve(Qt,xr,Pr,2);wo?z.appendChild(wo):z.textContent="\u{1F3A4}";let Or=(Im=ee.backgroundColor)!=null?Im:kt.backgroundColor;Or?z.style.backgroundColor=Or:z.style.backgroundColor="",Pr?z.style.color=Pr: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 rr=St==null?void 0:St.querySelector(".persona-send-button-tooltip"),oo=(Rm=ee.tooltipText)!=null?Rm:"Start voice recognition";if(((Wm=ee.showTooltip)!=null?Wm:!1)&&oo)if(rr)rr.textContent=oo,rr.style.display="";else{let yr=document.createElement("div");yr.className="persona-send-button-tooltip",yr.textContent=oo,St==null||St.insertBefore(yr,z)}else rr&&(rr.style.display="none");St.style.display="",z.disabled=_.isStreaming()}else z&&St&&(St.style.display="none",((Bm=(Hm=o.voiceRecognition)==null?void 0:Hm.provider)==null?void 0:Bm.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():dr&&Sn());if(((Dm=o.attachments)==null?void 0:Dm.enabled)===!0)if(!pe||!se){let ee=(Fm=o.attachments)!=null?Fm:{},Qt=(Om=((Nm=o.sendButton)!=null?Nm:{}).size)!=null?Om:"40px";dt||(dt=A("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),dt.style.display="none",Ft.insertBefore(dt,ke)),Ae||(Ae=document.createElement("input"),Ae.type="file",Ae.accept=((_m=ee.allowedTypes)!=null?_m:an).join(","),Ae.multiple=((Um=ee.maxFiles)!=null?Um:4)>1,Ae.style.display="none",Ae.setAttribute("aria-label","Attach files"),Ft.insertBefore(Ae,ke)),pe=A("div","persona-send-button-wrapper"),se=A("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),se.type="button",se.setAttribute("aria-label",(qm=ee.buttonTooltipText)!=null?qm:"Attach file");let it=(Vm=ee.buttonIconName)!=null?Vm:"paperclip",Ht=Qt,xr=parseFloat(Ht)||40,Pr=Math.round(xr*.6);se.style.width=Ht,se.style.height=Ht,se.style.minWidth=Ht,se.style.minHeight=Ht,se.style.fontSize="18px",se.style.lineHeight="1",se.style.backgroundColor="transparent",se.style.color="var(--persona-primary, #111827)",se.style.border="none",se.style.borderRadius="6px",se.style.transition="background-color 0.15s ease",se.addEventListener("mouseenter",()=>{se.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),se.addEventListener("mouseleave",()=>{se.style.backgroundColor="transparent"});let wo=ve(it,Pr,"currentColor",1.5);wo?se.appendChild(wo):se.textContent="\u{1F4CE}",se.addEventListener("click",oo=>{oo.preventDefault(),Ae==null||Ae.click()}),pe.appendChild(se);let Or=($m=ee.buttonTooltipText)!=null?$m:"Attach file",rr=A("div","persona-send-button-tooltip");rr.textContent=Or,pe.appendChild(rr),lt.append(pe),!vt&&Ae&&dt&&(vt=la.fromConfig(ee),vt.setPreviewsContainer(dt),Ae.addEventListener("change",async()=>{vt&&(Ae!=null&&Ae.files)&&(await vt.handleFileSelect(Ae.files),Ae.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(lx(ee.dropOverlay))}else{pe.style.display="";let ee=(zm=o.attachments)!=null?zm:{};Ae&&(Ae.accept=((jm=ee.allowedTypes)!=null?jm:an).join(","),Ae.multiple=((Gm=ee.maxFiles)!=null?Gm:4)>1),vt&&vt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else pe&&(pe.style.display="none"),vt&&vt.clearAttachments(),(Km=ce.querySelector(".persona-attachment-drop-overlay"))==null||Km.remove();let Yt=(Xm=o.sendButton)!=null?Xm:{},Kn=(Qm=Yt.useIcon)!=null?Qm:!1,Mn=(Jm=Yt.iconText)!=null?Jm:"\u2191",Tn=Yt.iconName,en=(Ym=Yt.tooltipText)!=null?Ym:"Send message",Xn=(Zm=Yt.showTooltip)!=null?Zm:!1,Co=(eg=Yt.size)!=null?eg:"40px",Ze=Yt.backgroundColor,hr=Yt.textColor;if(Kn){if(Ve.style.width=Co,Ve.style.height=Co,Ve.style.minWidth=Co,Ve.style.minHeight=Co,Ve.style.fontSize="18px",Ve.style.lineHeight="1",Ve.innerHTML="",hr?Ve.style.color=hr:Ve.style.color="var(--persona-button-primary-fg, #ffffff)",Tn){let ee=parseFloat(Co)||24,kt=(hr==null?void 0:hr.trim())||"currentColor",Qt=ve(Tn,ee,kt,2);Qt?Ve.appendChild(Qt):Ve.textContent=Mn}else Ve.textContent=Mn;Ve.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ze?(Ve.style.backgroundColor=Ze,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=(rg=(tg=o.copy)==null?void 0:tg.sendButtonLabel)!=null?rg:"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Ze?(Ve.style.backgroundColor=Ze,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),hr?Ve.style.color=hr:Ve.classList.add("persona-text-white");Yt.borderWidth?(Ve.style.borderWidth=Yt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),Yt.borderColor?Ve.style.borderColor=Yt.borderColor:Ve.style.borderColor="",Yt.paddingX?(Ve.style.paddingLeft=Yt.paddingX,Ve.style.paddingRight=Yt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),Yt.paddingY?(Ve.style.paddingTop=Yt.paddingY,Ve.style.paddingBottom=Yt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Gt=rt==null?void 0:rt.querySelector(".persona-send-button-tooltip");if(Xn&&en)if(Gt)Gt.textContent=en,Gt.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=en,rt==null||rt.insertBefore(ee,Ve)}else Gt&&(Gt.style.display="none");let jt=(ig=(og=o.layout)==null?void 0:og.contentMaxWidth)!=null?ig:W()?(sg=(ag=(ng=o.launcher)==null?void 0:ng.composerBar)==null?void 0:ag.contentMaxWidth)!=null?sg:"720px":void 0;jt?(Xe.style.maxWidth=jt,Xe.style.marginLeft="auto",Xe.style.marginRight="auto",Xe.style.width="100%",Ft&&(Ft.style.maxWidth=jt,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),Kt&&(Kt.style.maxWidth=jt,Kt.style.marginLeft="auto",Kt.style.marginRight="auto")):(Xe.style.maxWidth="",Xe.style.marginLeft="",Xe.style.marginRight="",Xe.style.width="",Ft&&(Ft.style.maxWidth="",Ft.style.marginLeft="",Ft.style.marginRight=""),Kt&&(Kt.style.maxWidth="",Kt.style.marginLeft="",Kt.style.marginRight=""));let gt=(lg=o.statusIndicator)!=null?lg:{},Zt=(dg=gt.visible)!=null?dg:!0;if(vr.style.display=Zt?"":"none",_){let ee=_.getStatus();Pt(vr,(Qt=>{var it,Ht,xr,Pr;return Qt==="idle"?(it=gt.idleText)!=null?it:Ir.idle:Qt==="connecting"?(Ht=gt.connectingText)!=null?Ht:Ir.connecting:Qt==="connected"?(xr=gt.connectedText)!=null?xr:Ir.connected:Qt==="error"?(Pr=gt.errorText)!=null?Pr:Ir.error:Ir[Qt]})(ee),gt,ee)}vr.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Mt=gt.align==="left"?"persona-text-left":gt.align==="center"?"persona-text-center":"persona-text-right";vr.classList.add(Mt)},open(){R()&&he(!0,"api")},close(){R()&&he(!1,"api")},toggle(){R()&&he(!L,"api")},clearChat(){Hr=!1,_.clearMessages(),Ho.clear(),Fo();try{localStorage.removeItem(Ja),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ja}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ja)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)}c={},T.syncFromMetadata(),ge==null||ge.clear(),ue==null||ue.reset(),j==null||j.update()},setMessage(l){return!ke||_.isStreaming()?!1:(!L&&R()&&he(!0,"system"),ke.value=l,ke.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let f=(l==null?void 0:l.trim())||ke.value.trim();return f?(!L&&R()&&he(!0,"system"),ke.value="",ke.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()||(!L&&R()&&he(!0,"system"),ht.manuallyDeactivated=!1,$r(),_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),uo("user"),_.isVoiceActive()&&Ma()})),!0):dr?!0:Jp()?(!L&&R()&&he(!0,"system"),ht.manuallyDeactivated=!1,$r(),ci("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(()=>{ht.active=!1,ht.manuallyDeactivated=!0,$r(),uo("user"),Zo()}),!0):!1:dr?(ht.manuallyDeactivated=!0,$r(),Sn("user"),!0):!1},injectMessage(l){return!L&&R()&&he(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!L&&R()&&he(!0,"system");let f=_.injectAssistantMessage(l);return N&&(N=!1,q&&(clearTimeout(q),q=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),f},injectUserMessage(l){return!L&&R()&&he(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!L&&R()&&he(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!L&&R()&&he(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!L&&R()&&he(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!L&&R()&&he(!0,"system"),_.injectTestEvent(l)},async connectStream(l,f){return _.connectStream(l,f)},__pushEventStreamEvent(l){ge&&(ue==null||ue.processEvent(l.type,l.payload),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Be||!ge||$o()},hideEventStream(){de&&xo()},isEventStreamVisible(){return de},showArtifacts(){ho(o)&&(Hr=!1,Yr(),At==null||At.setMobileOpen(!0))},hideArtifacts(){ho(o)&&(Hr=!0,Yr())},upsertArtifact(l){return ho(o)?(Hr=!1,_.upsertArtifact(l)):null},selectArtifact(l){ho(o)&&_.selectArtifact(l)},clearArtifacts(){ho(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 E&&!L&&!W()||!ke?!1:(ke.focus(),!0)},async resolveApproval(l,f,h){let I=_.getMessages().find(F=>{var $;return F.variant==="approval"&&(($=F.approval)==null?void 0:$.id)===l});if(!(I!=null&&I.approval))throw new Error(`Approval not found: ${l}`);if(I.approval.toolType==="webmcp"){_.resolveWebMcpApproval(I.id,f);return}return _.resolveApproval(I.approval,f,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){m(l)},on(l,f){return a.on(l,f)},off(l,f){a.off(l,f)},isOpen(){return R()&&L},isVoiceActive(){return ht.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:R()&&L,launcherEnabled:E,voiceActive:ht.active,streaming:_.isStreaming()}},showCSATFeedback(l){!L&&R()&&he(!0,"system");let f=Xe.querySelector(".persona-feedback-container");f&&f.remove();let h=Il({onSubmit:async(v,I)=>{var F;_.isClientTokenMode()&&await _.submitCSATFeedback(v,I),(F=l==null?void 0:l.onSubmit)==null||F.call(l,v,I)},onDismiss:l==null?void 0:l.onDismiss,...l});Xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!L&&R()&&he(!0,"system");let f=Xe.querySelector(".persona-feedback-container");f&&f.remove();let h=Rl({onSubmit:async(v,I)=>{var F;_.isClientTokenMode()&&await _.submitNPSFeedback(v,I),(F=l==null?void 0:l.onSubmit)==null||F.call(l,v,I)},onDismiss:l==null?void 0:l.onDismiss,...l});Xe.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(){G!=null&&(clearInterval(G),G=null),pt.forEach(l=>l()),Ue.remove(),Je==null||Je.remove(),nr==null||nr.destroy(),gr==null||gr.remove(),Ro&&je.removeEventListener("click",Ro)}};if((((nf=r==null?void 0:r.debugTools)!=null?nf:!1)||!!o.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,f={controller:cr,getMessages:cr.getMessages,getStatus:cr.getStatus,getMetadata:cr.getPersistentMetadata,updateMetadata:cr.updatePersistentMetadata,clearHistory:()=>cr.clearChat(),setVoiceActive:h=>h?cr.startVoiceRecognition():cr.stopVoiceRecognition()};window.AgentWidgetBrowser=f,pt.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 D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&cr.focusInput()};if(window.addEventListener("persona:focusInput",f),pt.push(()=>{window.removeEventListener("persona:focusInput",f)}),Be){let O=oe=>{let ne=oe.detail;(!(ne!=null&&ne.instanceId)||ne.instanceId===l)&&cr.showEventStream()},D=oe=>{let ne=oe.detail;(!(ne!=null&&ne.instanceId)||ne.instanceId===l)&&cr.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",D),pt.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",D)})}let h=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&cr.showArtifacts()},v=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&cr.hideArtifacts()},I=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&cr.upsertArtifact(D.artifact)},F=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&cr.selectArtifact(D.id)},$=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&cr.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",I),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",$),pt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",I),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",$)})}let fo=Dv(o.persistState);if(fo&&R()){let l=Fv(fo.storage),f=`${fo.keyPrefix}widget-open`,h=`${fo.keyPrefix}widget-voice`,v=`${fo.keyPrefix}widget-voice-mode`;if(l){let I=((af=fo.persist)==null?void 0:af.openState)&&l.getItem(f)==="true",F=((sf=fo.persist)==null?void 0:sf.voiceState)&&l.getItem(h)==="true",$=((lf=fo.persist)==null?void 0:lf.voiceState)&&l.getItem(v)==="true";if(I&&setTimeout(()=>{cr.open(),setTimeout(()=>{var O;if(F||$)cr.startVoiceRecognition();else if((O=fo.persist)!=null&&O.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(df=fo.persist)!=null&&df.openState&&(a.on("widget:opened",()=>{l.setItem(f,"true")}),a.on("widget:closed",()=>{l.setItem(f,"false")})),(cf=fo.persist)!=null&&cf.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")})),fo.clearOnChatClear){let O=()=>{l.removeItem(f),l.removeItem(h),l.removeItem(v)},D=()=>O();window.addEventListener("persona:clear-chat",D),pt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return u&&R()&&setTimeout(()=>{cr.open()},0),Yo(),Xs||gi().then(()=>{_&&(xa++,Ho.clear(),bn(Xe,_.getMessages(),me))}).catch(()=>{}),cr};var Nv=(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},Ov=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},_v=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Uv=(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.")},dx=(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"},Np=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=""},cx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Np(e)},Bp=e=>{e.style.transition=""},Dp=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=""},Fp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Bl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},qv=(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))},Vv=(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)},px=(e,t,r,o,n,a,s)=>{var x,C,T,E,w,k;let i=ao(a),c=i.reveal==="push";qv(e,t,r,o,c),Vv(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 d=e.ownerDocument.defaultView,u=(C=(x=a==null?void 0:a.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,g=(E=(T=a==null?void 0:a.launcher)==null?void 0:T.mobileBreakpoint)!=null?E:640,p=d!=null?d.innerWidth<=g:!1;if(u&&p&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Dp(t),Bp(o),cx(o),Fp(r),Bl(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((k=(w=a==null?void 0:a.launcher)==null?void 0:w.zIndex)!=null?k:Rr),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"),cx(o),Ov(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",Dp(t),Bp(o),Fp(r),Bl(n,o);let y=i.animate?"transform 180ms ease":"none",S=i.side==="right"?"translateX(100%)":"translateX(-100%)",b=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=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",Bp(o),Np(o),Bl(n,o);let y=Nv(i.width,e.clientWidth),S=Math.max(0,e.clientWidth),b=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=b,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="",Dp(t),Np(o),Fp(r),Bl(n,o);let y=i.reveal==="emerge";y?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=s?i.width:"0px",b=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",_v(o,i.maxHeight),o.style.overflow=y||M?"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")}},$v=(e,t)=>{let r=e.ownerDocument.createElement("div");return dx(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){dx(r,o)},destroy(){r.remove()}}},zv=(e,t)=>{var k,y,S,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"),c=r.createElement("div"),d=r.createElement("aside"),u=r.createElement("div"),g=(y=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)==null||y?(b=(S=t==null?void 0:t.launcher)==null?void 0:S.autoExpand)!=null?b:!1:!0;i.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",d.appendChild(u),o.insertBefore(s,e),c.appendChild(e);let p=null,m=()=>{p==null||p.disconnect(),p=null},x=()=>{m(),ao(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(p=new ResizeObserver(()=>{px(s,i,c,d,u,t,g)}),p.observe(s))},C=!1,T=()=>{px(s,i,c,d,u,t,g),x(),g&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,Uv(s,ao(t)))},E=s.ownerDocument.defaultView,w=()=>{T()};return E==null||E.addEventListener("resize",w),ao(t).reveal==="push"?(i.appendChild(c),i.appendChild(d),s.appendChild(i)):(s.appendChild(c),s.appendChild(d)),T(),{mode:"docked",host:u,shell:s,syncWidgetState(M){let W=M.launcherEnabled?M.open:!0;g!==W&&(g=W,T())},updateConfig(M){var W,R;t=M,((R=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)!=null?R:!0)===!1&&(g=!0),T()},destroy(){E==null||E.removeEventListener("resize",w),m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Gs=(e,t)=>ur(t)?zv(e,t):$v(e,t);var Op={},ux=!1,jv=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},Gv=()=>{try{if(typeof Op!="undefined"&&Op.url)return new URL("../widget.css",Op.url).href}catch{}return null},fx=(e,t)=>{let r=Gv(),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)}},mx=e=>{let t=jv(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Gs(t,n),s,i=[],c=(T,E)=>{var S,b;let k=!((b=(S=E==null?void 0:E.launcher)==null?void 0:S.enabled)!=null?b:!0)||ur(E),y=o.createElement("div");if(y.setAttribute("data-persona-root","true"),k&&(y.style.height="100%",y.style.display="flex",y.style.flexDirection="column",y.style.flex="1",y.style.minHeight="0"),r){let M=T.attachShadow({mode:"open"});M.appendChild(y),fx(M,o)}else T.appendChild(y),fx(T,o);return t.id&&y.setAttribute("data-persona-instance",t.id),y},d=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},g=()=>{let T=c(a.host,n);s=Hl(T,n,{debugTools:e.debugTools}),u()},p=()=>{i.forEach(T=>T()),i=[],s.destroy()};g(),e.onChatReady?e.onChatReady():e.onReady&&(ux||(ux=!0,console.warn("[Persona] `onReady` is deprecated: use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let m=T=>{p(),a.destroy(),a=Gs(t,T),n=T,g()},x={update(T){var b,M,W,R,L,N;let E={...n,...T,launcher:{...(b=n==null?void 0:n.launcher)!=null?b:{},...(M=T==null?void 0:T.launcher)!=null?M:{},dock:{...(R=(W=n==null?void 0:n.launcher)==null?void 0:W.dock)!=null?R:{},...(N=(L=T==null?void 0:T.launcher)==null?void 0:L.dock)!=null?N:{}}}},w=ur(n),k=ur(E),y=Dn(n),S=Dn(E);if(w!==k||y!==S){m(E);return}n=E,a.updateConfig(n),s.update(T),d()},destroy(){p(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},C=new Proxy(x,{get(T,E,w){if(E==="host")return a.host;if(E in T)return Reflect.get(T,E,w);let k=s[E];return typeof k=="function"?k.bind(s):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=C),C};var bx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Kv=new Set(["button","a","input","select","textarea","details","summary"]),Xv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),_p=/\b(product|card|item|listing|result)\b/i,qp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Qv=3e3,Jv=100;function vx(e){let t=typeof e.className=="string"?e.className:"";if(_p.test(t)||e.id&&_p.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&_p.test(o.value))return!0}return!1}function Cx(e){var t;return qp.test(((t=e.textContent)!=null?t:"").trim())}function wx(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 Yv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function gx(e){let t=e.match(qp);return t?t[0]:null}function hx(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 Zv(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 e0="commerce-card",t0="result-card";function xx(e){return!vx(e)||!Cx(e)||!wx(e)&&!Yv(e)?0:5200}function yx(e){var o;return!vx(e)||Cx(e)||!wx(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 Vp=[{id:e0,scoreElement(e){return xx(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||qp.test(o)&&o.length<32)}return!0},formatSummary(e,t){var c,d,u;if(xx(e)===0)return null;let{title:r,href:o}=hx(e),n=(u=(d=gx(((c=e.textContent)!=null?c:"").trim()))!=null?d:gx(t.text))!=null?u:"",a=Zv(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:t0,scoreElement(e){return yx(e)},formatSummary(e,t){if(yx(e)===0)return null;let{title:r,href:o}=hx(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
112
+ `)}}];function r0(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function o0(e){var u,g,p,m,x,C,T,E,w,k,y,S,b;let t=(u=e.options)!=null?u:{},r=(p=(g=t.maxElements)!=null?g:e.maxElements)!=null?p:80,o=(x=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",n=(T=(C=t.maxTextLength)!=null?C:e.maxTextLength)!=null?T:200,a=(w=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?w:!0,s=(k=t.root)!=null?k:e.root,i=(y=t.mode)!=null?y:"structured",c=(S=t.maxCandidates)!=null?S:Math.max(500,r*10),d=(b=e.rules)!=null?b:Vp;return i==="simple"&&e.rules&&e.rules.length>0?(r0(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:r,maxCandidates:c,excludeSelector:o,maxTextLength:n,visibleOnly:a,root:s,rules:d}}function Up(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var n0=["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"||Kv.has(t)||r&&Xv.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Sx(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 s0(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 d=0;d<e.attributes.length;d++){let u=e.attributes[d];u.name.startsWith("data-")&&(t[u.name]=u.value)}return t}function $p(e){let t=e.tagName.toLowerCase();if(e.id){let n=`#${Up(e.id)}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}}for(let n of n0){let a=e.getAttribute(n);if(a){let s=`${t}[${n}="${Up(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=>Up(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 i0(e){return e==="static"?Jv:Qv}function Ax(e,t){var n;let r=e.tagName.toLowerCase(),o=((n=e.textContent)!=null?n:"").trim().substring(0,t);return{selector:$p(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:a0(e),attributes:s0(e)}}function l0(e,t,r,o){let n=i0(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 d0(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 c0(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(bx.has(u)){i=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Sx(d)){i=s.nextNode();continue}let g=Ax(d,e.maxTextLength),p=g.text.length>0,m=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(T=>T==="role");if(!p&&!m){i=s.nextNode();continue}if(o.has(g.selector)){i=s.nextNode();continue}o.add(g.selector);let{score:x,formattingRule:C}=l0(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,p=u.enriched.interactivity==="static"?1:0;return g!==p?g-p:u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex});let c=[];for(let d of n){if(c.length>=e.maxElements)break;d0(c,d)||c.push(d)}return c.sort((d,u)=>{let g=d.enriched.interactivity==="static"?1:0,p=u.enriched.interactivity==="static"?1:0;return g!==p?g-p:g===1&&u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex}),c.map(d=>{var p;let u;if((p=d.formattingRule)!=null&&p.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 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,d=c.tagName.toLowerCase();if(bx.has(d)){a=n.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!Sx(c)){a=n.nextNode();continue}let u=Ax(c,e.maxTextLength),g=u.text.length>0,p=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!g&&!p){a=n.nextNode();continue}o.has(u.selector)||(o.add(u.selector),r.push(u))}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 Mx(e={}){var o;let t=o0(e),r=(o=t.root)!=null?o:document.body;return r?t.mode==="simple"?p0(t,r):c0(t,r):[]}var Dl=100;function Tx(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
113
  ${s.map(i=>`- ${i.split(`
114
114
  `).join(`
115
115
  `)}`).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,Hl)}" (clickable)`);o.push(`Interactive elements:
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,Dl)}" (clickable)`);o.push(`Interactive elements:
117
117
  ${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,Hl)}" (navigable)`);o.push(`Navigation links:
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,Dl)}" (navigable)`);o.push(`Navigation links:
119
119
  ${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,Hl)}" (input)`);o.push(`Form inputs:
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,Dl)}" (input)`);o.push(`Form inputs:
121
121
  ${s.join(`
122
- `)}`)}if(n.static.length>0){let s=n.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Hl)}"`);o.push(`Content:
122
+ `)}`)}if(n.static.length>0){let s=n.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Dl)}"`);o.push(`Content:
123
123
  ${s.join(`
124
124
  `)}`)}return o.join(`
125
125
 
126
- `)}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 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"}}},Px={components:{panel:{borderRadius:"0",shadow:"none"}}},Vp={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:oo},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?"]}},$p={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Px}},zp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Px}},jp={shop:Vp,minimal:$p,fullscreen:zp};function Rx(e){return jp[e]}var c0=`
126
+ `)}function Ex(){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 kx(){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 Lx(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:Vo(e.colors.primary,.95),100:Vo(e.colors.primary,.9),200:Vo(e.colors.primary,.8),300:Vo(e.colors.primary,.7),400:Vo(e.colors.primary,.6),500:e.colors.primary,600:Vo(e.colors.primary,.8),700:Vo(e.colors.primary,.7),800:Vo(e.colors.primary,.6),900:Vo(e.colors.primary,.5),950:Vo(e.colors.primary,.45)}}),{...t,palette:r}}}}function Px(){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 Ix(){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 Vo(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 Rx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var u0={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"}}},Wx={components:{panel:{borderRadius:"0",shadow:"none"}}},zp={id:"shop",label:"Shopping Assistant",config:{theme:u0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:no},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?"]}},jp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Wx}},Gp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Wx}},Kp={shop:zp,minimal:jp,fullscreen:Gp};function Hx(e){return Kp[e]}var f0=`
127
127
  @keyframes persona-stream-wipe {
128
128
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
129
129
  to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
@@ -159,7 +159,7 @@ ${s.join(`
159
159
  mask-image: none !important;
160
160
  }
161
161
  }
162
- `.trim(),p0={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:c0};ca(p0);var u0=`
162
+ `.trim(),m0={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:f0};ca(m0);var g0=`
163
163
  [data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
164
164
  animation: persona-stream-glyph-cycle-fade
165
165
  calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
@@ -177,7 +177,7 @@ ${s.join(`
177
177
  opacity: 1 !important;
178
178
  }
179
179
  }
180
- `.trim(),Xs="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",f0=10,m0=120,Gp=120,g0=.4,h0=50,x0=e=>{var o;if(!e)return Gp;let r=((o=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:o.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Gp},Ox=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=x0(t);return m0*r/Gp},Kp=e=>{let t=Xs[Math.floor(Math.random()*Xs.length)];return e&&t===e&&(t=Xs[(Xs.indexOf(t)+1)%Xs.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=Kp())}},Ix=new WeakMap,Wx=25,Hx=.5,b0=6,Bx=.25,Dx=new WeakMap,Fx=new WeakMap,v0=(e,t)=>{var n;if(!e)return Wx*Hx;let r=Dx.get(e);Dx.set(e,t);let o=(n=Fx.get(e))!=null?n:Wx;if(r!==void 0){let a=t-r;a>1&&(o=o*(1-Bx)+a*Bx,Fx.set(e,o))}return Math.max(b0,o*Hx)},Za=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&&Za.set(e,((t=Za.get(e))!=null?t:0)+1)},S0=e=>{var r;if(!e)return;let t=(r=Za.get(e))!=null?r:0;t<=1?Za.delete(e):Za.set(e,t-1)},_x=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=Kp();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=Ox(e),i=f0*s,c=n+i;if(o){let u=Ix.get(o);u!==void 0&&(c=Math.max(c,u)),Ix.set(o,c+a)}A0(e,t,c)},A0=(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,S0((c=e.dataset.glyphCycleMessageId)!=null?c:null),delete e.dataset.glyphCycleMessageId;return}let i=Kp(n);e.textContent=i,n=i,y0(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)},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=Za.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))M0(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()}};ca(T0);var Ux,qx,nr=typeof document!="undefined"&&(qx=(Ux=document.currentScript)==null?void 0:Ux.src)!=null?qx:null;bg(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${nr!=null?nr:"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)});pg(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${nr!=null?nr:"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});mi().catch(e=>{typeof console!="undefined"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});th(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${nr!=null?nr:"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);})();
180
+ `.trim(),Ks="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",h0=10,x0=120,Xp=120,y0=.4,b0=50,v0=e=>{var o;if(!e)return Xp;let r=((o=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:o.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Xp},qx=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=v0(t);return x0*r/Xp},Qp=e=>{let t=Ks[Math.floor(Math.random()*Ks.length)];return e&&t===e&&(t=Ks[(Ks.indexOf(t)+1)%Ks.length]),t},C0=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()<y0&&(n.textContent=Qp())}},Bx=new WeakMap,Dx=25,Fx=.5,w0=6,Nx=.25,Ox=new WeakMap,_x=new WeakMap,S0=(e,t)=>{var n;if(!e)return Dx*Fx;let r=Ox.get(e);Ox.set(e,t);let o=(n=_x.get(e))!=null?n:Dx;if(r!==void 0){let a=t-r;a>1&&(o=o*(1-Nx)+a*Nx,_x.set(e,o))}return Math.max(w0,o*Fx)},Ya=new Map,A0=e=>{var r;let t=e.closest("[data-message-id]");return(r=t==null?void 0:t.dataset.messageId)!=null?r:null},M0=e=>{var t;e&&Ya.set(e,((t=Ya.get(e))!=null?t:0)+1)},T0=e=>{var r;if(!e)return;let t=(r=Ya.get(e))!=null?r:0;t<=1?Ya.delete(e):Ya.set(e,t-1)},Vx=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=Qp();let r=A0(e);r&&(e.dataset.glyphCycleMessageId=r),M0(r);let o=e.closest(".persona-stream-glyph-cycle"),n=Date.now(),a=S0(o,n),s=qx(e),i=h0*s,c=n+i;if(o){let u=Bx.get(o);u!==void 0&&(c=Math.max(c,u)),Bx.set(o,c+a)}E0(e,t,c)},E0=(e,t,r)=>{var s;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=qx(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,T0((c=e.dataset.glyphCycleMessageId)!=null?c:null),delete e.dataset.glyphCycleMessageId;return}let i=Qp(n);e.textContent=i,n=i,C0(e),setTimeout(a,o)};setTimeout(a,o)},Ux=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))Vx(o)},k0=e=>e.nodeType===1,L0={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:g0,bufferContent(e){if(e.length<b0)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=Ya.get(e.id))!=null?t:0)>0},onAttach(e){Ux(e);let t=new MutationObserver(r=>{for(let o of r)for(let n of Array.from(o.addedNodes))k0(n)&&(n.classList.contains("persona-stream-char")&&n.closest(".persona-stream-glyph-cycle")?Vx(n):Ux(n))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};ca(L0);var $x,zx,sr=typeof document!="undefined"&&(zx=($x=document.currentScript)==null?void 0:$x.src)!=null?zx:null;vg(()=>{let e=sr==null?void 0:sr.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===sr?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${sr!=null?sr:"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)});ug(()=>{let e=sr==null?void 0:sr.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===sr?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${sr!=null?sr:"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});gi().catch(e=>{typeof console!="undefined"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});nh(()=>{let e=sr==null?void 0:sr.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===sr?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${sr!=null?sr:"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 ny(P0);})();
181
181
  /*! Bundled license information:
182
182
 
183
183
  lucide/dist/esm/icons/activity.mjs: