@runtypelabs/persona 4.4.2 → 4.5.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,23 +1,23 @@
1
- "use strict";var AgentWidget=(()=>{var cy=Object.create;var js=Object.defineProperty;var py=Object.getOwnPropertyDescriptor;var uy=Object.getOwnPropertyNames;var fy=Object.getPrototypeOf,my=Object.prototype.hasOwnProperty;var Cl=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,r)=>(typeof require!="undefined"?require:t)[r]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var rg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),gy=(e,t)=>{for(var r in t)js(e,r,{get:t[r],enumerable:!0})},og=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of uy(t))!my.call(e,n)&&n!==r&&js(e,n,{get:()=>t[n],enumerable:!(o=py(t,n))||o.enumerable});return e};var Sa=(e,t,r)=>(r=e!=null?cy(fy(e)):{},og(t||!e||!e.__esModule?js(r,"default",{value:e,enumerable:!0}):r,e)),hy=e=>og(js({},"__esModule",{value:!0}),e);var kl=rg(_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 Ys=rg(xr=>{"use strict";var Hy=xr&&xr.__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]})),By=xr&&xr.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Hy(t,e,r)};Object.defineProperty(xr,"__esModule",{value:!0});xr.Allow=xr.MalformedJSON=xr.PartialJSON=xr.parseJSON=xr.parse=void 0;var Lr=kl();Object.defineProperty(xr,"Allow",{enumerable:!0,get:function(){return Lr.Allow}});By(kl(),xr);var Js=class extends Error{};xr.PartialJSON=Js;var Qs=class extends Error{};xr.MalformedJSON=Qs;function vg(e,t=Lr.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return Dy(e.trim(),t)}xr.parseJSON=vg;var Dy=(e,t)=>{let r=e.length,o=0,n=u=>{throw new Js(`${u} at position ${o}`)},a=u=>{throw new Qs(`${u} at position ${o}`)},s=()=>(f(),o>=r&&n("Unexpected end of input"),e[o]==='"'?i():e[o]==="{"?c():e[o]==="["?l():e.substring(o,o+4)==="null"||Lr.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Lr.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Lr.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Lr.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Lr.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Lr.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):p()),i=()=>{let u=o,m=!1;for(o++;o<r&&(e[o]!=='"'||m&&e[o-1]==="\\");)m=e[o]==="\\"?!m:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(u,++o-Number(m)))}catch(x){a(String(x))}else if(Lr.Allow.STR&t)try{return JSON.parse(e.substring(u,o-Number(m))+'"')}catch{return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{o++,f();let u={};try{for(;e[o]!=="}";){if(f(),o>=r&&Lr.Allow.OBJ&t)return u;let m=i();f(),o++;try{let x=s();u[m]=x}catch(x){if(Lr.Allow.OBJ&t)return u;throw x}f(),e[o]===","&&o++}}catch{if(Lr.Allow.OBJ&t)return u;n("Expected '}' at end of object")}return o++,u},l=()=>{o++;let u=[];try{for(;e[o]!=="]";)u.push(s()),f(),e[o]===","&&o++}catch{if(Lr.Allow.ARR&t)return u;n("Expected ']' at end of array")}return o++,u},p=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Lr.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let u=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==r&&!(Lr.Allow.NUM&t)&&n("Unterminated number literal");try{return JSON.parse(e.substring(u,o))}catch{e.substring(u,o)==="-"&&n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(x){a(String(x))}}},f=()=>{for(;o<r&&`
2
- \r `.includes(e[o]);)o++};return s()},Fy=vg;xr.parse=Fy});var Z0={};gy(Z0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Nl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Fl,ASK_USER_QUESTION_TOOL_NAME:()=>ls,AgentWidgetClient:()=>Jn,AgentWidgetSession:()=>Ia,AttachmentManager:()=>ea,BrowserSpeechEngine:()=>Mn,DEFAULT_COMPONENTS:()=>Uc,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ki,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Jr,DEFAULT_PALETTE:()=>Oc,DEFAULT_SEMANTIC:()=>_c,DEFAULT_WIDGET_CONFIG:()=>Ht,PRESETS:()=>Pp,PRESET_FULLSCREEN:()=>Lp,PRESET_MINIMAL:()=>kp,PRESET_SHOP:()=>Ep,ReadAloudController:()=>Zn,SUGGEST_REPLIES_CLIENT_TOOL:()=>ri,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Hl,SUGGEST_REPLIES_TOOL_NAME:()=>vo,THEME_ZONES:()=>ih,VERSION:()=>Xn,WEBMCP_TOOL_PREFIX:()=>bo,WebMcpBridge:()=>Ta,accessibilityPlugin:()=>Ex,animationsPlugin:()=>kx,applyThemeVariables:()=>Tn,attachHeaderToContainer:()=>oa,brandPlugin:()=>Lx,buildComposer:()=>Fa,buildDefaultHeader:()=>Qc,buildHeader:()=>tn,buildHeaderWithLayout:()=>Da,buildMinimalHeader:()=>Yc,builtInClientToolsForDispatch:()=>ps,collectEnrichedPageContext:()=>Mx,componentRegistry:()=>rn,createActionManager:()=>Hs,createAgentExperience:()=>cl,createAskUserQuestionBubble:()=>Wg,createBestAvailableVoiceProvider:()=>hi,createBubbleWithLayout:()=>Rh,createCSATFeedback:()=>il,createComboButton:()=>Vi,createComponentMiddleware:()=>ax,createComponentStreamParser:()=>ol,createDefaultSanitizer:()=>Ml,createDirectivePostprocessor:()=>lg,createDropdownMenu:()=>Pn,createFlexibleJsonStreamParser:()=>Fg,createIconButton:()=>cr,createImagePart:()=>$g,createJsonStreamParser:()=>ci,createLabelButton:()=>ks,createLocalStorageAdapter:()=>rl,createMarkdownProcessor:()=>ns,createMarkdownProcessorFromConfig:()=>Gn,createMessageActions:()=>ap,createNPSFeedback:()=>ll,createPlainTextParser:()=>li,createPlugin:()=>Ix,createRegexJsonParser:()=>di,createStandardBubble:()=>Na,createTextPart:()=>gs,createTheme:()=>Ha,createThemeObserver:()=>Ii,createToggleGroup:()=>Sh,createTypingIndicator:()=>na,createVoiceProvider:()=>An,createWidgetHostLayout:()=>Bs,createXmlParser:()=>pi,defaultActionHandlers:()=>la,defaultJsonActionParser:()=>Ws,defaultParseRules:()=>Mp,detectColorScheme:()=>vs,directivePostprocessor:()=>dg,ensureAskUserQuestionSheet:()=>La,escapeHtml:()=>Fo,extractComponentDirectiveFromMessage:()=>sl,fileToImagePart:()=>jg,formatEnrichedContext:()=>Tx,generateAssistantMessageId:()=>Qn,generateMessageId:()=>_g,generateStableSelector:()=>Tp,generateUserMessageId:()=>Pa,getActiveTheme:()=>Ba,getColorScheme:()=>Vc,getDisplayText:()=>qg,getHeaderLayout:()=>Zc,getImageParts:()=>zg,getPreset:()=>Hx,hasComponentDirective:()=>al,hasImages:()=>Vg,headerLayouts:()=>zi,highContrastPlugin:()=>Rx,initAgentWidget:()=>mx,isAskUserQuestionMessage:()=>Jo,isComponentDirectiveType:()=>nx,isDockedMountMode:()=>nr,isSuggestRepliesMessage:()=>cs,isVoiceSupported:()=>xs,isWebMcpToolName:()=>yn,latestAgentSuggestions:()=>oi,listRegisteredStreamAnimations:()=>Gc,markdownPostprocessor:()=>Al,mergeWithDefaults:()=>Li,normalizeContent:()=>Ug,parseAskUserQuestionPayload:()=>Qo,parseSuggestRepliesPayload:()=>Dl,pickBestVoice:()=>Ra,pluginRegistry:()=>Is,reducedMotionPlugin:()=>Px,registerStreamAnimationPlugin:()=>ra,removeAskUserQuestionSheet:()=>wn,renderComponentDirective:()=>nl,renderLoadingIndicatorWithFallback:()=>np,renderLucideIcon:()=>fe,resolveDockConfig:()=>Qr,resolveSanitizer:()=>Ma,resolveTokens:()=>Pi,stripWebMcpPrefix:()=>Xs,themeToCssVariables:()=>Ri,unregisterStreamAnimationPlugin:()=>jc,validateImageFile:()=>Gg,validateTheme:()=>qc});var Sl=null,os=null,Aa=null,ng=e=>{Sl=e};var Gs=()=>os?Promise.resolve(os):Aa||(Sl?(Aa=Sl().then(e=>(os=e,e)),Aa):(Aa=import("./markdown-parsers-entry").then(e=>(os=e,e)),Aa)),jn=()=>os;var xy=e=>{if(e)return e},ns=e=>{let t=null;return r=>{var n,a;let o=jn();if(!o)return Fo(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=xy(e==null?void 0:e.renderer);c&&t.use({renderer:c})}return t.parse(r)}},Gn=e=>e?ns({markedOptions:e.options,renderer:e.renderer}):ns(),yy=ns(),Al=e=>yy(e),Fo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),sg=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),ag=e=>`%%FORM_PLACEHOLDER_${e}%%`,ig=(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=ag(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=ag(t.length);return t.push({token:a,type:n}),a}),r},lg=e=>{let t=Gn(e);return r=>{let o=[],n=ig(r,o),a=t(n);return o.forEach(({token:s,type:i})=>{let c=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${sg(i)}"></div>`;a=a.replace(c,p)}),a}},dg=e=>{let t=[],r=ig(e,t),o=Al(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="${sg(a)}"></div>`;o=o.replace(s,c)}),o};var by={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"]},vy=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ml=()=>{let e=null;return t=>{let r=jn();if(!r)return Fo(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:")&&!vy.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,by)}},Ma=e=>e===!1?null:typeof e=="function"?e:Ml();var cg=/^\s*\|?[\s:|-]*-[\s:|-]*$/,pg=e=>e.includes("|"),ug=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(r=>r.trim())},wy=e=>`| ${e.join(" | ")} |`,Cy=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Sy=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),fg=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
3
- `),r=!1;for(let o=0;o<t.length-1;o++){let n=t[o],a=t[o+1];if(!pg(n)||cg.test(n)||!cg.test(a))continue;let s=ug(n).length;if(s<1)continue;let i=Cy(s);t[o+1]!==i&&(t[o+1]=i,r=!0);let c=o+2;for(;c<t.length;c++){let l=t[c];if(l.trim()===""||!pg(l))break;let p=wy(Sy(ug(l),s));t[c]!==p&&(t[c]=p,r=!0)}o=c-1}return r?t.join(`
4
- `):e};var bo="webmcp:",Tl=new Map,mg=e=>{var t;Tl.clear();for(let r of e){let o=(t=r.title)==null?void 0:t.trim();o&&Tl.set(r.name,o)}},as=e=>Tl.get(Xs(e)),Ks={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},El=null,hg=e=>{El=e};function xg(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}:${Ay(t.join(""))}`}function gg(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 Ay(e){let t=gg(e,0).toString(36),r=gg(e,2654435761).toString(36);return`${t}.${r}`}var Ta=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 Ks.warn("getTools() threw: shipping an empty WebMCP snapshot.",n),[]}mg(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=Ty(n.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,r,o){if(await this.ensureReady(),this.config.enabled!==!0)return yo("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let x=typeof document!="undefined"&&!!document.modelContext;return yo(x?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let a=Xs(t),s;try{s=await n.getTools()}catch(x){let b=x instanceof Error?x.message:String(x);return yo(`Failed to read WebMCP registry: ${b}`)}mg(s);let i=s.find(x=>x.name===a);if(!i)return yo(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return yo(`WebMCP tool not allowed by client allowlist: ${a}`);if(o!=null&&o.aborted)return yo("Aborted by cancel()");let c=as(a),l={toolName:a,args:r,description:i.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(l))return yo("User declined the tool call.");if(o!=null&&o.aborted)return yo("Aborted by cancel()");let p=new AbortController,f=!1,u=setTimeout(()=>{f=!0,p.abort()},this.timeoutMs),m=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",m,{once:!0}));try{let x=await n.executeTool(i,Py(r),{signal:p.signal});return Ey(x)}catch(x){if(f)return yo(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return yo("Aborted by cancel()");let b=x instanceof Error?x.message:String(x);return yo(b)}finally{clearTimeout(u),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(El?await El():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ks.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,Ks.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:ky;try{return await r(t)}catch(n){return Ks.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=>My(t,o))}},Xs=e=>e.startsWith(bo)?e.slice(bo.length):e,yn=e=>e.startsWith(bo),My=(e,t)=>{if(t==="*")return!0;let r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)},Ty=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Ey=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:Ry(t)}]}},yo=e=>({isError:!0,content:[{type:"text",text:e}]}),ky=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ly(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var AgentWidget=(()=>{var Ly=Object.create;var Js=Object.defineProperty;var Py=Object.getOwnPropertyDescriptor;var Ry=Object.getOwnPropertyNames;var Iy=Object.getPrototypeOf,Wy=Object.prototype.hasOwnProperty;var Ll=(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 xg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Hy=(e,t)=>{for(var r in t)Js(e,r,{get:t[r],enumerable:!0})},yg=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ry(t))!Wy.call(e,n)&&n!==r&&Js(e,n,{get:()=>t[n],enumerable:!(o=Py(t,n))||o.enumerable});return e};var La=(e,t,r)=>(r=e!=null?Ly(Iy(e)):{},yg(t||!e||!e.__esModule?Js(r,"default",{value:e,enumerable:!0}):r,e)),By=e=>yg(Js({},"__esModule",{value:!0}),e);var Bl=xg(_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 oi=xg(hr=>{"use strict";var Zy=hr&&hr.__createBinding||(Object.create?(function(e,t,r,o){o===void 0&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}):(function(e,t,r,o){o===void 0&&(o=r),e[o]=t[r]})),eb=hr&&hr.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Zy(t,e,r)};Object.defineProperty(hr,"__esModule",{value:!0});hr.Allow=hr.MalformedJSON=hr.PartialJSON=hr.parseJSON=hr.parse=void 0;var Lr=Bl();Object.defineProperty(hr,"Allow",{enumerable:!0,get:function(){return Lr.Allow}});eb(Bl(),hr);var ti=class extends Error{};hr.PartialJSON=ti;var ri=class extends Error{};hr.MalformedJSON=ri;function Bg(e,t=Lr.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return tb(e.trim(),t)}hr.parseJSON=Bg;var tb=(e,t)=>{let r=e.length,o=0,n=u=>{throw new ti(`${u} at position ${o}`)},a=u=>{throw new ri(`${u} at position ${o}`)},s=()=>(f(),o>=r&&n("Unexpected end of input"),e[o]==='"'?i():e[o]==="{"?c():e[o]==="["?l():e.substring(o,o+4)==="null"||Lr.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Lr.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Lr.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Lr.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Lr.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Lr.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):p()),i=()=>{let u=o,g=!1;for(o++;o<r&&(e[o]!=='"'||g&&e[o-1]==="\\");)g=e[o]==="\\"?!g:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(u,++o-Number(g)))}catch(x){a(String(x))}else if(Lr.Allow.STR&t)try{return JSON.parse(e.substring(u,o-Number(g))+'"')}catch{return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{o++,f();let u={};try{for(;e[o]!=="}";){if(f(),o>=r&&Lr.Allow.OBJ&t)return u;let g=i();f(),o++;try{let x=s();u[g]=x}catch(x){if(Lr.Allow.OBJ&t)return u;throw x}f(),e[o]===","&&o++}}catch{if(Lr.Allow.OBJ&t)return u;n("Expected '}' at end of object")}return o++,u},l=()=>{o++;let u=[];try{for(;e[o]!=="]";)u.push(s()),f(),e[o]===","&&o++}catch{if(Lr.Allow.ARR&t)return u;n("Expected ']' at end of array")}return o++,u},p=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(g){if(Lr.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(g))}}let u=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==r&&!(Lr.Allow.NUM&t)&&n("Unterminated number literal");try{return JSON.parse(e.substring(u,o))}catch{e.substring(u,o)==="-"&&n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(x){a(String(x))}}},f=()=>{for(;o<r&&`
2
+ \r `.includes(e[o]);)o++};return s()},rb=Bg;hr.parse=rb});var yw={};Hy(yw,{ASK_USER_QUESTION_CLIENT_TOOL:()=>zl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>$l,ASK_USER_QUESTION_TOOL_NAME:()=>hs,AgentWidgetClient:()=>aa,AgentWidgetSession:()=>Na,AttachmentManager:()=>da,BrowserSpeechEngine:()=>Wn,DEFAULT_COMPONENTS:()=>Kc,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Wi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>jr,DEFAULT_PALETTE:()=>jc,DEFAULT_SEMANTIC:()=>Gc,DEFAULT_WIDGET_CONFIG:()=>It,PRESETS:()=>Fp,PRESET_FULLSCREEN:()=>Dp,PRESET_MINIMAL:()=>Bp,PRESET_SHOP:()=>Hp,ReadAloudController:()=>la,SUGGEST_REPLIES_CLIENT_TOOL:()=>ii,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Ul,SUGGEST_REPLIES_TOOL_NAME:()=>Co,THEME_ZONES:()=>Ch,VERSION:()=>na,WEBMCP_TOOL_PREFIX:()=>wo,WebMcpBridge:()=>Ia,accessibilityPlugin:()=>qx,animationsPlugin:()=>Vx,applyThemeVariables:()=>Hn,attachHeaderToContainer:()=>pa,brandPlugin:()=>$x,buildComposer:()=>Va,buildDefaultHeader:()=>np,buildHeader:()=>sn,buildHeaderWithLayout:()=>qa,buildMinimalHeader:()=>ap,builtInClientToolsForDispatch:()=>bs,collectEnrichedPageContext:()=>_x,componentRegistry:()=>ln,createActionManager:()=>qs,createAgentExperience:()=>gl,createAskUserQuestionBubble:()=>Kg,createBestAvailableVoiceProvider:()=>wi,createBubbleWithLayout:()=>jh,createCSATFeedback:()=>ul,createComboButton:()=>Ki,createComponentMiddleware:()=>vx,createComponentStreamParser:()=>ll,createDefaultSanitizer:()=>Il,createDirectivePostprocessor:()=>Sg,createDropdownMenu:()=>On,createFlexibleJsonStreamParser:()=>Yg,createIconButton:()=>pr,createImagePart:()=>sh,createJsonStreamParser:()=>gi,createLabelButton:()=>Ds,createLocalStorageAdapter:()=>il,createMarkdownProcessor:()=>us,createMarkdownProcessorFromConfig:()=>ra,createMessageActions:()=>up,createNPSFeedback:()=>fl,createPlainTextParser:()=>fi,createPlugin:()=>Gx,createRegexJsonParser:()=>mi,createStandardBubble:()=>$a,createTextPart:()=>Ss,createTheme:()=>_a,createThemeObserver:()=>Fi,createToggleGroup:()=>Nh,createTypingIndicator:()=>ua,createVoiceProvider:()=>In,createWidgetHostLayout:()=>Vs,createXmlParser:()=>hi,defaultActionHandlers:()=>ha,defaultJsonActionParser:()=>Us,defaultParseRules:()=>Ip,detectColorScheme:()=>ks,directivePostprocessor:()=>Ag,ensureAskUserQuestionSheet:()=>Ba,escapeHtml:()=>Uo,extractComponentDirectiveFromMessage:()=>pl,fileToImagePart:()=>ih,formatEnrichedContext:()=>Ux,generateAssistantMessageId:()=>sa,generateMessageId:()=>th,generateStableSelector:()=>Wp,generateUserMessageId:()=>Da,getActiveTheme:()=>Ua,getColorScheme:()=>Qc,getDisplayText:()=>oh,getHeaderLayout:()=>sp,getImageParts:()=>ah,getPreset:()=>Xx,hasComponentDirective:()=>cl,hasImages:()=>nh,headerLayouts:()=>Xi,highContrastPlugin:()=>jx,initAgentWidget:()=>Lx,isAskUserQuestionMessage:()=>rn,isComponentDirectiveType:()=>bx,isDockedMountMode:()=>nr,isSuggestRepliesMessage:()=>ys,isVoiceSupported:()=>Ms,isWebMcpToolName:()=>Tn,latestAgentSuggestions:()=>li,listRegisteredStreamAnimations:()=>ep,markdownPostprocessor:()=>Rl,mergeWithDefaults:()=>Hi,normalizeContent:()=>rh,parseAskUserQuestionPayload:()=>on,parseSuggestRepliesPayload:()=>Vl,pickBestVoice:()=>Fa,pluginRegistry:()=>_s,reducedMotionPlugin:()=>zx,registerStreamAnimationPlugin:()=>ca,removeAskUserQuestionSheet:()=>Ln,renderComponentDirective:()=>dl,renderLoadingIndicatorWithFallback:()=>pp,renderLucideIcon:()=>ge,resolveDockConfig:()=>Gr,resolveSanitizer:()=>Ra,resolveTokens:()=>Bi,stripWebMcpPrefix:()=>ei,themeToCssVariables:()=>Di,unregisterStreamAnimationPlugin:()=>Zc,validateImageFile:()=>lh,validateTheme:()=>Xc});var Pl=null,ps=null,Pa=null,bg=e=>{Pl=e};var Ys=()=>ps?Promise.resolve(ps):Pa||(Pl?(Pa=Pl().then(e=>(ps=e,e)),Pa):(Pa=import("./markdown-parsers-entry").then(e=>(ps=e,e)),Pa)),ta=()=>ps;var Dy=e=>{if(e)return e},us=e=>{let t=null;return r=>{var n,a;let o=ta();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=Dy(e==null?void 0:e.renderer);c&&t.use({renderer:c})}return t.parse(r)}},ra=e=>e?us({markedOptions:e.options,renderer:e.renderer}):us(),Fy=us(),Rl=e=>Fy(e),Uo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),wg=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vg=e=>`%%FORM_PLACEHOLDER_${e}%%`,Cg=(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=vg(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=vg(t.length);return t.push({token:a,type:n}),a}),r},Sg=e=>{let t=ra(e);return r=>{let o=[],n=Cg(r,o),a=t(n);return o.forEach(({token:s,type:i})=>{let c=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${wg(i)}"></div>`;a=a.replace(c,p)}),a}},Ag=e=>{let t=[],r=Cg(e,t),o=Rl(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="${wg(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"]},Oy=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Il=()=>{let e=null;return t=>{let r=ta();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:")&&!Oy.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,Ny)}},Ra=e=>e===!1?null:typeof e=="function"?e:Il();var Mg=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Tg=e=>e.includes("|"),Eg=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(r=>r.trim())},_y=e=>`| ${e.join(" | ")} |`,Uy=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,qy=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),kg=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
3
+ `),r=!1;for(let o=0;o<t.length-1;o++){let n=t[o],a=t[o+1];if(!Tg(n)||Mg.test(n)||!Mg.test(a))continue;let s=Eg(n).length;if(s<1)continue;let i=Uy(s);t[o+1]!==i&&(t[o+1]=i,r=!0);let c=o+2;for(;c<t.length;c++){let l=t[c];if(l.trim()===""||!Tg(l))break;let p=_y(qy(Eg(l),s));t[c]!==p&&(t[c]=p,r=!0)}o=c-1}return r?t.join(`
4
+ `):e};var wo="webmcp:",Wl=new Map,Lg=e=>{var t;Wl.clear();for(let r of e){let o=(t=r.title)==null?void 0:t.trim();o&&Wl.set(r.name,o)}},fs=e=>Wl.get(ei(e)),Zs={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Hl=null,Rg=e=>{Hl=e};function Ig(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}:${Vy(t.join(""))}`}function Pg(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 Vy(e){let t=Pg(e,0).toString(36),r=Pg(e,2654435761).toString(36);return`${t}.${r}`}var Ia=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var r;this.confirmHandler=(r=t.onConfirm)!=null?r:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let r;try{r=await t.getTools()}catch(n){return Zs.warn("getTools() threw: shipping an empty WebMCP snapshot.",n),[]}Lg(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=zy(n.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,r,o){if(await this.ensureReady(),this.config.enabled!==!0)return vo("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let x=typeof document!="undefined"&&!!document.modelContext;return vo(x?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let a=ei(t),s;try{s=await n.getTools()}catch(x){let b=x instanceof Error?x.message:String(x);return vo(`Failed to read WebMCP registry: ${b}`)}Lg(s);let i=s.find(x=>x.name===a);if(!i)return vo(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return vo(`WebMCP tool not allowed by client allowlist: ${a}`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let c=fs(a),l={toolName:a,args:r,description:i.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(l))return vo("User declined the tool call.");if(o!=null&&o.aborted)return vo("Aborted by cancel()");let p=new AbortController,f=!1,u=setTimeout(()=>{f=!0,p.abort()},this.timeoutMs),g=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",g,{once:!0}));try{let x=await n.executeTool(i,Xy(r),{signal:p.signal});return jy(x)}catch(x){if(f)return vo(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let b=x instanceof Error?x.message:String(x);return vo(b)}finally{clearTimeout(u),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Hl?await Hl():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Zs.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let r=t;return typeof r.getTools!="function"||typeof r.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Zs.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let r=(o=this.confirmHandler)!=null?o:Gy;try{return await r(t)}catch(n){return Zs.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,n),!1}}passesClientAllowlist(t){let r=this.config.allowlist;return!r||r.length===0?!0:r.some(o=>$y(t,o))}},ei=e=>e.startsWith(wo)?e.slice(wo.length):e,Tn=e=>e.startsWith(wo),$y=(e,t)=>{if(t==="*")return!0;let r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)},zy=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},jy=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:Qy(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Gy=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ky(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
5
5
 
6
6
  Arguments:
7
7
  ${t}`:"")+(e.description?`
8
8
 
9
- ${e.description}`:"");return window.confirm(r)},Ly=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)}},Py=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ry=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Iy="agent_",Wy="flow_";function yg(e){return e.startsWith(Iy)?{kind:"agentId",agentId:e}:e.startsWith(Wy)?{kind:"flowId",flowId:e}:null}function bg(e,t){let r=e.trim();if(!r)throw new Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let s=r.slice(0,o),i=r.slice(o+1);if(s==="runtype"){let l=yg(i);if(l)return l;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let c=t==null?void 0:t[s];if(!c)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(i).payload}}let n=yg(r);if(n)return n;let a=t==null?void 0:t.default;if(a)return{kind:"payload",payload:a(r).payload};throw new Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var bn=Sa(Ys(),1);var w=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},No=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var At=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let i of Object.keys(s)){let c=s[i];c!=null&&(a[i]=c)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},ss=(...e)=>e.filter(Boolean).join(" ");var ls="ask_user_question",is=8,Ea="data-persona-ask-sheet-for",Ny="Other",Oy="Other\u2026",Cg="Type your own answer here",Sg="Send",_y="Next",Uy="Back",qy="Submit all",Vy="Skip",zy=3,Ll="data-ask-current-index",Pl="data-ask-question-count",Ag="data-ask-answers",Rl="data-ask-grouped",Mg="data-ask-layout",$y=e=>e.layout==="pills"?"pills":"rows",jy=e=>e.getAttribute(Mg)==="pills"?"pills":"rows",wg=!1,Tg=e=>e.replace(/["\\]/g,"\\$&"),Jo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ls,Zs=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},Qo=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,bn.parse)(n,bn.STR|bn.OBJ|bn.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},ds=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>is&&!wg&&(wg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${is}.`)),t.slice(0,is)},Gy=e=>{var t;return(t=ds(e)[0])!=null?t:null},Ky=(e,t)=>{var r;return(r=ds(e)[t])!=null?r:null},Eg=(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))},kg=(e,t,r)=>{if(e!=="rows")return null;let o=w("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=w("span","persona-ask-row-check");o.appendChild(n)}else{let n=w("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Xy=(e,t,r,o)=>{let a=w("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=w("span","persona-ask-row-content"),i=w("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let l=w("span","persona-ask-row-description");l.textContent=e.description,s.appendChild(l)}a.appendChild(s);let c=kg(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Jy=e=>{let r=w("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},Qy=(e,t,r,o)=>{var p,f,u;let a=w("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<zy;m++)a.appendChild(Jy(o));return a}if(c.forEach((m,x)=>{a.appendChild(Xy(m,x,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Ny:Oy;if(o==="rows"){let x=w("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(c.length)),x.setAttribute("data-ask-other-row","true");let b=w("span","persona-ask-row-content"),L=document.createElement("input");L.type="text",L.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",L.placeholder=(p=t.freeTextPlaceholder)!=null?p:Cg,L.setAttribute("data-ask-free-text-input","true"),L.setAttribute("aria-label",(f=t.freeTextLabel)!=null?f:m),b.appendChild(L),x.appendChild(b);let E=kg(o,s,c.length);E&&x.appendChild(E),a.appendChild(x)}else{let x=w("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(u=t.freeTextLabel)!=null?u:m,a.appendChild(x)}}return a},Lg=(e,t)=>{var a,s;let o=w("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:Cg,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=w("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Sg,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Yy=e=>{var o;let t=w("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=w("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:Sg,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Zy=(e,t,r)=>{var l,p,f,u;let o=w("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=w("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(l=r.backLabel)!=null?l:Uy,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=w("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=w("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(p=r.skipLabel)!=null?p:Vy,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=w("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(f=r.submitAllLabel)!=null?f:qy:(u=r.nextLabel)!=null?u:_y,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},Kn=e=>{let t=e.getAttribute(Ag);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Pg=(e,t)=>{e.setAttribute(Ag,JSON.stringify(t))},co=e=>{var r;let t=Number((r=e.getAttribute(Ll))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},eb=(e,t)=>{e.setAttribute(Ll,String(Math.max(0,Math.floor(t))))},ka=e=>{var r;let t=Number((r=e.getAttribute(Pl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},vn=e=>e.getAttribute(Rl)==="true",tb=(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},rb=(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)))},ei=(e,t)=>{let{payload:r}=Qo(t),o=ds(r),n=Kn(e),a={},s=new Set;return o.forEach((i,c)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(n,c)&&(a[l]=n[c]))}),a},Rg=e=>{let t=Kn(e),r=co(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var f;let l=(f=c.getAttribute("data-option-label"))!=null?f:"",p=n.has(l);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let s=new Set(Array.from(a).map(c=>{var l;return(l=c.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},Ig=e=>{if(!vn(e))return;let t=Kn(e),r=co(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}},Il=(e,t,r)=>{let o=Zs(r),n=jy(e),{payload:a,complete:s}=Qo(t),i=vn(e),c=co(e),l=ka(e),p=i?Ky(a,c):Gy(a),f=!!(p!=null&&p.multiSelect),u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${c+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let A=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=A,x.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let A=Qy(p,o,s,n);b.replaceWith(A)}if(n!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Lg(o,n))}let L=e.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!L?e.appendChild(Yy(o)):(!f||i)&&L&&L.remove(),e.setAttribute("data-multi-select",f?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=Zy(c,l,o);E?E.replaceWith(A):e.appendChild(A)}else E&&E.remove();Rg(e),Ig(e)},ob=(e,t,r)=>{let o=Zs(t),n=$y(o),a=e.toolCall.id,s=ds(r),i=Math.max(1,s.length),c=i>1,l=tb(e,s),p=c?rb(e,i):0,f=w("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Ea,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",e.id),f.setAttribute(Pl,String(i)),f.setAttribute(Ll,String(p)),f.setAttribute(Rl,c?"true":"false"),f.setAttribute(Mg,n),Pg(f,l),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Eg(f,o);let u=w("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=w("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",u.appendChild(m);let x=w("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",u.appendChild(x),f.appendChild(u);let L=w("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),f.appendChild(L),n!=="rows"&&f.appendChild(Lg(o,n)),Il(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},nb=(e,t,r)=>{let{payload:o}=Qo(t),n=Math.max(1,ds(o).length);n>ka(e)&&(e.setAttribute(Pl,String(n)),n>1&&!vn(e)&&e.setAttribute(Rl,"true")),Il(e,t,r)},Wg=(e,t)=>{let r=w("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=Zs(t);Eg(r,o);let n=w("span","persona-ask-stub-label"),{complete:a}=Qo(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},La=(e,t,r)=>{if(!r||!Jo(e)||Zs(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Ea}]`).forEach(l=>{l.getAttribute(Ea)!==n&&l.remove()});let s=r.querySelector(`[${Ea}="${Tg(n)}"]`);if(s){nb(s,e,t);return}let{payload:i}=Qo(e),c=ob(e,t,i);r.appendChild(c)},wn=(e,t)=>{if(!e)return;let r=t?`[${Ea}="${Tg(t)}"]`:`[${Ea}]`;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)})},Wl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Cn=(e,t)=>{let r=Kn(e),o=co(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,Pg(e,r),Rg(e),Ig(e)},ti=(e,t,r,o)=>{let n=ka(e),a=Math.max(0,Math.min(n-1,o));eb(e,a),Il(e,t,r)};var vo="suggest_replies";var Hl={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},ri={name:vo,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Hl,origin:"sdk",annotations:{readOnlyHint:!0}},Bl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),cs=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===vo},Dl=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},oi=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!cs(o))continue;let n=Dl((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},Hg=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 Fl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:is,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Nl={name:ls,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Fl,origin:"sdk",annotations:{readOnlyHint:!0}},ps=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(Nl),Hg(e)&&t.push(ri),t};var Yo=Sa(Ys(),1),ni=e=>e.replace(/\\n/g,`
10
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Sn=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)}},ab=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`},Bg=e=>e.status==="complete"?ab(e):e.status==="pending"?"Waiting":"",sb=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 Dg=e=>e.status==="complete"?sb(e):"Using tool...",ai=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},fs=e=>{var r,o,n;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ai(t)},si=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 ai(t)},Ol=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=fs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},ii=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&us(o,r.slice(a,s.index),[]),s[1]!==void 0?us(o,s[1],["bold"]):s[2]!==void 0?us(o,s[2],["italic"]):s[3]!==void 0&&us(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&us(o,r.slice(a),[]),o},us=(e,t,r)=>{let o=t.split("{duration}");for(let n=0;n<o.length;n++)o[n]&&e.push({text:o[n],styles:r}),n<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},ib=()=>{let e=null,t=0,r=o=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(n);if(a&&a[1])try{return a[1].replace(/\\n/g,`
9
+ ${e.description}`:"");return window.confirm(r)},Ky=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)}},Xy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Qy=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Jy="agent_",Yy="flow_";function Wg(e){return e.startsWith(Jy)?{kind:"agentId",agentId:e}:e.startsWith(Yy)?{kind:"flowId",flowId:e}:null}function Hg(e,t){let r=e.trim();if(!r)throw new Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let s=r.slice(0,o),i=r.slice(o+1);if(s==="runtype"){let l=Wg(i);if(l)return l;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let c=t==null?void 0:t[s];if(!c)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(i).payload}}let n=Wg(r);if(n)return n;let a=t==null?void 0:t.default;if(a)return{kind:"payload",payload:a(r).payload};throw new Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var En=La(oi(),1);var w=(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 St=(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},ms=(...e)=>e.filter(Boolean).join(" ");var hs="ask_user_question",gs=8,Wa="data-persona-ask-sheet-for",ob="Other",nb="Other\u2026",Fg="Type your own answer here",Ng="Send",ab="Next",sb="Back",ib="Submit all",lb="Skip",db=3,Dl="data-ask-current-index",Fl="data-ask-question-count",Og="data-ask-answers",Nl="data-ask-grouped",_g="data-ask-layout",cb=e=>e.layout==="pills"?"pills":"rows",pb=e=>e.getAttribute(_g)==="pills"?"pills":"rows",Dg=!1,Ug=e=>e.replace(/["\\]/g,"\\$&"),rn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===hs,ni=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}},xs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>gs&&!Dg&&(Dg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${gs}.`)),t.slice(0,gs)},ub=e=>{var t;return(t=xs(e)[0])!=null?t:null},fb=(e,t)=>{var r;return(r=xs(e)[t])!=null?r:null},qg=(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))},Vg=(e,t,r)=>{if(e!=="rows")return null;let o=w("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=w("span","persona-ask-row-check");o.appendChild(n)}else{let n=w("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},mb=(e,t,r,o)=>{let a=w("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=w("span","persona-ask-row-content"),i=w("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let l=w("span","persona-ask-row-description");l.textContent=e.description,s.appendChild(l)}a.appendChild(s);let c=Vg(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},gb=e=>{let r=w("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},hb=(e,t,r,o)=>{var p,f,u;let a=w("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(g=>g&&typeof g.label=="string"&&g.label.length>0);if(c.length===0&&!r){for(let g=0;g<db;g++)a.appendChild(gb(o));return a}if(c.forEach((g,x)=>{a.appendChild(mb(g,x,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let g=o==="rows"?ob:nb;if(o==="rows"){let x=w("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(c.length)),x.setAttribute("data-ask-other-row","true");let b=w("span","persona-ask-row-content"),L=document.createElement("input");L.type="text",L.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",L.placeholder=(p=t.freeTextPlaceholder)!=null?p:Fg,L.setAttribute("data-ask-free-text-input","true"),L.setAttribute("aria-label",(f=t.freeTextLabel)!=null?f:g),b.appendChild(L),x.appendChild(b);let E=Vg(o,s,c.length);E&&x.appendChild(E),a.appendChild(x)}else{let x=w("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(u=t.freeTextLabel)!=null?u:g,a.appendChild(x)}}return a},$g=(e,t)=>{var a,s;let o=w("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:Fg,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=w("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Ng,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},xb=e=>{var o;let t=w("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=w("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:Ng,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},yb=(e,t,r)=>{var l,p,f,u;let o=w("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=w("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(l=r.backLabel)!=null?l:sb,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=w("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=w("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(p=r.skipLabel)!=null?p:lb,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=w("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(f=r.submitAllLabel)!=null?f:ib:(u=r.nextLabel)!=null?u:ab,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},oa=e=>{let t=e.getAttribute(Og);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},zg=(e,t)=>{e.setAttribute(Og,JSON.stringify(t))},so=e=>{var r;let t=Number((r=e.getAttribute(Dl))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},bb=(e,t)=>{e.setAttribute(Dl,String(Math.max(0,Math.floor(t))))},Ha=e=>{var r;let t=Number((r=e.getAttribute(Fl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},kn=e=>e.getAttribute(Nl)==="true",vb=(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},wb=(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)))},ai=(e,t)=>{let{payload:r}=on(t),o=xs(r),n=oa(e),a={},s=new Set;return o.forEach((i,c)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(n,c)&&(a[l]=n[c]))}),a},jg=e=>{let t=oa(e),r=so(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var f;let l=(f=c.getAttribute("data-option-label"))!=null?f:"",p=n.has(l);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let s=new Set(Array.from(a).map(c=>{var l;return(l=c.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},Gg=e=>{if(!kn(e))return;let t=oa(e),r=so(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}},Ol=(e,t,r)=>{let o=ni(r),n=pb(e),{payload:a,complete:s}=on(t),i=kn(e),c=so(e),l=Ha(e),p=i?fb(a,c):ub(a),f=!!(p!=null&&p.multiSelect),u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${c+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let A=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=A,x.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let A=hb(p,o,s,n);b.replaceWith(A)}if(n!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith($g(o,n))}let L=e.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!L?e.appendChild(xb(o)):(!f||i)&&L&&L.remove(),e.setAttribute("data-multi-select",f?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=yb(c,l,o);E?E.replaceWith(A):e.appendChild(A)}else E&&E.remove();jg(e),Gg(e)},Cb=(e,t,r)=>{let o=ni(t),n=cb(o),a=e.toolCall.id,s=xs(r),i=Math.max(1,s.length),c=i>1,l=vb(e,s),p=c?wb(e,i):0,f=w("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Wa,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",e.id),f.setAttribute(Fl,String(i)),f.setAttribute(Dl,String(p)),f.setAttribute(Nl,c?"true":"false"),f.setAttribute(_g,n),zg(f,l),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),qg(f,o);let u=w("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=w("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",u.appendChild(g);let x=w("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",u.appendChild(x),f.appendChild(u);let L=w("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),f.appendChild(L),n!=="rows"&&f.appendChild($g(o,n)),Ol(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Sb=(e,t,r)=>{let{payload:o}=on(t),n=Math.max(1,xs(o).length);n>Ha(e)&&(e.setAttribute(Fl,String(n)),n>1&&!kn(e)&&e.setAttribute(Nl,"true")),Ol(e,t,r)},Kg=(e,t)=>{let r=w("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=ni(t);qg(r,o);let n=w("span","persona-ask-stub-label"),{complete:a}=on(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Ba=(e,t,r)=>{if(!r||!rn(e)||ni(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Wa}]`).forEach(l=>{l.getAttribute(Wa)!==n&&l.remove()});let s=r.querySelector(`[${Wa}="${Ug(n)}"]`);if(s){Sb(s,e,t);return}let{payload:i}=on(e),c=Cb(e,t,i);r.appendChild(c)},Ln=(e,t)=>{if(!e)return;let r=t?`[${Wa}="${Ug(t)}"]`:`[${Wa}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},_l=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Pn=(e,t)=>{let r=oa(e),o=so(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,zg(e,r),jg(e),Gg(e)},si=(e,t,r,o)=>{let n=Ha(e),a=Math.max(0,Math.min(n-1,o));bb(e,a),Ol(e,t,r)};var Co="suggest_replies";var Ul={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},ii={name:Co,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:Ul,origin:"sdk",annotations:{readOnlyHint:!0}},ql=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ys=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Co},Vl=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},li=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!ys(o))continue;let n=Vl((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},Xg=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 $l={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:gs,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},zl={name:hs,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:$l,origin:"sdk",annotations:{readOnlyHint:!0}},bs=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(zl),Xg(e)&&t.push(ii),t};var nn=La(oi(),1),di=e=>e.replace(/\\n/g,`
10
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Rn=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)}},Ab=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`},Qg=e=>e.status==="complete"?Ab(e):e.status==="pending"?"Waiting":"",Mb=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 Jg=e=>e.status==="complete"?Mb(e):"Using tool...",ci=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ws=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 ci(t)},pi=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 ci(t)},jl=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=ws(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},ui=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&vs(o,r.slice(a,s.index),[]),s[1]!==void 0?vs(o,s[1],["bold"]):s[2]!==void 0?vs(o,s[2],["italic"]):s[3]!==void 0&&vs(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&vs(o,r.slice(a),[]),o},vs=(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})},Tb=()=>{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,`
11
11
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
12
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ms=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=ib();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)}},ci=()=>{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,Yo.parse)(r,Yo.STR|Yo.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?ni(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=ni(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Fg=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?ni(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ni(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,Yo.parse)(a,Yo.STR|Yo.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},pi=()=>{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 Ng="4.4.2";var Xn=Ng;var db="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function cb(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 _l=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 pb(e){switch(e){case"json":return ci;case"regex-json":return di;case"xml":return pi;default:return li}}var Og=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ub(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=Og(r);if(!Og(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ms(e);return ms(t)!==null&&s===null?t:e}var Jn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(r=t.apiUrl)!=null?r:db,this.headers={"Content-Type":"application/json","X-Persona-Version":Xn,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:pb(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 Ta(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}routing(){let{agentId:t,flowId:r,target:o,targetProviders:n}=this.config;if(!o)return{agentId:t,flowId:r};let a=bg(o,n);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/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 i,c,l;let t=((c=(i=this.config).getStoredSessionId)==null?void 0:c.call(i))||null,r=this.routing(),o=(l=r.agentId)!=null?l:r.flowId,n={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):a.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/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":Xn},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.isClientTokenMode()?this.dispatchClientToken(t,r):this.isAgentMode()?this.dispatchAgent(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,f={sessionId:c.sessionId,messages:t.messages.filter(_l).map(y=>{var S,v,M;return{id:y.id,role:y.role,content:(M=(v=(S=y.contentParts)!=null?S:y.llmContent)!=null?v:y.rawContent)!=null?M:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},u=l.clientTools,m=!!(u&&u.length>0),x=m?xg(u):void 0,b=this.clientToolsFingerprintSessionId===c.sessionId,L=m&&b&&this.lastSentClientToolsFingerprint===x,E=!1,A=null,T;for(let y=0;;y++){let v={...f,...m&&(E||!L)&&u?{clientTools:u}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(v),signal:o.signal}),T.status===409&&y===0&&m){let M=await T.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=M!=null?M:{error:"Chat request failed"}}break}if(!T.ok){let y=A!=null?A:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(T.status===429){let v=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let S=new Error(y.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!T.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(T.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let l=c instanceof Error?c:new Error(String(c));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var l,p;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ui}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,i,c;let r=this.routing().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(_l).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let f=new Date(l.createdAt).getTime(),u=new Date(p.createdAt).getTime();return f-u}).map(l=>{var p,f,u;return{role:l.role,content:(u=(f=(p=l.contentParts)!=null?p:l.llmContent)!=null?f:l.rawContent)!=null?u:l.content,createdAt:l.createdAt}}),n={agent:(s=this.config.agent)!=null?s:{agentId:r},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...ps(this.config),...(c=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?c:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let f=await p({messages:t,config:this.config});f&&typeof f=="object"&&Object.assign(l,f)}catch(f){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",f)}})),Object.keys(l).length&&(n.context=l)}return n}async buildPayload(t){var s,i;let r=t.slice().filter(_l).sort((c,l)=>{let p=new Date(c.createdAt).getTime(),f=new Date(l.createdAt).getTime();return p-f}).map(c=>{var l,p,f;return{role:c.role,content:(f=(p=(l=c.contentParts)!=null?l:c.llmContent)!=null?p:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o=this.routing(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[c,l]of Object.entries(o.targetPayload))c!=="messages"&&(n[c]=l);let a=[...ps(this.config),...(i=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?i:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(c,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(c).length&&(n.context=c)}if(this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...n},config:this.config});if(c&&typeof c=="object"){let l=c;return n.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=n.clientTools),l}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",c)}return n}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=f,n(f),f},l=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var bt,yr,Co,So;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,l=()=>i+c++,p=P=>{let ee=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,Se=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,We=P.tools?P.tools.map(ke=>({...ke,chunks:ke.chunks?[...ke.chunks]:void 0})):void 0;return{...P,reasoning:ee,toolCall:Se,tools:We}},f=P=>{if(P.role!=="assistant"||P.variant)return!0;let ee=Array.isArray(P.contentParts)&&P.contentParts.length>0,Se=typeof P.rawContent=="string"&&P.rawContent.trim()!=="";return typeof P.content=="string"&&P.content.trim()!==""||ee||Se||!!P.stopReason},u=P=>{f(P)&&r({type:"message",message:p(P)})},m=null,x=null,b={current:null},L={current:null},E=null,A="",T=new Map,y=new Map,S=new Map,v=new Map,M=new Map,W={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},I=P=>{if(P==null)return null;try{return String(P)}catch{return null}},D=P=>{var ee,Se,We,ke,He;return I((He=(ke=(We=(Se=(ee=P.stepId)!=null?ee:P.step_id)!=null?Se:P.step)!=null?We:P.parentId)!=null?ke:P.flowStepId)!=null?He:P.flow_step_id)},O=P=>{var ee,Se,We,ke,He,Ge,st;return I((st=(Ge=(He=(ke=(We=(Se=(ee=P.callId)!=null?ee:P.call_id)!=null?Se:P.requestId)!=null?We:P.request_id)!=null?ke:P.toolCallId)!=null?He:P.tool_call_id)!=null?Ge:P.stepId)!=null?st:P.step_id)},J=o,me=!1,de=()=>{if(m)return m;let P,ee=E;return!me&&J?(P=J,me=!0):J&&ee?P=`${J}_${ee}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:P,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(m),m},te=(P,ee)=>{W.lastId=ee,P&&W.byStep.set(P,ee)},Ae=(P,ee)=>{var He;let Se=(He=P.reasoningId)!=null?He:P.id,We=D(P);if(Se){let Ge=String(Se);return te(We,Ge),Ge}if(We){let Ge=W.byStep.get(We);if(Ge)return W.lastId=Ge,Ge}if(W.lastId&&!ee)return W.lastId;if(!ee)return null;let ke=`reason-${l()}`;return te(We,ke),ke},Ie=P=>{let ee=v.get(P);if(ee)return ee;let Se={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:P,status:"streaming",chunks:[]}};return v.set(P,Se),u(Se),Se},le=(P,ee)=>{H.lastId=ee,P&&H.byCall.set(P,ee)},Ce=new Set,se=new Map,ie=new Set,pe=new Map,Ee=P=>{if(!P)return!1;let ee=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},De=(P,ee)=>{var He;let Se=(He=P.toolId)!=null?He:P.id,We=O(P);if(Se){let Ge=String(Se);return le(We,Ge),Ge}if(We){let Ge=H.byCall.get(We);if(Ge)return H.lastId=Ge,Ge}if(H.lastId&&!ee)return H.lastId;if(!ee)return null;let ke=`tool-${l()}`;return le(We,ke),ke},j=P=>{let ee=M.get(P);if(ee)return ee;let Se={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:P,status:"pending"}};return M.set(P,Se),u(Se),Se},Q=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let ee=Number(P);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let Se=Date.parse(P);if(!Number.isNaN(Se))return Se}return Date.now()},Fe=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},K=new Map,ce=new Map,qe=new Map,ot=(P,ee,Se)=>{var st;let We=qe.get(P);We||(We=[],qe.set(P,We));let ke=0,He=We.length;for(;ke<He;){let Rt=ke+He>>>1;We[Rt].seq<ee?ke=Rt+1:He=Rt}((st=We[ke])==null?void 0:st.seq)===ee?We[ke]={seq:ee,text:Se}:We.splice(ke,0,{seq:ee,text:Se});let Ge="";for(let Rt=0;Rt<We.length;Rt++)Ge+=We[Rt].text;return Ge},yt=(P,ee)=>{let Se=Fe(ee),We=ce.get(P.id),ke=ub(We,Se);P.rawContent=ke;let He=K.get(P.id),Ge=he=>{var vt;let Ne=(vt=P.content)!=null?vt:"";he.trim()!==""&&(Ne.trim().length===0||he.startsWith(Ne)||he.trimStart().startsWith(Ne.trim()))&&(P.content=he)},st=()=>{var he;if(He){let Ne=(he=He.close)==null?void 0:he.call(He);Ne instanceof Promise&&Ne.catch(()=>{})}K.delete(P.id),ce.delete(P.id),P.streaming=!1,u(P)};if(!He){Ge(Se),st();return}let Rt=ms(ke);if(Rt!==null&&Rt.trim()!==""){Ge(Rt),st();return}let ae=he=>{var Je;let Ne=typeof he=="string"?he:(Je=he==null?void 0:he.text)!=null?Je:null;if(Ne!==null&&Ne.trim()!=="")return Ne;let vt=He.getExtractedText();return vt!==null&&vt.trim()!==""?vt:Se},F;try{F=He.processChunk(ke)}catch{Ge(Se),st();return}if(F instanceof Promise){F.then(he=>{Ge(ae(he)),st()}).catch(()=>{Ge(Se),st()});return}Ge(ae(F)),st()},Ot=null,Qt=(P,ee,Se,We)=>{var Rt;P.rawContent=ee,K.has(P.id)||K.set(P.id,this.createStreamParser());let ke=K.get(P.id),He=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(He&&ce.set(P.id,ee),ke.__isPlainTextParser===!0){P.content=We!==void 0?ee:P.content+Se,ce.delete(P.id),K.delete(P.id),P.rawContent=void 0,u(P);return}let st=ke.processChunk(ee);if(st instanceof Promise)st.then(ae=>{var he;let F=typeof ae=="string"?ae:(he=ae==null?void 0:ae.text)!=null?he:null;F!==null&&F.trim()!==""?(P.content=F,u(P)):!He&&!ee.trim().startsWith("<")&&(P.content=We!==void 0?ee:P.content+Se,ce.delete(P.id),K.delete(P.id),P.rawContent=void 0,u(P))}).catch(()=>{P.content=We!==void 0?ee:P.content+Se,ce.delete(P.id),K.delete(P.id),P.rawContent=void 0,u(P)});else{let ae=typeof st=="string"?st:(Rt=st==null?void 0:st.text)!=null?Rt:null;ae!==null&&ae.trim()!==""?(P.content=ae,u(P)):!He&&!ee.trim().startsWith("<")&&(P.content=We!==void 0?ee:P.content+Se,ce.delete(P.id),K.delete(P.id),P.rawContent=void 0,u(P))}},Ye=(P,ee)=>{var Rt,ae;let Se=ee!=null?ee:P.content;if(Se==null||Se===""){P.streaming=!1,u(P);return}let We=ce.get(P.id),ke=We!=null?We:Fe(Se);P.rawContent=ke;let He=K.get(P.id),Ge=null,st=!1;if(He&&(Ge=He.getExtractedText(),Ge===null&&(Ge=ms(ke)),Ge===null)){let F=He.processChunk(ke);F instanceof Promise?(st=!0,F.then(he=>{var vt;let Ne=typeof he=="string"?he:(vt=he==null?void 0:he.text)!=null?vt:null;Ne!==null&&(P.content=Ne,P.streaming=!1,K.delete(P.id),ce.delete(P.id),u(P))}).catch(()=>{})):Ge=typeof F=="string"?F:(Rt=F==null?void 0:F.text)!=null?Rt:null}if(!st){Ge!==null&&Ge.trim()!==""?P.content=Ge:ce.has(P.id)||(P.content=Fe(Se));let F=K.get(P.id);if(F){let he=(ae=F.close)==null?void 0:ae.call(F);he instanceof Promise&&he.catch(()=>{}),K.delete(P.id)}ce.delete(P.id),P.streaming=!1,u(P)}},ge=(P,ee,Se)=>{let We=y.get(P);if(We)return We;let ke={id:`nested-${ee}-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Se?{variant:Se}:{},...Se==="reasoning"?{reasoning:{id:P,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return y.set(P,ke),u(ke),ke},X=[],dt,ze=new Map,ve=0,Me="agent",et=!1,Pt=null,Z=null,Ue=new Map,Ar=(bt=this.config.iterationDisplay)!=null?bt:"separate";for(dt=()=>{var P,ee,Se,We,ke,He,Ge,st,Rt,ae,F,he,Ne,vt,Je,Bt,Mt,gt,Lt,Jt,_t,Fr,qt,Nr,Zr,br,Rr,eo,on,wt,Ao,Mo,_o,uo,pt,Rn,To,In,Ir,da,nn,Uo,an,sn,Wn,Hn,ln,xt,Or,_r,Mr,Ct,to,ro,Ur,dn,qo,cn,qr,It,Tr,oo,pn,Vo,un,ye,Wr,Eo,ut,ar,sr,ko,$a,zo,Bn,Lo,q,ca,Po,Ro,$o,Io,fo,pa,Fs,Vr,zr,mo,go,Dn,jo,vr,Wo,ua,Fn,fa,Ns,ma,Os,ga,ct,ja,no,Hr,_s;for(let ha=0;ha<X.length;ha++){let Ze=X[ha].payloadType,k=X[ha].payload;if(!et&&Me!=="flow"&&typeof k.stepType=="string"&&(Me="flow"),Ze==="reasoning_start"){let $=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if($&&V){T.set($,V),ge($,V,"reasoning");continue}let G=(P=Ae(k,!0))!=null?P:`reason-${l()}`,xe=Ie(G);xe.reasoning=(ee=xe.reasoning)!=null?ee:{id:G,status:"streaming",chunks:[]},xe.reasoning.startedAt=(We=xe.reasoning.startedAt)!=null?We:Q((Se=k.startedAt)!=null?Se:k.timestamp),xe.reasoning.completedAt=void 0,xe.reasoning.durationMs=void 0,(k.scope==="loop"||k.scope==="turn")&&(xe.reasoning.scope=k.scope),xe.streaming=!0,xe.reasoning.status="streaming",u(xe)}else if(Ze==="reasoning_delta"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)&&y.has($)){let Oe=y.get($),ft=(Ge=(He=(ke=k.reasoningText)!=null?ke:k.text)!=null?He:k.delta)!=null?Ge:"";ft&&k.hidden!==!0&&Oe.reasoning&&(Oe.reasoning.chunks.push(String(ft)),u(Oe));continue}let V=(Rt=(st=Ae(k,!1))!=null?st:Ae(k,!0))!=null?Rt:`reason-${l()}`,G=Ie(V);G.reasoning=(ae=G.reasoning)!=null?ae:{id:V,status:"streaming",chunks:[]},G.reasoning.startedAt=(he=G.reasoning.startedAt)!=null?he:Q((F=k.startedAt)!=null?F:k.timestamp);let xe=(Je=(vt=(Ne=k.reasoningText)!=null?Ne:k.text)!=null?vt:k.delta)!=null?Je:"";if(xe&&k.hidden!==!0){let Oe=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(Oe!==void 0){let ft=ot(V,Oe,String(xe));G.reasoning.chunks=[ft]}else G.reasoning.chunks.push(String(xe))}if(G.reasoning.status=k.done?"complete":"streaming",k.done){G.reasoning.completedAt=Q((Bt=k.completedAt)!=null?Bt:k.timestamp);let Oe=(Mt=G.reasoning.startedAt)!=null?Mt:Date.now();G.reasoning.durationMs=Math.max(0,((gt=G.reasoning.completedAt)!=null?gt:Date.now())-Oe)}G.streaming=G.reasoning.status!=="complete",u(G)}else if(Ze==="reasoning_complete"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)&&y.has($)){let ft=y.get($);if(ft.reasoning){let nt=typeof k.text=="string"?k.text:"";nt&&ft.reasoning.chunks.length===0&&ft.reasoning.chunks.push(nt),ft.reasoning.status="complete",ft.streaming=!1,u(ft)}T.delete($),y.delete($);continue}let V=(Jt=(Lt=Ae(k,!1))!=null?Lt:Ae(k,!0))!=null?Jt:`reason-${l()}`,G=typeof k.text=="string"?k.text:"";!v.get(V)&&(G||k.scope==="loop")&&Ie(V);let xe=v.get(V);if(xe!=null&&xe.reasoning){(k.scope==="loop"||k.scope==="turn")&&(xe.reasoning.scope=k.scope),G&&xe.reasoning.chunks.length===0&&xe.reasoning.chunks.push(G),xe.reasoning.status="complete",xe.reasoning.completedAt=Q((_t=k.completedAt)!=null?_t:k.timestamp);let ft=(Fr=xe.reasoning.startedAt)!=null?Fr:Date.now();xe.reasoning.durationMs=Math.max(0,((qt=xe.reasoning.completedAt)!=null?qt:Date.now())-ft),xe.streaming=!1,u(xe)}let Oe=D(k);Oe&&W.byStep.delete(Oe)}else if(Ze==="tool_start"){m&&(m.streaming=!1,u(m),m=null),typeof k.iteration=="number"&&(ve=k.iteration);let $=(Zr=(Nr=typeof k.toolCallId=="string"?k.toolCallId:void 0)!=null?Nr:De(k,!0))!=null?Zr:`tool-${l()}`,V=(br=k.toolName)!=null?br:k.name;if(Ee(V)){Ce.add($);continue}le(O(k),$);let G=j($),xe=(Rr=G.toolCall)!=null?Rr:{id:$,status:"pending"};xe.name=V!=null?V:xe.name,xe.status="running",k.parameters!==void 0?xe.args=k.parameters:k.args!==void 0&&(xe.args=k.args),xe.startedAt=(on=xe.startedAt)!=null?on:Q((eo=k.startedAt)!=null?eo:k.timestamp),xe.completedAt=void 0,xe.durationMs=void 0,G.toolCall=xe,G.streaming=!0,k.executionId&&(G.agentMetadata={executionId:k.executionId,iteration:k.iteration}),u(G)}else if(Ze==="tool_output_delta"){let $=(Ao=(wt=De(k,!1))!=null?wt:De(k,!0))!=null?Ao:`tool-${l()}`;if(Ce.has($))continue;let V=j($),G=(Mo=V.toolCall)!=null?Mo:{id:$,status:"running"};G.startedAt=(uo=G.startedAt)!=null?uo:Q((_o=k.startedAt)!=null?_o:k.timestamp);let xe=(To=(Rn=(pt=k.text)!=null?pt:k.delta)!=null?Rn:k.message)!=null?To:"";xe&&(G.chunks=(In=G.chunks)!=null?In:[],G.chunks.push(String(xe))),G.status="running",V.toolCall=G,V.streaming=!0;let Oe=k.agentContext;(Oe||k.executionId)&&(V.agentMetadata=(nn=V.agentMetadata)!=null?nn:{executionId:(Ir=Oe==null?void 0:Oe.executionId)!=null?Ir:k.executionId,iteration:(da=Oe==null?void 0:Oe.iteration)!=null?da:k.iteration}),u(V)}else if(Ze==="tool_complete"){let $=(an=(Uo=De(k,!1))!=null?Uo:De(k,!0))!=null?an:`tool-${l()}`;if(Ce.has($)){Ce.delete($);continue}let V=j($),G=(sn=V.toolCall)!=null?sn:{id:$,status:"running"};G.status="complete",k.result!==void 0&&(G.result=k.result),typeof k.duration=="number"&&(G.duration=k.duration),G.completedAt=Q((Wn=k.completedAt)!=null?Wn:k.timestamp);let xe=(Hn=k.duration)!=null?Hn:k.executionTime;if(typeof xe=="number")G.durationMs=xe;else{let nt=(ln=G.startedAt)!=null?ln:Date.now();G.durationMs=Math.max(0,((xt=G.completedAt)!=null?xt:Date.now())-nt)}V.toolCall=G,V.streaming=!1;let Oe=k.agentContext;(Oe||k.executionId)&&(V.agentMetadata=(Mr=V.agentMetadata)!=null?Mr:{executionId:(Or=Oe==null?void 0:Oe.executionId)!=null?Or:k.executionId,iteration:(_r=Oe==null?void 0:Oe.iteration)!=null?_r:k.iteration}),u(V);let ft=O(k);ft&&H.byCall.delete(ft)}else if(Ze==="await"&&k.toolName){let $=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,V=(Ct=$!=null?$:k.toolId)!=null?Ct:`local-${l()}`,G=j(V),xe=k.toolName,Oe=k.origin==="webmcp"&&!yn(xe)?`webmcp:${xe}`:xe,ft=yn(Oe),nt=(to=G.toolCall)!=null?to:{id:V,status:"pending"};nt.name=Oe,nt.args=k.parameters,nt.status=ft?"running":"complete",nt.chunks=(ro=nt.chunks)!=null?ro:[],nt.startedAt=(qo=nt.startedAt)!=null?qo:Q((dn=(Ur=k.startedAt)!=null?Ur:k.timestamp)!=null?dn:k.awaitedAt),ft?(nt.completedAt=void 0,nt.duration=void 0,nt.durationMs=void 0):nt.completedAt=(cn=nt.completedAt)!=null?cn:nt.startedAt,G.toolCall=nt,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(It=k.executionId)!=null?It:(qr=G.agentMetadata)==null?void 0:qr.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},u(G)}else if(Ze==="text_start"){let $=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if($&&V){T.set($,V);continue}let G=m;G&&(Me==="flow"?(Ye(G),Ot=G):(G.streaming=!1,u(G)),m=null),E=typeof k.id=="string"?k.id:E,A=""}else if(Ze==="text_delta"){let $=typeof k.id=="string"?k.id:null,V=$?T.get($):void 0;if($&&V){let xe=typeof k.delta=="string"?k.delta:"",Oe=((Tr=S.get($))!=null?Tr:"")+xe;if(S.set($,Oe),Oe.trim()==="")continue;let ft=ge($,V);ft.agentMetadata={...ft.agentMetadata,executionId:k.executionId,parentToolId:V},Qt(ft,Oe,xe,void 0);continue}if(E=typeof k.id=="string"?k.id:E,Me==="flow"){let xe=typeof k.delta=="string"?k.delta:"";if(A+=xe,A.trim()==="")continue;let Oe=de();Oe.agentMetadata={executionId:k.executionId,iteration:k.iteration},Qt(Oe,A,xe,void 0),x=Oe;continue}let G=de();G.content+=(oo=k.delta)!=null?oo:"",G.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:Pt!=null?Pt:void 0,agentName:Z==null?void 0:Z.agentName},x=G,u(G)}else if(Ze==="text_complete"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)){let G=y.get($);G&&Ye(G),T.delete($),S.delete($),y.delete($);continue}let V=m;V&&(Me==="flow"?(Ye(V),Ot=V):(((pn=V.content)!=null?pn:"")===""&&typeof k.text=="string"&&(V.content=k.text),V.streaming=!1,u(V)),m=null),E=null,A=""}else if(Ze==="step_complete"){let $=k.stepType,V=k.executionType;if($==="tool"||V==="context")continue;if(k.success===!1){let G=k.error,xe=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((Vo=G.message)!=null?Vo:"Step failed"):"Step failed";r({type:"error",error:new Error(xe)});let Oe=m;Oe&&Oe.streaming&&(Oe.streaming=!1,u(Oe)),r({type:"status",status:"idle"});continue}{let G=Ot;Ot=null;let xe=k.stopReason,Oe=(un=k.result)==null?void 0:un.response;if(G)xe&&(G.stopReason=xe),Oe!=null?yt(G,Oe):G.streaming!==!1&&(K.delete(G.id),ce.delete(G.id),G.streaming=!1,u(G));else{let ft=Oe!=null&&Oe!=="";if(ft||xe){let nt=de();xe&&(nt.stopReason=xe),ft?Ye(nt,Oe):(nt.streaming=!1,u(nt))}}continue}}else if(Ze==="execution_start")Me=k.kind==="flow"?"flow":"agent",et=!0,Me==="agent"&&(Z={executionId:k.executionId,agentId:(ye=k.agentId)!=null?ye:"virtual",agentName:(Wr=k.agentName)!=null?Wr:"",status:"running",currentIteration:0,maxTurns:(Eo=k.maxTurns)!=null?Eo:1,startedAt:Q(k.startedAt)});else if(Ze==="turn_start"){let $=typeof k.iteration=="number"?k.iteration:ve;if($!==ve){if(Z&&(Z.currentIteration=$),Ar==="separate"&&$>1){let V=m;V&&(V.streaming=!1,u(V),Ue.set($-1,V),m=null)}ve=$}Pt=typeof k.id=="string"?k.id:null,x=null}else if(Ze==="tool_input_delta"){let $=(ut=k.toolCallId)!=null?ut:H.lastId;if($){let V=M.get($);V!=null&&V.toolCall&&(V.toolCall.chunks=(ar=V.toolCall.chunks)!=null?ar:[],V.toolCall.chunks.push((sr=k.delta)!=null?sr:""),u(V))}}else{if(Ze==="tool_input_complete")continue;if(Ze==="turn_complete"){let $=k.stopReason,V=m!=null?m:x;if($&&V!==null){let G=k.id;(!G||((ko=V.agentMetadata)==null?void 0:ko.turnId)===G)&&(V.stopReason=$,u(V))}Pt===k.id&&(Pt=null)}else if(Ze==="media_start"){let $=String(k.id);ze.set($,{mediaType:typeof k.mediaType=="string"?k.mediaType:void 0,role:typeof k.role=="string"?k.role:void 0,toolCallId:k.toolCallId,parts:[]})}else if(Ze==="media_delta"){let $=ze.get(String(k.id));$&&typeof k.delta=="string"&&$.parts.push(k.delta)}else if(Ze==="media_complete"){let $=String(k.id),V=ze.get($);ze.delete($);let G=(zo=($a=typeof k.mediaType=="string"?k.mediaType:void 0)!=null?$a:V==null?void 0:V.mediaType)!=null?zo:"application/octet-stream",xe=typeof k.data=="string"?k.data:void 0,Oe=typeof k.url=="string"?k.url:V&&V.parts.length>0?V.parts.join(""):void 0,ft=null;if(xe)ft={type:"media",data:xe,mediaType:G};else if(Oe){let pr=G.toLowerCase();ft={type:pr==="image"||pr.startsWith("image/")?"image-url":"file-url",url:Oe,mediaType:G}}let nt=(Bn=k.toolCallId)!=null?Bn:V==null?void 0:V.toolCallId,Ga=ft?[ft]:[],Br=[];for(let pr of Ga){if(!pr||typeof pr!="object")continue;let ur=pr,Nn=typeof ur.type=="string"?ur.type:void 0,Go=typeof ur.mediaType=="string"?ur.mediaType.toLowerCase():"",Er=null,hr="";if(Nn==="media"){let $r=typeof ur.data=="string"?ur.data:void 0;if(!$r)continue;hr=Go.length>0?Go:"application/octet-stream",Er=`data:${hr};base64,${$r}`}else if(Nn==="image-url"){let $r=typeof ur.url=="string"?ur.url:void 0;if(!$r)continue;hr=Go,Er=$r}else if(Nn==="file-url"){let $r=typeof ur.url=="string"?ur.url:void 0;if(!$r)continue;hr=Go,Er=$r}else continue;if(Er)if(Nn==="image-url"||hr.startsWith("image/"))Br.push({type:"image",image:Er,...hr.includes("/")?{mimeType:hr}:{}});else if(hr.startsWith("audio/"))Br.push({type:"audio",audio:Er,mimeType:hr});else if(hr.startsWith("video/"))Br.push({type:"video",video:Er,mimeType:hr});else{let $r=hr||"application/octet-stream";Br.push({type:"file",data:Er,mimeType:$r,filename:cb($r)})}}if(Br.length>0){let pr=l(),ur=nt,Go={id:`agent-media-${typeof ur=="string"&&ur.length>0?`${ur}-${pr}`:String(pr)}`,role:"assistant",content:"",contentParts:Br,createdAt:new Date().toISOString(),streaming:!1,sequence:pr,agentMetadata:{executionId:k.executionId,iteration:typeof k.iteration=="number"?k.iteration:ve}};u(Go);let Er=m;Er&&(Er.streaming=!1,u(Er)),m=null,b.current=null}}else if(Ze==="execution_complete"){let $=(Lo=k.kind)!=null?Lo:Me;$==="agent"&&Z&&(Z.status=k.success?"complete":"error",Z.completedAt=Q(k.completedAt),Z.stopReason=k.stopReason);let V=m;V&&($==="flow"&&V.streaming!==!1?Ye(V):(V.streaming=!1,u(V)),m=null),E=null,A="",Ot=null,r({type:"status",status:"idle"})}else if(Ze==="execution_error"){let $=typeof k.error=="string"?k.error:(ca=(q=k.error)==null?void 0:q.message)!=null?ca:"Execution error";r({type:"error",error:new Error($)})}else if(Ze!=="ping"){if(Ze==="approval_start"){let $=(Po=k.approvalId)!=null?Po:`approval-${l()}`,V={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ro=Z==null?void 0:Z.agentId)!=null?Ro:"virtual",executionId:(Io=($o=k.executionId)!=null?$o:Z==null?void 0:Z.executionId)!=null?Io:"",toolName:(fo=k.toolName)!=null?fo:"",toolType:k.toolType,description:(Fs=k.description)!=null?Fs:`Execute ${(pa=k.toolName)!=null?pa:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ze==="step_await"&&k.awaitReason==="approval_required"){let $=(Vr=k.approvalId)!=null?Vr:`approval-${l()}`,V={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(zr=Z==null?void 0:Z.agentId)!=null?zr:"virtual",executionId:(go=(mo=k.executionId)!=null?mo:Z==null?void 0:Z.executionId)!=null?go:"",toolName:(Dn=k.toolName)!=null?Dn:"",toolType:k.toolType,description:(vr=k.description)!=null?vr:`Execute ${(jo=k.toolName)!=null?jo:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ze==="approval_complete"){let $=k.approvalId;if($){let G={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(Wo=k.decision)!=null?Wo:"approved",agentId:(ua=Z==null?void 0:Z.agentId)!=null?ua:"virtual",executionId:(fa=(Fn=k.executionId)!=null?Fn:Z==null?void 0:Z.executionId)!=null?fa:"",toolName:(Ns=k.toolName)!=null?Ns:"",description:(ma=k.description)!=null?ma:"",resolvedAt:Date.now()}};u(G)}}else if(Ze==="artifact_start"||Ze==="artifact_delta"||Ze==="artifact_update"||Ze==="artifact_complete"){if(Ze==="artifact_start"){let $=k.artifactType,V=String(k.id),G=typeof k.title=="string"?k.title:void 0;if(r({type:"artifact_start",id:V,artifactType:$,title:G,component:typeof k.component=="string"?k.component:void 0}),pe.set(V,{markdown:"",title:G}),!ie.has(V)){ie.add(V);let xe={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:V,title:G,artifactType:$,status:"streaming"}})};se.set(V,xe),u(xe)}}else if(Ze==="artifact_delta"){let $=String(k.id),V=typeof k.delta=="string"?k.delta:String((Os=k.delta)!=null?Os:"");r({type:"artifact_delta",id:$,artDelta:V});let G=pe.get($);G&&(G.markdown+=V)}else if(Ze==="artifact_update"){let $=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};r({type:"artifact_update",id:String(k.id),props:$,component:typeof k.component=="string"?k.component:void 0})}else if(Ze==="artifact_complete"){let $=String(k.id);r({type:"artifact_complete",id:$});let V=se.get($);if(V){V.streaming=!1;try{let G=JSON.parse((ga=V.rawContent)!=null?ga:"{}");if(G.props){G.props.status="complete";let xe=pe.get($);xe!=null&&xe.markdown&&(G.props.markdown=xe.markdown)}V.rawContent=JSON.stringify(G)}catch{}pe.delete($),u(V),se.delete($)}}}else if(Ze==="transcript_insert"){let $=k.message;if(!$||typeof $!="object")continue;let V=String((ct=$.id)!=null?ct:`msg-${l()}`),G=$.role,Oe={id:V,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:l()};if(u(Oe),Oe.rawContent)try{let ft=JSON.parse(Oe.rawContent),nt=(ja=ft==null?void 0:ft.props)==null?void 0:ja.artifactId;typeof nt=="string"&&ie.add(nt)}catch{}m=null,b.current=null,K.delete(V),ce.delete(V)}else if(Ze==="error"){if(k.recoverable===!1&&k.error!=null&&k.error!==""){let $=typeof k.error=="string"?k.error:((no=k.error)==null?void 0:no.message)!=null?String(k.error.message):"Execution error";r({type:"error",error:new Error($)});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}else if(Ze==="step_error"||Ze==="dispatch_error"||Ze==="flow_error"){let $=null;if(k.error instanceof Error)$=k.error;else if(Ze==="dispatch_error"){let V=(Hr=k.message)!=null?Hr:k.error;V!=null&&V!==""&&($=new Error(String(V)))}else{let V=k.error;typeof V=="string"&&V!==""?$=new Error(V):V!=null&&typeof V=="object"&&"message"in V&&($=new Error(String((_s=V.message)!=null?_s:V)))}if($){r({type:"error",error:$});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}}}}X.length=0};;){let{done:P,value:ee}=await n.read();if(P)break;s+=a.decode(ee,{stream:!0});let Se=s.split(`
12
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Cs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},fi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},mi=()=>{var t;let e=Tb();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)}},gi=()=>{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"?di(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=di(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Yg=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?di(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?di(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:()=>{}}},hi=()=>{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 Zg="4.5.0";var na=Zg;var kb="https://api.runtype.com/v1/dispatch",xi="https://api.runtype.com";function Lb(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 Gl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Pb(e){switch(e){case"json":return gi;case"regex-json":return mi;case"xml":return hi;default:return fi}}var eh=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Rb(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=eh(r);if(!eh(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=Cs(e);return Cs(t)!==null&&s===null?t:e}var aa=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(r=t.apiUrl)!=null?r:kb,this.headers={"Content-Type":"application/json","X-Persona-Version":na,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Pb(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 Ia(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}routing(){let{agentId:t,flowId:r,target:o,targetProviders:n}=this.config;if(!o)return{agentId:t,flowId:r};let a=Hg(o,n);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/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 i,c,l;let t=((c=(i=this.config).getStoredSessionId)==null?void 0:c.call(i))||null,r=this.routing(),o=(l=r.agentId)!=null?l:r.flowId,n={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":na},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):a.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/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":na},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.isClientTokenMode()?this.dispatchClientToken(t,r):this.isAgentMode()?this.dispatchAgent(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,f={sessionId:c.sessionId,messages:t.messages.filter(Gl).map(y=>{var S,v,M;return{id:y.id,role:y.role,content:(M=(v=(S=y.contentParts)!=null?S:y.llmContent)!=null?v:y.rawContent)!=null?M:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},u=l.clientTools,g=!!(u&&u.length>0),x=g?Ig(u):void 0,b=this.clientToolsFingerprintSessionId===c.sessionId,L=g&&b&&this.lastSentClientToolsFingerprint===x,E=!1,A=null,T;for(let y=0;;y++){let v={...f,...g&&(E||!L)&&u?{clientTools:u}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":na},body:JSON.stringify(v),signal:o.signal}),T.status===409&&y===0&&g){let M=await T.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=M!=null?M:{error:"Chat request failed"}}break}if(!T.ok){let y=A!=null?A:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(T.status===429){let v=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let S=new Error(y.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!T.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(T.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let l=c instanceof Error?c:new Error(String(c));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var l,p;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||xi}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,i,c;let r=this.routing().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Gl).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let f=new Date(l.createdAt).getTime(),u=new Date(p.createdAt).getTime();return f-u}).map(l=>{var p,f,u;return{role:l.role,content:(u=(f=(p=l.contentParts)!=null?p:l.llmContent)!=null?f:l.rawContent)!=null?u:l.content,createdAt:l.createdAt}}),n={agent:(s=this.config.agent)!=null?s:{agentId:r},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...bs(this.config),...(c=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?c:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let f=await p({messages:t,config:this.config});f&&typeof f=="object"&&Object.assign(l,f)}catch(f){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",f)}})),Object.keys(l).length&&(n.context=l)}return n}async buildPayload(t){var s,i;let r=t.slice().filter(Gl).sort((c,l)=>{let p=new Date(c.createdAt).getTime(),f=new Date(l.createdAt).getTime();return p-f}).map(c=>{var l,p,f;return{role:c.role,content:(f=(p=(l=c.contentParts)!=null?l:c.llmContent)!=null?p:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o=this.routing(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[c,l]of Object.entries(o.targetPayload))c!=="messages"&&(n[c]=l);let a=[...bs(this.config),...(i=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?i:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(c,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(c).length&&(n.context=c)}if(this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...n},config:this.config});if(c&&typeof c=="object"){let l=c;return n.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=n.clientTools),l}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",c)}return n}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=f,n(f),f},l=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var yt,xr,Ao,Mo;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,l=()=>i+c++,p=P=>{let ee=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,Me=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,He=P.tools?P.tools.map(Le=>({...Le,chunks:Le.chunks?[...Le.chunks]:void 0})):void 0;return{...P,reasoning:ee,toolCall:Me,tools:He}},f=P=>{if(P.role!=="assistant"||P.variant)return!0;let ee=Array.isArray(P.contentParts)&&P.contentParts.length>0,Me=typeof P.rawContent=="string"&&P.rawContent.trim()!=="";return typeof P.content=="string"&&P.content.trim()!==""||ee||Me||!!P.stopReason},u=P=>{f(P)&&r({type:"message",message:p(P)})},g=null,x=null,b={current:null},L={current:null},E=null,A="",T=new Map,y=new Map,S=new Map,v=new Map,M=new Map,W={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},I=P=>{if(P==null)return null;try{return String(P)}catch{return null}},F=P=>{var ee,Me,He,Le,Be;return I((Be=(Le=(He=(Me=(ee=P.stepId)!=null?ee:P.step_id)!=null?Me:P.step)!=null?He:P.parentId)!=null?Le:P.flowStepId)!=null?Be:P.flow_step_id)},O=P=>{var ee,Me,He,Le,Be,Ge,at;return I((at=(Ge=(Be=(Le=(He=(Me=(ee=P.callId)!=null?ee:P.call_id)!=null?Me:P.requestId)!=null?He:P.request_id)!=null?Le:P.toolCallId)!=null?Be:P.tool_call_id)!=null?Ge:P.stepId)!=null?at:P.step_id)},Q=o,he=!1,ce=()=>{if(g)return g;let P,ee=E;return!he&&Q?(P=Q,he=!0):Q&&ee?P=`${Q}_${ee}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:P,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(g),g},te=(P,ee)=>{W.lastId=ee,P&&W.byStep.set(P,ee)},Te=(P,ee)=>{var Be;let Me=(Be=P.reasoningId)!=null?Be:P.id,He=F(P);if(Me){let Ge=String(Me);return te(He,Ge),Ge}if(He){let Ge=W.byStep.get(He);if(Ge)return W.lastId=Ge,Ge}if(W.lastId&&!ee)return W.lastId;if(!ee)return null;let Le=`reason-${l()}`;return te(He,Le),Le},We=P=>{let ee=v.get(P);if(ee)return ee;let Me={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:P,status:"streaming",chunks:[]}};return v.set(P,Me),u(Me),Me},de=(P,ee)=>{H.lastId=ee,P&&H.byCall.set(P,ee)},Ae=new Set,ne=new Map,le=new Set,ue=new Map,ke=P=>{if(!P)return!1;let ee=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},Fe=(P,ee)=>{var Be;let Me=(Be=P.toolId)!=null?Be:P.id,He=O(P);if(Me){let Ge=String(Me);return de(He,Ge),Ge}if(He){let Ge=H.byCall.get(He);if(Ge)return H.lastId=Ge,Ge}if(H.lastId&&!ee)return H.lastId;if(!ee)return null;let Le=`tool-${l()}`;return de(He,Le),Le},j=P=>{let ee=M.get(P);if(ee)return ee;let Me={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:P,status:"pending"}};return M.set(P,Me),u(Me),Me},J=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let ee=Number(P);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let Me=Date.parse(P);if(!Number.isNaN(Me))return Me}return Date.now()},Ne=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},K=new Map,pe=new Map,qe=new Map,ot=(P,ee,Me)=>{var at;let He=qe.get(P);He||(He=[],qe.set(P,He));let Le=0,Be=He.length;for(;Le<Be;){let Pt=Le+Be>>>1;He[Pt].seq<ee?Le=Pt+1:Be=Pt}((at=He[Le])==null?void 0:at.seq)===ee?He[Le]={seq:ee,text:Me}:He.splice(Le,0,{seq:ee,text:Me});let Ge="";for(let Pt=0;Pt<He.length;Pt++)Ge+=He[Pt].text;return Ge},xt=(P,ee)=>{let Me=Ne(ee),He=pe.get(P.id),Le=Rb(He,Me);P.rawContent=Le;let Be=K.get(P.id),Ge=ye=>{var bt;let Oe=(bt=P.content)!=null?bt:"";ye.trim()!==""&&(Oe.trim().length===0||ye.startsWith(Oe)||ye.trimStart().startsWith(Oe.trim()))&&(P.content=ye)},at=()=>{var ye;if(Be){let Oe=(ye=Be.close)==null?void 0:ye.call(Be);Oe instanceof Promise&&Oe.catch(()=>{})}K.delete(P.id),pe.delete(P.id),P.streaming=!1,u(P)};if(!Be){Ge(Me),at();return}let Pt=Cs(Le);if(Pt!==null&&Pt.trim()!==""){Ge(Pt),at();return}let se=ye=>{var Qe;let Oe=typeof ye=="string"?ye:(Qe=ye==null?void 0:ye.text)!=null?Qe:null;if(Oe!==null&&Oe.trim()!=="")return Oe;let bt=Be.getExtractedText();return bt!==null&&bt.trim()!==""?bt:Me},N;try{N=Be.processChunk(Le)}catch{Ge(Me),at();return}if(N instanceof Promise){N.then(ye=>{Ge(se(ye)),at()}).catch(()=>{Ge(Me),at()});return}Ge(se(N)),at()},Ft=null,Qt=(P,ee,Me,He)=>{var Pt;P.rawContent=ee,K.has(P.id)||K.set(P.id,this.createStreamParser());let Le=K.get(P.id),Be=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(Be&&pe.set(P.id,ee),Le.__isPlainTextParser===!0){P.content=He!==void 0?ee:P.content+Me,pe.delete(P.id),K.delete(P.id),P.rawContent=void 0,u(P);return}let at=Le.processChunk(ee);if(at instanceof Promise)at.then(se=>{var ye;let N=typeof se=="string"?se:(ye=se==null?void 0:se.text)!=null?ye:null;N!==null&&N.trim()!==""?(P.content=N,u(P)):!Be&&!ee.trim().startsWith("<")&&(P.content=He!==void 0?ee:P.content+Me,pe.delete(P.id),K.delete(P.id),P.rawContent=void 0,u(P))}).catch(()=>{P.content=He!==void 0?ee:P.content+Me,pe.delete(P.id),K.delete(P.id),P.rawContent=void 0,u(P)});else{let se=typeof at=="string"?at:(Pt=at==null?void 0:at.text)!=null?Pt:null;se!==null&&se.trim()!==""?(P.content=se,u(P)):!Be&&!ee.trim().startsWith("<")&&(P.content=He!==void 0?ee:P.content+Me,pe.delete(P.id),K.delete(P.id),P.rawContent=void 0,u(P))}},Ye=(P,ee)=>{var Pt,se;let Me=ee!=null?ee:P.content;if(Me==null||Me===""){P.streaming=!1,u(P);return}let He=pe.get(P.id),Le=He!=null?He:Ne(Me);P.rawContent=Le;let Be=K.get(P.id),Ge=null,at=!1;if(Be&&(Ge=Be.getExtractedText(),Ge===null&&(Ge=Cs(Le)),Ge===null)){let N=Be.processChunk(Le);N instanceof Promise?(at=!0,N.then(ye=>{var bt;let Oe=typeof ye=="string"?ye:(bt=ye==null?void 0:ye.text)!=null?bt:null;Oe!==null&&(P.content=Oe,P.streaming=!1,K.delete(P.id),pe.delete(P.id),u(P))}).catch(()=>{})):Ge=typeof N=="string"?N:(Pt=N==null?void 0:N.text)!=null?Pt:null}if(!at){Ge!==null&&Ge.trim()!==""?P.content=Ge:pe.has(P.id)||(P.content=Ne(Me));let N=K.get(P.id);if(N){let ye=(se=N.close)==null?void 0:se.call(N);ye instanceof Promise&&ye.catch(()=>{}),K.delete(P.id)}pe.delete(P.id),P.streaming=!1,u(P)}},xe=(P,ee,Me)=>{let He=y.get(P);if(He)return He;let Le={id:`nested-${ee}-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:P,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return y.set(P,Le),u(Le),Le},X=[],dt,$e=new Map,Ce=0,be="agent",et=!1,Lt=null,Z=null,Ue=new Map,Sr=(yt=this.config.iterationDisplay)!=null?yt:"separate";for(dt=()=>{var P,ee,Me,He,Le,Be,Ge,at,Pt,se,N,ye,Oe,bt,Qe,Wt,At,gt,kt,Xt,Ot,tr,To,zo,lo,co,dn,$t,po,jo,Hr,Rr,Br,uo,Eo,cn,Xr,pn,vt,ko,Lo,Go,fo,pt,_n,Po,Un,Ir,xa,un,Ko,fn,mn,qn,Vn,gn,ht,Dr,Fr,Ar,wt,Qr,Jr,Nr,hn,we,Xo,Yr,_t,Zr,Qo,Ja,ya,Ya,$n,Ro,xn,st,ar,sr,Io,Za,Jo,zn,Wo,q,ba,mo,Ho,Yo,Bo,go,va,zs,yr,Mr,ho,Tr,jn,xo,br,Do,wa,Gn,Ca;for(let Fo=0;Fo<X.length;Fo++){let Ze=X[Fo].payloadType,k=X[Fo].payload;if(!et&&be!=="flow"&&typeof k.stepType=="string"&&(be="flow"),Ze==="reasoning_start"){let z=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if(z&&V){T.set(z,V),xe(z,V,"reasoning");continue}let G=(P=Te(k,!0))!=null?P:`reason-${l()}`,me=We(G);me.reasoning=(ee=me.reasoning)!=null?ee:{id:G,status:"streaming",chunks:[]},me.reasoning.startedAt=(He=me.reasoning.startedAt)!=null?He:J((Me=k.startedAt)!=null?Me:k.timestamp),me.reasoning.completedAt=void 0,me.reasoning.durationMs=void 0,(k.scope==="loop"||k.scope==="turn")&&(me.reasoning.scope=k.scope),me.streaming=!0,me.reasoning.status="streaming",u(me)}else if(Ze==="reasoning_delta"){let z=typeof k.id=="string"?k.id:null;if(z&&T.has(z)&&y.has(z)){let oe=y.get(z),ut=(Ge=(Be=(Le=k.reasoningText)!=null?Le:k.text)!=null?Be:k.delta)!=null?Ge:"";ut&&k.hidden!==!0&&oe.reasoning&&(oe.reasoning.chunks.push(String(ut)),u(oe));continue}let V=(Pt=(at=Te(k,!1))!=null?at:Te(k,!0))!=null?Pt:`reason-${l()}`,G=We(V);G.reasoning=(se=G.reasoning)!=null?se:{id:V,status:"streaming",chunks:[]},G.reasoning.startedAt=(ye=G.reasoning.startedAt)!=null?ye:J((N=k.startedAt)!=null?N:k.timestamp);let me=(Qe=(bt=(Oe=k.reasoningText)!=null?Oe:k.text)!=null?bt:k.delta)!=null?Qe:"";if(me&&k.hidden!==!0){let oe=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(oe!==void 0){let ut=ot(V,oe,String(me));G.reasoning.chunks=[ut]}else G.reasoning.chunks.push(String(me))}if(G.reasoning.status=k.done?"complete":"streaming",k.done){G.reasoning.completedAt=J((Wt=k.completedAt)!=null?Wt:k.timestamp);let oe=(At=G.reasoning.startedAt)!=null?At:Date.now();G.reasoning.durationMs=Math.max(0,((gt=G.reasoning.completedAt)!=null?gt:Date.now())-oe)}G.streaming=G.reasoning.status!=="complete",u(G)}else if(Ze==="reasoning_complete"){let z=typeof k.id=="string"?k.id:null;if(z&&T.has(z)&&y.has(z)){let ut=y.get(z);if(ut.reasoning){let ct=typeof k.text=="string"?k.text:"";ct&&ut.reasoning.chunks.length===0&&ut.reasoning.chunks.push(ct),ut.reasoning.status="complete",ut.streaming=!1,u(ut)}T.delete(z),y.delete(z);continue}let V=(Xt=(kt=Te(k,!1))!=null?kt:Te(k,!0))!=null?Xt:`reason-${l()}`,G=typeof k.text=="string"?k.text:"";!v.get(V)&&(G||k.scope==="loop")&&We(V);let me=v.get(V);if(me!=null&&me.reasoning){(k.scope==="loop"||k.scope==="turn")&&(me.reasoning.scope=k.scope),G&&me.reasoning.chunks.length===0&&me.reasoning.chunks.push(G),me.reasoning.status="complete",me.reasoning.completedAt=J((Ot=k.completedAt)!=null?Ot:k.timestamp);let ut=(tr=me.reasoning.startedAt)!=null?tr:Date.now();me.reasoning.durationMs=Math.max(0,((To=me.reasoning.completedAt)!=null?To:Date.now())-ut),me.streaming=!1,u(me)}let oe=F(k);oe&&W.byStep.delete(oe)}else if(Ze==="tool_start"){g&&(g.streaming=!1,u(g),g=null),typeof k.iteration=="number"&&(Ce=k.iteration);let z=(lo=(zo=typeof k.toolCallId=="string"?k.toolCallId:void 0)!=null?zo:Fe(k,!0))!=null?lo:`tool-${l()}`,V=(co=k.toolName)!=null?co:k.name;if(ke(V)){Ae.add(z);continue}de(O(k),z);let G=j(z),me=(dn=G.toolCall)!=null?dn:{id:z,status:"pending"};me.name=V!=null?V:me.name,me.status="running",k.parameters!==void 0?me.args=k.parameters:k.args!==void 0&&(me.args=k.args),me.startedAt=(po=me.startedAt)!=null?po:J(($t=k.startedAt)!=null?$t:k.timestamp),me.completedAt=void 0,me.durationMs=void 0,G.toolCall=me,G.streaming=!0,k.executionId&&(G.agentMetadata={executionId:k.executionId,iteration:k.iteration}),u(G)}else if(Ze==="tool_output_delta"){let z=(Hr=(jo=Fe(k,!1))!=null?jo:Fe(k,!0))!=null?Hr:`tool-${l()}`;if(Ae.has(z))continue;let V=j(z),G=(Rr=V.toolCall)!=null?Rr:{id:z,status:"running"};G.startedAt=(uo=G.startedAt)!=null?uo:J((Br=k.startedAt)!=null?Br:k.timestamp);let me=(Xr=(cn=(Eo=k.text)!=null?Eo:k.delta)!=null?cn:k.message)!=null?Xr:"";me&&(G.chunks=(pn=G.chunks)!=null?pn:[],G.chunks.push(String(me))),G.status="running",V.toolCall=G,V.streaming=!0;let oe=k.agentContext;(oe||k.executionId)&&(V.agentMetadata=(Lo=V.agentMetadata)!=null?Lo:{executionId:(vt=oe==null?void 0:oe.executionId)!=null?vt:k.executionId,iteration:(ko=oe==null?void 0:oe.iteration)!=null?ko:k.iteration}),u(V)}else if(Ze==="tool_complete"){let z=(fo=(Go=Fe(k,!1))!=null?Go:Fe(k,!0))!=null?fo:`tool-${l()}`;if(Ae.has(z)){Ae.delete(z);continue}let V=j(z),G=(pt=V.toolCall)!=null?pt:{id:z,status:"running"};G.status="complete",k.result!==void 0&&(G.result=k.result),typeof k.duration=="number"&&(G.duration=k.duration),G.completedAt=J((_n=k.completedAt)!=null?_n:k.timestamp);let me=(Po=k.duration)!=null?Po:k.executionTime;if(typeof me=="number")G.durationMs=me;else{let ct=(Un=G.startedAt)!=null?Un:Date.now();G.durationMs=Math.max(0,((Ir=G.completedAt)!=null?Ir:Date.now())-ct)}V.toolCall=G,V.streaming=!1;let oe=k.agentContext;(oe||k.executionId)&&(V.agentMetadata=(Ko=V.agentMetadata)!=null?Ko:{executionId:(xa=oe==null?void 0:oe.executionId)!=null?xa:k.executionId,iteration:(un=oe==null?void 0:oe.iteration)!=null?un:k.iteration}),u(V);let ut=O(k);ut&&H.byCall.delete(ut)}else if(Ze==="await"&&k.toolName){let z=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,V=(fn=z!=null?z:k.toolId)!=null?fn:`local-${l()}`,G=j(V),me=k.toolName,oe=k.origin==="webmcp"&&!Tn(me)?`webmcp:${me}`:me,ut=Tn(oe),ct=(mn=G.toolCall)!=null?mn:{id:V,status:"pending"};ct.name=oe,ct.args=k.parameters,ct.status=ut?"running":"complete",ct.chunks=(qn=ct.chunks)!=null?qn:[],ct.startedAt=(ht=ct.startedAt)!=null?ht:J((gn=(Vn=k.startedAt)!=null?Vn:k.timestamp)!=null?gn:k.awaitedAt),ut?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Dr=ct.completedAt)!=null?Dr:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Ar=k.executionId)!=null?Ar:(Fr=G.agentMetadata)==null?void 0:Fr.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},u(G)}else if(Ze==="text_start"){let z=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if(z&&V){T.set(z,V);continue}let G=g;G&&(be==="flow"?(Ye(G),Ft=G):(G.streaming=!1,u(G)),g=null),E=typeof k.id=="string"?k.id:E,A=""}else if(Ze==="text_delta"){let z=typeof k.id=="string"?k.id:null,V=z?T.get(z):void 0;if(z&&V){let me=typeof k.delta=="string"?k.delta:"",oe=((wt=S.get(z))!=null?wt:"")+me;if(S.set(z,oe),oe.trim()==="")continue;let ut=xe(z,V);ut.agentMetadata={...ut.agentMetadata,executionId:k.executionId,parentToolId:V},Qt(ut,oe,me,void 0);continue}if(E=typeof k.id=="string"?k.id:E,be==="flow"){let me=typeof k.delta=="string"?k.delta:"";if(A+=me,A.trim()==="")continue;let oe=ce();oe.agentMetadata={executionId:k.executionId,iteration:k.iteration},Qt(oe,A,me,void 0),x=oe;continue}let G=ce();G.content+=(Qr=k.delta)!=null?Qr:"",G.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:Lt!=null?Lt:void 0,agentName:Z==null?void 0:Z.agentName},x=G,u(G)}else if(Ze==="text_complete"){let z=typeof k.id=="string"?k.id:null;if(z&&T.has(z)){let G=y.get(z);G&&Ye(G),T.delete(z),S.delete(z),y.delete(z);continue}let V=g;V&&(be==="flow"?(Ye(V),Ft=V):(((Jr=V.content)!=null?Jr:"")===""&&typeof k.text=="string"&&(V.content=k.text),V.streaming=!1,u(V)),g=null),E=null,A=""}else if(Ze==="step_complete"){let z=k.stepType,V=k.executionType;if(z==="tool"||V==="context")continue;if(k.success===!1){let G=k.error,me=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((Nr=G.message)!=null?Nr:"Step failed"):"Step failed";r({type:"error",error:new Error(me)});let oe=g;oe&&oe.streaming&&(oe.streaming=!1,u(oe)),r({type:"status",status:"idle"});continue}{let G=Ft;Ft=null;let me=k.stopReason,oe=(hn=k.result)==null?void 0:hn.response;if(G)me&&(G.stopReason=me),oe!=null?xt(G,oe):G.streaming!==!1&&(K.delete(G.id),pe.delete(G.id),G.streaming=!1,u(G));else{let ut=oe!=null&&oe!=="";if(ut||me){let ct=ce();me&&(ct.stopReason=me),ut?Ye(ct,oe):(ct.streaming=!1,u(ct))}}continue}}else if(Ze==="execution_start")be=k.kind==="flow"?"flow":"agent",et=!0,be==="agent"&&(Z={executionId:k.executionId,agentId:(we=k.agentId)!=null?we:"virtual",agentName:(Xo=k.agentName)!=null?Xo:"",status:"running",currentIteration:0,maxTurns:(Yr=k.maxTurns)!=null?Yr:1,startedAt:J(k.startedAt)});else if(Ze==="turn_start"){let z=typeof k.iteration=="number"?k.iteration:Ce;if(z!==Ce){if(Z&&(Z.currentIteration=z),Sr==="separate"&&z>1){let V=g;V&&(V.streaming=!1,u(V),Ue.set(z-1,V),g=null)}Ce=z}Lt=typeof k.id=="string"?k.id:null,x=null}else if(Ze==="tool_input_delta"){let z=(_t=k.toolCallId)!=null?_t:H.lastId;if(z){let V=M.get(z);V!=null&&V.toolCall&&(V.toolCall.chunks=(Zr=V.toolCall.chunks)!=null?Zr:[],V.toolCall.chunks.push((Qo=k.delta)!=null?Qo:""),u(V))}}else{if(Ze==="tool_input_complete")continue;if(Ze==="turn_complete"){let z=k.stopReason,V=g!=null?g:x;if(z&&V!==null){let G=k.id;(!G||((Ja=V.agentMetadata)==null?void 0:Ja.turnId)===G)&&(V.stopReason=z,u(V))}Lt===k.id&&(Lt=null)}else if(Ze==="media_start"){let z=String(k.id);$e.set(z,{mediaType:typeof k.mediaType=="string"?k.mediaType:void 0,role:typeof k.role=="string"?k.role:void 0,toolCallId:k.toolCallId,parts:[]})}else if(Ze==="media_delta"){let z=$e.get(String(k.id));z&&typeof k.delta=="string"&&z.parts.push(k.delta)}else if(Ze==="media_complete"){let z=String(k.id),V=$e.get(z);$e.delete(z);let G=(Ya=(ya=typeof k.mediaType=="string"?k.mediaType:void 0)!=null?ya:V==null?void 0:V.mediaType)!=null?Ya:"application/octet-stream",me=typeof k.data=="string"?k.data:void 0,oe=typeof k.url=="string"?k.url:V&&V.parts.length>0?V.parts.join(""):void 0,ut=null;if(me)ut={type:"media",data:me,mediaType:G};else if(oe){let eo=G.toLowerCase();ut={type:eo==="image"||eo.startsWith("image/")?"image-url":"file-url",url:oe,mediaType:G}}let ct=($n=k.toolCallId)!=null?$n:V==null?void 0:V.toolCallId,Or=ut?[ut]:[],yn=[];for(let eo of Or){if(!eo||typeof eo!="object")continue;let ir=eo,to=typeof ir.type=="string"?ir.type:void 0,Zo=typeof ir.mediaType=="string"?ir.mediaType.toLowerCase():"",ur=null,Er="";if(to==="media"){let _r=typeof ir.data=="string"?ir.data:void 0;if(!_r)continue;Er=Zo.length>0?Zo:"application/octet-stream",ur=`data:${Er};base64,${_r}`}else if(to==="image-url"){let _r=typeof ir.url=="string"?ir.url:void 0;if(!_r)continue;Er=Zo,ur=_r}else if(to==="file-url"){let _r=typeof ir.url=="string"?ir.url:void 0;if(!_r)continue;Er=Zo,ur=_r}else continue;if(ur)if(to==="image-url"||Er.startsWith("image/"))yn.push({type:"image",image:ur,...Er.includes("/")?{mimeType:Er}:{}});else if(Er.startsWith("audio/"))yn.push({type:"audio",audio:ur,mimeType:Er});else if(Er.startsWith("video/"))yn.push({type:"video",video:ur,mimeType:Er});else{let _r=Er||"application/octet-stream";yn.push({type:"file",data:ur,mimeType:_r,filename:Lb(_r)})}}if(yn.length>0){let eo=l(),ir=ct,Zo={id:`agent-media-${typeof ir=="string"&&ir.length>0?`${ir}-${eo}`:String(eo)}`,role:"assistant",content:"",contentParts:yn,createdAt:new Date().toISOString(),streaming:!1,sequence:eo,agentMetadata:{executionId:k.executionId,iteration:typeof k.iteration=="number"?k.iteration:Ce}};u(Zo);let ur=g;ur&&(ur.streaming=!1,u(ur)),g=null,b.current=null}}else if(Ze==="execution_complete"){let z=(Ro=k.kind)!=null?Ro:be;z==="agent"&&Z&&(Z.status=k.success?"complete":"error",Z.completedAt=J(k.completedAt),Z.stopReason=k.stopReason);let V=g;V&&(z==="flow"&&V.streaming!==!1?Ye(V):(V.streaming=!1,u(V)),g=null),E=null,A="",Ft=null,r({type:"status",status:"idle"})}else if(Ze==="execution_error"){let z=typeof k.error=="string"?k.error:(st=(xn=k.error)==null?void 0:xn.message)!=null?st:"Execution error";r({type:"error",error:new Error(z)})}else if(Ze!=="ping"){if(Ze==="approval_start"){let z=(ar=k.approvalId)!=null?ar:`approval-${l()}`,V={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(sr=Z==null?void 0:Z.agentId)!=null?sr:"virtual",executionId:(Za=(Io=k.executionId)!=null?Io:Z==null?void 0:Z.executionId)!=null?Za:"",toolName:(Jo=k.toolName)!=null?Jo:"",toolType:k.toolType,description:(Wo=k.description)!=null?Wo:`Execute ${(zn=k.toolName)!=null?zn:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ze==="step_await"&&k.awaitReason==="approval_required"){let z=(q=k.approvalId)!=null?q:`approval-${l()}`,V={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(ba=Z==null?void 0:Z.agentId)!=null?ba:"virtual",executionId:(Ho=(mo=k.executionId)!=null?mo:Z==null?void 0:Z.executionId)!=null?Ho:"",toolName:(Yo=k.toolName)!=null?Yo:"",toolType:k.toolType,description:(go=k.description)!=null?go:`Execute ${(Bo=k.toolName)!=null?Bo:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ze==="approval_complete"){let z=k.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(va=k.decision)!=null?va:"approved",agentId:(zs=Z==null?void 0:Z.agentId)!=null?zs:"virtual",executionId:(Mr=(yr=k.executionId)!=null?yr:Z==null?void 0:Z.executionId)!=null?Mr:"",toolName:(ho=k.toolName)!=null?ho:"",description:(Tr=k.description)!=null?Tr:"",resolvedAt:Date.now()}};u(G)}}else if(Ze==="artifact_start"||Ze==="artifact_delta"||Ze==="artifact_update"||Ze==="artifact_complete"){if(Ze==="artifact_start"){let z=k.artifactType,V=String(k.id),G=typeof k.title=="string"?k.title:void 0;if(r({type:"artifact_start",id:V,artifactType:z,title:G,component:typeof k.component=="string"?k.component:void 0}),ue.set(V,{markdown:"",title:G}),!le.has(V)){le.add(V);let me={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:V,title:G,artifactType:z,status:"streaming"}})};ne.set(V,me),u(me)}}else if(Ze==="artifact_delta"){let z=String(k.id),V=typeof k.delta=="string"?k.delta:String((jn=k.delta)!=null?jn:"");r({type:"artifact_delta",id:z,artDelta:V});let G=ue.get(z);G&&(G.markdown+=V)}else if(Ze==="artifact_update"){let z=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};r({type:"artifact_update",id:String(k.id),props:z,component:typeof k.component=="string"?k.component:void 0})}else if(Ze==="artifact_complete"){let z=String(k.id);r({type:"artifact_complete",id:z});let V=ne.get(z);if(V){V.streaming=!1;try{let G=JSON.parse((xo=V.rawContent)!=null?xo:"{}");if(G.props){G.props.status="complete";let me=ue.get(z);me!=null&&me.markdown&&(G.props.markdown=me.markdown)}V.rawContent=JSON.stringify(G)}catch{}ue.delete(z),u(V),ne.delete(z)}}}else if(Ze==="transcript_insert"){let z=k.message;if(!z||typeof z!="object")continue;let V=String((br=z.id)!=null?br:`msg-${l()}`),G=z.role,oe={id:V,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(u(oe),oe.rawContent)try{let ut=JSON.parse(oe.rawContent),ct=(Do=ut==null?void 0:ut.props)==null?void 0:Do.artifactId;typeof ct=="string"&&le.add(ct)}catch{}g=null,b.current=null,K.delete(V),pe.delete(V)}else if(Ze==="error"){if(k.recoverable===!1&&k.error!=null&&k.error!==""){let z=typeof k.error=="string"?k.error:((wa=k.error)==null?void 0:wa.message)!=null?String(k.error.message):"Execution error";r({type:"error",error:new Error(z)});let V=g;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}else if(Ze==="step_error"||Ze==="dispatch_error"||Ze==="flow_error"){let z=null;if(k.error instanceof Error)z=k.error;else if(Ze==="dispatch_error"){let V=(Gn=k.message)!=null?Gn:k.error;V!=null&&V!==""&&(z=new Error(String(V)))}else{let V=k.error;typeof V=="string"&&V!==""?z=new Error(V):V!=null&&typeof V=="object"&&"message"in V&&(z=new Error(String((Ca=V.message)!=null?Ca:V)))}if(z){r({type:"error",error:z});let V=g;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}}}}X.length=0};;){let{done:P,value:ee}=await n.read();if(P)break;s+=a.decode(ee,{stream:!0});let Me=s.split(`
13
13
 
14
- `);s=(yr=Se.pop())!=null?yr:"";for(let We of Se){let ke=We.split(`
15
- `),He="message",Ge="";for(let ae of ke)ae.startsWith("event:")?He=ae.replace("event:","").trim():ae.startsWith("data:")&&(Ge+=ae.replace("data:","").trim());if(!Ge)continue;let st;try{st=JSON.parse(Ge)}catch(ae){r({type:"error",error:ae instanceof Error?ae:new Error("Failed to parse chat stream payload")});continue}let Rt=He!=="message"?He:(Co=st.type)!=null?Co:"message";if((So=this.onSSEEvent)==null||So.call(this,Rt,st),this.parseSSEEvent){b.current=m;let ae=await this.handleCustomSSEEvent(st,r,b,u,l,L);if(b.current&&b.current!==m&&(m=b.current),ae)continue}X.push({payloadType:Rt,payload:st}),dt()}}dt()}};function _g(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Pa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Qn(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var fi="[Image]";function Ug(e){return typeof e=="string"?[{type:"text",text:e}]:e}function qg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Vg(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 gs(e){return{type:"text",text:e}}function $g(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 jg(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 Gg(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 Kg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],fb=["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"],Zo=[...Kg,...fb];function mb(e){return Kg.includes(e)||e.startsWith("image/")}function mi(e){return mb(e.type)}async function Xg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;mi(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=Zo,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 gb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Qg(e,t){let r=gb(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 gi=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 Yg=16e3,hb=24e3,xb=4096,yb=1380533830;function bb(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===yb?new Uint8Array(e,44):new Uint8Array(e)}function vb(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var hs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Yg,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){l.getTracks().forEach(b=>b.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,f=new p({sampleRate:Yg});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new gi(hb);if(n!==this.callGeneration){u.destroy(),l.getTracks().forEach(b=>b.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${vb(o)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(m,["runtype.bearer",r]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,l,x,n))},x.onmessage=b=>this.handleMessage(b,n),x.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=b=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(b.code!==1e3){let L=b.code?` (code ${b.code})`:"";this.emitError(new Error(`Voice connection closed${L}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(xb,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),l=new Int16Array(c.length);for(let p=0;p<c.length;p++){let f=Math.max(-1,Math.min(1,c[p]));l[p]=f<0?f*32768:f*32767}o.send(l.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,r){if(r!==this.callGeneration||!this.playback)return;let o=bb(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 Yn=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 An(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new hs(e.runtype);case"browser":if(!Yn.isSupported())throw new Error("Browser speech recognition not supported");return new Yn(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 hi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return An({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return An({type:"runtype",runtype:e.runtype});if(Yn.isSupported())return An({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function xs(e){try{return hi(e),!0}catch{return!1}}function Ra(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 Mn=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):Ra(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var l,p;let c=i.error;c==="canceled"||c==="interrupted"?(l=r.onEnd)==null||l.call(r):(p=r.onError)==null||p.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Zn=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 Ul(e){if(!e)return"";let t=wb(e);return Zg(t!==null?t:e)}function wb(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 Zg(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
14
+ `);s=(xr=Me.pop())!=null?xr:"";for(let He of Me){let Le=He.split(`
15
+ `),Be="message",Ge="";for(let se of Le)se.startsWith("event:")?Be=se.replace("event:","").trim():se.startsWith("data:")&&(Ge+=se.replace("data:","").trim());if(!Ge)continue;let at;try{at=JSON.parse(Ge)}catch(se){r({type:"error",error:se instanceof Error?se:new Error("Failed to parse chat stream payload")});continue}let Pt=Be!=="message"?Be:(Ao=at.type)!=null?Ao:"message";if((Mo=this.onSSEEvent)==null||Mo.call(this,Pt,at),this.parseSSEEvent){b.current=g;let se=await this.handleCustomSSEEvent(at,r,b,u,l,L);if(b.current&&b.current!==g&&(g=b.current),se)continue}X.push({payloadType:Pt,payload:at}),dt()}}dt()}};function th(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Da(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function sa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var yi="[Image]";function rh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function oh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function nh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ah(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ss(e){return{type:"text",text:e}}function sh(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 ih(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 lh(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 dh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ib=["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=[...dh,...Ib];function Wb(e){return dh.includes(e)||e.startsWith("image/")}function bi(e){return Wb(e.type)}async function ch(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;bi(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 ph(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 Hb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function uh(e,t){let r=Hb(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 vi=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 fh=16e3,Bb=24e3,Db=4096,Fb=1380533830;function Nb(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Fb?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 As=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:fh,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){l.getTracks().forEach(b=>b.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,f=new p({sampleRate:fh});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new vi(Bb);if(n!==this.callGeneration){u.destroy(),l.getTracks().forEach(b=>b.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${Ob(o)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(g,["runtype.bearer",r]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,l,x,n))},x.onmessage=b=>this.handleMessage(b,n),x.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=b=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(b.code!==1e3){let L=b.code?` (code ${b.code})`:"";this.emitError(new Error(`Voice connection closed${L}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(Db,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),l=new Int16Array(c.length);for(let p=0;p<c.length;p++){let f=Math.max(-1,Math.min(1,c[p]));l[p]=f<0?f*32768:f*32767}o.send(l.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,r){if(r!==this.callGeneration||!this.playback)return;let o=Nb(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 ia=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 As(e.runtype);case"browser":if(!ia.isSupported())throw new Error("Browser speech recognition not supported");return new ia(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 wi(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(ia.isSupported())return In({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ms(e){try{return wi(e),!0}catch{return!1}}function Fa(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 Wn=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):Fa(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var l,p;let c=i.error;c==="canceled"||c==="interrupted"?(l=r.onEnd)==null||l.call(r):(p=r.onError)==null||p.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var la=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 Kl(e){if(!e)return"";let t=_b(e);return mh(t!==null?t:e)}function _b(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 mh(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,`
16
16
  `),t=t.replace(/\n{2,}/g,`
17
- `),t.trim()}var ql=null,eh=e=>{ql=e},Vl=()=>ql?ql():import("./runtype-tts-entry");var Cb=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Sb(e,t){return Cb.some(r=>e[r]!==t[r])}function th(e,t){let r=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(r);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${o}
17
+ `),t.trim()}var Xl=null,gh=e=>{Xl=e},Ql=()=>Xl?Xl():import("./runtype-tts-entry");var Ub=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function qb(e,t){return Ub.some(r=>e[r]!==t[r])}function hh(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}
18
18
 
19
- _Details: ${r.message}_`:o}var ys=e=>({isError:!0,content:[{type:"text",text:e}]}),rh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,oh=e=>yn(e)||e===vo,Ia=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 Zn(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,l,p,f;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall,m=!!(u!=null&&u.name)&&(yn(u.name)||u.name===vo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(f=(p=this.callbacks).onError)==null||f.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Jn(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,l;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=(l=(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)!=null?l:this.config.agentId;!r||!o||!this.config.clientToken||Vl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return xs((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i,c;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=Mn.isSupported()?new Mn({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let l=(o=t.host)!=null?o:this.config.apiUrl,p=(c=(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)!=null?c:this.config.agentId,f=this.config.clientToken,u=t.browserFallback!==!1;if(l&&p&&f)return Vl().then(({RuntypeSpeechEngine:m,FallbackSpeechEngine:x})=>{let b=new m({host:l,agentId:p,clientToken:f,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return u&&r?new x(b,r,{onFallback:L=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${L.message}`)}):b});if(u&&r)return f&&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=An(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,c,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:c,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,l;(l=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||l.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,l;this.voiceStatus=i,this.voiceActive=i==="listening",(l=(c=this.callbacks).onVoiceStatusChanged)==null||l.call(c,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,o,n,a,s,i,c,l,p,f,u,m;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:(a=(n=(o=t.runtype)==null?void 0:o.agentId)!=null?n:this.config.agentId)!=null?a:"",clientToken:(i=(s=t.runtype)==null?void 0:s.clientToken)!=null?i:this.config.clientToken,host:(l=(c=t.runtype)==null?void 0:c.host)!=null?l:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(f=t.runtype)==null?void 0:f.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((u=t.browser)==null?void 0:u.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.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 Jn(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:l=!1,voiceProcessing:p,rawContent:f}=t,m={id:s!=null?s:r==="user"?Pa():r==="assistant"?Qn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:l,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:l,sequence:p,streaming:f=!1,voiceProcessing:u,rawContent:m}=o,b={id:c!=null?c:n==="user"?Pa():n==="assistant"?Qn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:f,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};r.push(b)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,l={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var l,p,f,u,m;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let n=Pa(),a=Qn(),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 b=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!b){let L=th(x,this.config.errorMessage);if(L){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:L,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(x instanceof Error?(f=(p=this.callbacks).onError)==null||f.call(p,x):(m=(u=this.callbacks).onError)==null||m.call(u,new Error(String(x))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort();let t=Qn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let f=th(l,this.config.errorMessage);if(f){let u={id:t,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,l):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(l))))}}async connectStream(t,r){var n,a,s;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(n=this.abortController)==null||n.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var p,f,u,m,x;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(b=>b.id===n),i={id:n,role:"assistant",content:"",createdAt:(p=s==null?void 0:s.createdAt)!=null?p:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,l=c&&typeof c=="object"?c.onDecision:void 0;try{let b;if(l?b=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):b=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),b){let L=null;if(b instanceof Response){if(!b.ok){let E=await b.json().catch(()=>null);throw new Error((u=E==null?void 0:E.error)!=null?u:`Approval request failed: ${b.status}`)}L=b.body}else b instanceof ReadableStream&&(L=b);L?await this.connectStream(L,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(b){let L=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,L||(x=(m=this.callbacks).onError)==null||x.call(m,b instanceof Error?b:new Error(String(b)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var p,f,u,m,x,b,L,E,A,T,y,S;let o=this.messages.find(v=>v.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let n=(f=t.agentMetadata)==null?void 0:f.executionId,a=(u=t.toolCall)==null?void 0:u.name;if(!n||!a){(x=(m=this.callbacks).onError)==null||x.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let v=(b=t.toolCall)==null?void 0:b.args,M=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(M.length===1){let W=typeof((L=M[0])==null?void 0:L.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=(A=t.toolCall)==null?void 0:A.args,l=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(l.length===0){let v=typeof r=="string"?r:Object.entries(r).map(([M,W])=>`${M}: ${Array.isArray(W)?W.join(", "):W}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=s!=null?s:{};l.forEach((M,W)=>{let H=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!H)return;let I=v[H],D=Array.isArray(I)?I.join(", "):typeof I=="string"?I:"";this.appendMessage({id:`ask-user-q-${i}-${W}`,role:"assistant",content:H,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${W}`,role:"user",content:D||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(n,{[a]:r});if(!v.ok){let M=await v.json().catch(()=>null);throw new Error((T=M==null?void 0:M.error)!=null?T:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(S=(y=this.callbacks).onError)==null||S.call(y,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==vo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,l,p,f;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async u=>{var S,v,M,W,H,I,D;let m=(S=u.toolCall)==null?void 0:S.name,x=(v=u.toolCall)==null?void 0:v.id;if(!m||!x)return null;let b=`${t}:${x}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(b),o.push(b);let L=this.markWebMcpToolRunning(u),E=(W=(M=u.agentMetadata)==null?void 0:M.webMcpToolCallId)!=null?W:m;if(m===vo)return{dedupeKey:b,resumeKey:E,output:Bl(),toolMessage:u,startedAt:L,completedAt:Date.now()};let A=new AbortController;this.webMcpResolveControllers.add(A),n.push(A);let T=this.client.executeWebMcpToolCall(m,(H=u.toolCall)==null?void 0:H.args,A.signal),y;if(!T)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await T}catch(O){let J=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return J||(D=(I=this.callbacks).onError)==null||D.call(I,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(u,ys(J?"Aborted by cancel()":rh(O)),L),this.webMcpInflightKeys.delete(b),null}return A.signal.aborted?(this.markWebMcpToolComplete(u,ys("Aborted by cancel()"),L),this.webMcpInflightKeys.delete(b),null):{dedupeKey:b,resumeKey:E,output:y,toolMessage:u,startedAt:L,completedAt:Date.now()}})),i=[];try{if(i=s.filter(x=>x!==null),i.length===0)return;let u={};for(let x of i)u[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,u,{signal:a.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((c=x==null?void 0:x.error)!=null?c:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((l=x.toolMessage.toolCall)==null?void 0:l.name)===vo?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(p=this.callbacks).onError)==null||f.call(p,u instanceof Error?u:new Error(String(u)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,ys("Aborted by cancel()"),x.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of n)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,b,L,E,A,T,y,S,v,M,W,H;let r=(x=t.agentMetadata)==null?void 0:x.executionId,o=(b=t.toolCall)==null?void 0:b.name,n=(L=t.toolCall)==null?void 0:L.id;if(!r){(A=(E=this.callbacks).onError)==null||A.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let I=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(I)||this.webMcpResolvedKeys.has(I))return;this.webMcpInflightKeys.add(I);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(I)}catch(D){(y=(T=this.callbacks).onError)==null||y.call(T,D instanceof Error?D:new Error(String(D)))}finally{this.webMcpInflightKeys.delete(I)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let l=o===vo,p=(S=t.toolCall)==null?void 0:S.args,f=l?null:this.client.executeWebMcpToolCall(o,p,c),u="execute",m=s;try{let I;if(l?I=Bl():f?I=await f:I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),c.aborted){this.markWebMcpToolComplete(t,ys("Aborted by cancel()"),s);return}let D=(M=(v=t.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?M:o;u="resume",await this.resumeWithToolOutput(r,D,I,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,I,s,m,l?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(I){let D=I instanceof Error&&(I.name==="AbortError"||I.message.includes("aborted")||I.message.includes("abort"));(u==="execute"||D||c.aborted)&&this.markWebMcpToolComplete(t,ys(D||c.aborted?"Aborted by cancel()":rh(I)),s),D||(H=(W=this.callbacks).onError)==null||H.call(W,I instanceof Error?I:new Error(String(I)))}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=Ul(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ra(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=Ul(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var p,f,u,m,x,b,L,E,A,T,y,S,v,M,W;if(a!==o)return n;let s={...n,...r};if(((p=n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=n.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(u=s.agentMetadata)!=null?u:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let H=n.approval,I=r.approval;s.approval={...H,...I,executionId:I.executionId||H.executionId,toolName:I.toolName||H.toolName,description:I.description||H.description,toolType:(m=I.toolType)!=null?m:H.toolType,reason:(x=I.reason)!=null?x:H.reason,parameters:(b=I.parameters)!=null?b:H.parameters}}let i=(L=r.toolCall)==null?void 0:L.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,l=(A=r.toolCall)==null?void 0:A.id;if(i&&oh(i)&&c&&l&&((T=r.agentMetadata)==null?void 0:T.awaitingLocalTool)===!0){let H=`${c}:${l}`,I=this.webMcpInflightKeys.has(H),D=this.webMcpResolvedKeys.has(H),O=(y=n.toolCall)==null?void 0:y.name,J=((S=n.agentMetadata)==null?void 0:S.executionId)===c&&((v=n.toolCall)==null?void 0:v.id)===l&&O!==void 0&&oh(O)&&((M=n.toolCall)==null?void 0:M.status)==="complete";(I||D||J)&&(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,l;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(l=o.sequence)!=null?l:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var zl=[["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 $l=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var jl=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Gl=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var Kl=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Xl=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Jl=[["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 Ql=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var Yl=[["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 Zl=[["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 ed=[["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 td=[["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 rd=[["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 od=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var nd=[["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 ad=[["path",{d:"M20 6 9 17l-5-5"}]];var sd=[["path",{d:"m6 9 6 6 6-6"}]];var id=[["path",{d:"m15 18-6-6 6-6"}]];var ld=[["path",{d:"m9 18 6-6-6-6"}]];var dd=[["path",{d:"m18 15-6-6-6 6"}]];var xi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var yi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var cd=[["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 pd=[["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 ud=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var fd=[["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 md=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var gd=[["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 bi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var vi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var xd=[["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 yd=[["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 bd=[["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 vd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var wd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Cd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Sd=[["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 Ad=[["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 Md=[["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 Td=[["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 Ed=[["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 wi=[["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 Ld=[["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 Pd=[["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 Rd=[["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 Id=[["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 Wd=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Hd=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Ci=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Bd=[["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 Dd=[["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 Fd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Nd=[["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 Od=[["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 Si=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var _d=[["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 Ud=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var qd=[["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 Vd=[["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 zd=[["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 $d=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var jd=[["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 Gd=[["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 Kd=[["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 Xd=[["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 Jd=[["path",{d:"M5 12h14"}]];var Qd=[["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 Yd=[["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 Zd=[["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 ec=[["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 tc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var rc=[["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 oc=[["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 nc=[["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 ac=[["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 sc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var ic=[["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 lc=[["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 dc=[["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 cc=[["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 pc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var uc=[["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 fc=[["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 mc=[["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 gc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"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 Ai=[["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 xc=[["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 yc=[["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 bc=[["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 vc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Mi=[["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 wc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Cc=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Sc=[["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 Ac=[["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 Mc=[["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 Tc=[["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 Ec=[["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 Lc=[["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 Pc=[["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 Ti=[["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 Rc=[["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 Ic=[["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 Wc=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Hc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Bc=[["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 Dc=[["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 Fc=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Nc=[["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 Ab={activity:zl,"arrow-down":$l,"arrow-up":Xl,"arrow-up-right":Kl,bot:ed,"chevron-down":sd,"chevron-up":dd,"chevron-right":ld,"chevron-left":id,check:ad,clipboard:pd,"clipboard-copy":cd,copy:fd,file:Sd,"file-code":vd,"file-spreadsheet":wd,"file-text":Cd,"image-plus":Bd,loader:_d,"loader-circle":Si,mic:Kd,paperclip:ec,"refresh-cw":lc,search:pc,send:uc,"shield-alert":gc,"shield-check":hc,"shield-x":Ai,square:wc,"thumbs-down":Tc,"thumbs-up":Ec,upload:Ic,"volume-2":Hc,x:Fc,user:Wc,mail:qd,phone:nc,calendar:od,clock:ud,building:td,"map-pin":Vd,lock:Ud,key:Nd,"credit-card":md,"at-sign":Jl,hash:Rd,globe:Pd,link:Od,"circle-check":xi,"circle-x":yi,"triangle-alert":Ti,info:Fd,ban:Ql,shield:xc,"arrow-left":jl,"arrow-right":Gl,"external-link":yd,ellipsis:vi,"ellipsis-vertical":bi,menu:$d,house:Ci,plus:sc,minus:Jd,pencil:rc,trash:Pc,"trash-2":Lc,save:cc,download:hd,share:mc,funnel:wi,settings:fc,"rotate-cw":dc,maximize:zd,minimize:Xd,"shopping-cart":bc,"shopping-bag":yc,package:Zd,truck:Rc,tag:Mc,gift:Ld,receipt:ic,wallet:Dc,store:Sc,"dollar-sign":gd,percent:oc,play:ac,pause:tc,"volume-x":Bc,camera:nd,image:Dd,film:Md,headphones:Id,"message-circle":jd,"message-square":Gd,bell:Yl,heart:Wd,star:Cc,eye:bd,"eye-off":xd,bookmark:Zl,"calendar-days":rd,history:Hd,timer:kc,folder:kd,"folder-open":Ed,files:Ad,sparkles:Mi,zap:Nc,sun:Ac,moon:Yd,flag:Td,monitor:Qd,smartphone:vc},fe=(e,t=24,r="currentColor",o=2)=>{let n=Ab[e];return n?Mb(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 Mb(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&c.setAttribute(l,String(p))}),n.appendChild(c)}),n}var Ei={allowedTypes:Zo,maxFileSize:10*1024*1024,maxFiles:4};function Tb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Eb(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 ea=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ei.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ei.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Ei.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:Ei.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,o,n,a,s,i,c;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,l,"count");continue}let p=Jg(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let f=(n=p.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,f);continue}try{let f=await Xg(l),u=mi(l)?URL.createObjectURL(l):null,m={id:Tb(),file:l,previewUrl:u,contentPart:f};this.attachments.push(m),this.renderPreview(m)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=mi(t.file),o=w("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=w("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=w("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=Eb(t.file.type),c=fe(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let l=w("span");l.textContent=Qg(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",s.appendChild(l),o.appendChild(s)}let n=w("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=fe("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var nh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bs(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];nh(a)&&nh(n)?r[o]=bs(a,n):r[o]=n}return r}var Jr="min(440px, calc(100vw - 24px))",ki="440px",kb={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:Jr,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)"},Ht={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:kb,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 ah(e,t){if(!(!e&&!t))return e?t?bs(e,t):e:t}function Li(e){var t,r,o,n,a,s,i,c,l,p,f,u,m,x,b,L,E,A,T,y,S;return e?{...Ht,...e,theme:ah(Ht.theme,e.theme),darkTheme:ah(Ht.darkTheme,e.darkTheme),launcher:{...Ht.launcher,...e.launcher,dock:{...(t=Ht.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=Ht.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{...Ht.copy,...e.copy},sendButton:{...Ht.sendButton,...e.sendButton},statusIndicator:{...Ht.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ht.voiceRecognition,...e.voiceRecognition},features:(()=>{var se,ie,pe,Ee,De,j,Q,Fe,K,ce;let v=(se=Ht.features)==null?void 0:se.artifacts,M=(ie=e.features)==null?void 0:ie.artifacts,W=(pe=Ht.features)==null?void 0:pe.scrollToBottom,H=(Ee=e.features)==null?void 0:Ee.scrollToBottom,I=(De=Ht.features)==null?void 0:De.scrollBehavior,D=(j=e.features)==null?void 0:j.scrollBehavior,O=(Q=Ht.features)==null?void 0:Q.streamAnimation,J=(Fe=e.features)==null?void 0:Fe.streamAnimation,me=(K=Ht.features)==null?void 0:K.askUserQuestion,de=(ce=e.features)==null?void 0:ce.askUserQuestion,te=v===void 0&&M===void 0?void 0:{...v,...M,layout:{...v==null?void 0:v.layout,...M==null?void 0:M.layout}},Ae=W===void 0&&H===void 0?void 0:{...W,...H},Ie=I===void 0&&D===void 0?void 0:{...I,...D},le=O===void 0&&J===void 0?void 0:{...O,...J},Ce=me===void 0&&de===void 0?void 0:{...me,...de,styles:{...me==null?void 0:me.styles,...de==null?void 0:de.styles}};return{...Ht.features,...e.features,...Ae!==void 0?{scrollToBottom:Ae}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...te!==void 0?{artifacts:te}:{},...le!==void 0?{streamAnimation:le}:{},...Ce!==void 0?{askUserQuestion:Ce}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:Ht.suggestionChips,suggestionChipsConfig:{...Ht.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ht.layout,...e.layout,header:{...(s=Ht.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=Ht.layout)==null?void 0:c.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(f=(p=Ht.layout)==null?void 0:p.messages)==null?void 0:f.avatar,...(m=(u=e.layout)==null?void 0:u.messages)==null?void 0:m.avatar},timestamp:{...(b=(x=Ht.layout)==null?void 0:x.messages)==null?void 0:b.timestamp,...(E=(L=e.layout)==null?void 0:L.messages)==null?void 0:E.timestamp}},slots:{...(A=Ht.layout)==null?void 0:A.slots,...(T=e.layout)==null?void 0:T.slots}},markdown:{...Ht.markdown,...e.markdown,options:{...(y=Ht.markdown)==null?void 0:y.options,...(S=e.markdown)==null?void 0:S.options}},messageActions:{...Ht.messageActions,...e.messageActions}}:Ht}var Oc={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"}},_c={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"}},Uc={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:Jr,maxWidth:ki,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Wa(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Wa(e,o):o}function Pi(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let c=Wa(e,s);c!==void 0&&(t[i]={path:i,value:c,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function qc(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 sh(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]=sh(a,n):r[o]=n}return r}function Lb(e,t){return t?sh(e,t):e}function Ha(e,t={}){var n,a,s,i,c,l,p,f,u,m,x,b,L;let r={palette:Oc,semantic:_c,components:Uc},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(u=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...r.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(b=e==null?void 0:e.semantic)==null?void 0:b.spacing},typography:{...r.semantic.typography,...(L=e==null?void 0:e.semantic)==null?void 0:L.typography}},components:Lb(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=qc(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Ri(e){var b,L,E,A,T,y,S,v,M,W,H,I,D,O,J,me,de,te,Ae,Ie,le,Ce,se,ie,pe,Ee,De,j,Q,Fe,K,ce,qe,ot,yt,Ot,Qt,Ye,ge,X,dt,ze,ve,Me,et,Pt,Z,Ue,Ar,bt,yr,Co,So,P,ee,Se,We,ke,He,Ge,st,Rt,ae,F,he,Ne,vt,Je,Bt,Mt,gt,Lt,Jt,_t,Fr,qt,Nr,Zr,br,Rr,eo,on,wt,Ao,Mo,_o,uo,pt,Rn,To,In,Ir,da,nn,Uo,an,sn,Wn,Hn,ln,xt,Or,_r,Mr,Ct,to,ro,Ur,dn,qo,cn,qr,It,Tr,oo,pn,Vo,un;let t=Pi(e),r={};for(let[ye,Wr]of Object.entries(t)){let Eo=ye.replace(/\./g,"-");r[`--persona-${Eo}`]=Wr.value}r["--persona-primary"]=(b=r["--persona-semantic-colors-primary"])!=null?b:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(L=r["--persona-semantic-colors-secondary"])!=null?L:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(E=r["--persona-semantic-colors-accent"])!=null?E:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(A=r["--persona-semantic-colors-surface"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(T=r["--persona-semantic-colors-background"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(S=r["--persona-semantic-colors-text"])!=null?S:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(v=r["--persona-semantic-colors-text-muted"])!=null?v:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(M=r["--persona-semantic-colors-text-inverse"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(W=r["--persona-semantic-colors-border"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(H=r["--persona-semantic-colors-divider"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(I=r["--persona-components-voice-recording-indicator"])!=null?I:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(D=r["--persona-components-voice-recording-background"])!=null?D:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(O=r["--persona-components-voice-processing-icon"])!=null?O:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(J=r["--persona-components-voice-speaking-icon"])!=null?J:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-surface"],r["--persona-approval-border"]=(de=r["--persona-components-approval-requested-border"])!=null?de:r["--persona-border"],r["--persona-approval-text"]=(te=r["--persona-components-approval-requested-text"])!=null?te:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Ae=r["--persona-components-approval-requested-shadow"])!=null?Ae:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",r["--persona-approval-approve-bg"]=(Ie=r["--persona-components-approval-approve-background"])!=null?Ie:r["--persona-button-primary-bg"],r["--persona-approval-deny-bg"]=(le=r["--persona-components-approval-deny-background"])!=null?le:r["--persona-container"],r["--persona-attachment-image-bg"]=(Ce=r["--persona-components-attachment-image-background"])!=null?Ce:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(se=r["--persona-components-attachment-image-border"])!=null?se:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(ie=r["--persona-semantic-typography-fontFamily"])!=null?ie:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(pe=r["--persona-semantic-typography-fontSize"])!=null?pe:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(Ee=r["--persona-semantic-typography-fontWeight"])!=null?Ee:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(De=r["--persona-semantic-typography-lineHeight"])!=null?De: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"]=(Q=r["--persona-palette-radius-md"])!=null?Q:"0.375rem",r["--persona-radius-lg"]=(Fe=r["--persona-palette-radius-lg"])!=null?Fe:"0.5rem",r["--persona-radius-xl"]=(K=r["--persona-palette-radius-xl"])!=null?K:"0.75rem",r["--persona-radius-full"]=(ce=r["--persona-palette-radius-full"])!=null?ce:"9999px",r["--persona-launcher-radius"]=(ot=(qe=r["--persona-components-launcher-borderRadius"])!=null?qe:r["--persona-palette-radius-full"])!=null?ot:"9999px",r["--persona-launcher-bg"]=(yt=r["--persona-components-launcher-background"])!=null?yt:r["--persona-primary"],r["--persona-launcher-fg"]=(Ot=r["--persona-components-launcher-foreground"])!=null?Ot:r["--persona-text-inverse"],r["--persona-launcher-border"]=(Qt=r["--persona-components-launcher-border"])!=null?Qt:r["--persona-border"],r["--persona-button-primary-bg"]=(Ye=r["--persona-components-button-primary-background"])!=null?Ye:r["--persona-primary"],r["--persona-button-primary-fg"]=(ge=r["--persona-components-button-primary-foreground"])!=null?ge:r["--persona-text-inverse"],r["--persona-button-radius"]=(dt=(X=r["--persona-components-button-primary-borderRadius"])!=null?X:r["--persona-palette-radius-full"])!=null?dt:"9999px",r["--persona-panel-radius"]=(ve=(ze=r["--persona-components-panel-borderRadius"])!=null?ze:r["--persona-radius-xl"])!=null?ve:"0.75rem",r["--persona-panel-border"]=(Me=r["--persona-components-panel-border"])!=null?Me:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Pt=(et=r["--persona-components-panel-shadow"])!=null?et:r["--persona-palette-shadows-xl"])!=null?Pt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(Z=r["--persona-components-launcher-shadow"])!=null?Z:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(Ar=(Ue=r["--persona-components-input-borderRadius"])!=null?Ue:r["--persona-radius-lg"])!=null?Ar:"0.5rem",r["--persona-message-user-radius"]=(yr=(bt=r["--persona-components-message-user-borderRadius"])!=null?bt:r["--persona-radius-lg"])!=null?yr:"0.5rem",r["--persona-message-assistant-radius"]=(So=(Co=r["--persona-components-message-assistant-borderRadius"])!=null?Co:r["--persona-radius-lg"])!=null?So:"0.5rem",r["--persona-header-bg"]=(P=r["--persona-components-header-background"])!=null?P:r["--persona-surface"],r["--persona-header-border"]=(ee=r["--persona-components-header-border"])!=null?ee:r["--persona-divider"],r["--persona-header-icon-bg"]=(Se=r["--persona-components-header-iconBackground"])!=null?Se:r["--persona-primary"],r["--persona-header-icon-fg"]=(We=r["--persona-components-header-iconForeground"])!=null?We:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(ke=r["--persona-components-header-titleForeground"])!=null?ke:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(He=r["--persona-components-header-subtitleForeground"])!=null?He:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(Ge=r["--persona-components-header-actionIconForeground"])!=null?Ge:r["--persona-muted"];let o=(st=e.components)==null?void 0:st.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(Rt=e.components)==null?void 0:Rt.introCard;r["--persona-intro-card-bg"]=(ae=r["--persona-components-introCard-background"])!=null?ae:r["--persona-surface"],r["--persona-intro-card-radius"]=(F=r["--persona-components-introCard-borderRadius"])!=null?F:"1rem",r["--persona-intro-card-padding"]=(he=r["--persona-components-introCard-padding"])!=null?he:"1.5rem",r["--persona-intro-card-shadow"]=(vt=(Ne=n==null?void 0:n.shadow)!=null?Ne:r["--persona-components-introCard-shadow"])!=null?vt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Je=r["--persona-components-input-background"])!=null?Je:r["--persona-surface"],r["--persona-input-placeholder"]=(Bt=r["--persona-components-input-placeholder"])!=null?Bt:r["--persona-text-muted"],r["--persona-message-user-bg"]=(Mt=r["--persona-components-message-user-background"])!=null?Mt:r["--persona-accent"],r["--persona-message-user-text"]=(gt=r["--persona-components-message-user-text"])!=null?gt:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(Lt=r["--persona-components-message-user-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Jt=r["--persona-components-message-assistant-background"])!=null?Jt:r["--persona-surface"],r["--persona-message-assistant-text"]=(_t=r["--persona-components-message-assistant-text"])!=null?_t:r["--persona-text"],r["--persona-message-assistant-border"]=(Fr=r["--persona-components-message-assistant-border"])!=null?Fr:r["--persona-border"],r["--persona-message-assistant-shadow"]=(qt=r["--persona-components-message-assistant-shadow"])!=null?qt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(Zr=(Nr=r["--persona-components-scrollToBottom-background"])!=null?Nr:r["--persona-button-primary-bg"])!=null?Zr:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(Rr=(br=r["--persona-components-scrollToBottom-foreground"])!=null?br:r["--persona-button-primary-fg"])!=null?Rr:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(eo=r["--persona-components-scrollToBottom-border"])!=null?eo:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(on=r["--persona-components-scrollToBottom-size"])!=null?on:"40px",r["--persona-scroll-to-bottom-radius"]=(Mo=(Ao=(wt=r["--persona-components-scrollToBottom-borderRadius"])!=null?wt:r["--persona-button-radius"])!=null?Ao:r["--persona-radius-full"])!=null?Mo:"9999px",r["--persona-scroll-to-bottom-shadow"]=(uo=(_o=r["--persona-components-scrollToBottom-shadow"])!=null?_o:r["--persona-palette-shadows-sm"])!=null?uo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(pt=r["--persona-components-scrollToBottom-padding"])!=null?pt:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(Rn=r["--persona-components-scrollToBottom-gap"])!=null?Rn:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(In=(To=r["--persona-components-scrollToBottom-fontSize"])!=null?To:r["--persona-palette-typography-fontSize-sm"])!=null?In:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(Ir=r["--persona-components-scrollToBottom-iconSize"])!=null?Ir:"14px",r["--persona-tool-bubble-shadow"]=(da=r["--persona-components-toolBubble-shadow"])!=null?da:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(nn=r["--persona-components-reasoningBubble-shadow"])!=null?nn:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Uo=r["--persona-components-composer-shadow"])!=null?Uo:"none",r["--persona-md-inline-code-bg"]=(an=r["--persona-components-markdown-inlineCode-background"])!=null?an:r["--persona-container"],r["--persona-md-inline-code-color"]=(sn=r["--persona-components-markdown-inlineCode-foreground"])!=null?sn:r["--persona-text"],r["--persona-md-link-color"]=(Hn=(Wn=r["--persona-components-markdown-link-foreground"])!=null?Wn:r["--persona-accent"])!=null?Hn:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let l=r["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(r["--persona-md-prose-font-family"]=l),r["--persona-md-code-block-bg"]=(ln=r["--persona-components-markdown-codeBlock-background"])!=null?ln:r["--persona-container"],r["--persona-md-code-block-border-color"]=(xt=r["--persona-components-markdown-codeBlock-borderColor"])!=null?xt:r["--persona-border"],r["--persona-md-code-block-text-color"]=(Or=r["--persona-components-markdown-codeBlock-textColor"])!=null?Or:"inherit",r["--persona-md-table-header-bg"]=(_r=r["--persona-components-markdown-table-headerBackground"])!=null?_r:r["--persona-container"],r["--persona-md-table-border-color"]=(Mr=r["--persona-components-markdown-table-borderColor"])!=null?Mr:r["--persona-border"],r["--persona-md-hr-color"]=(Ct=r["--persona-components-markdown-hr-color"])!=null?Ct:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(to=r["--persona-components-markdown-blockquote-borderColor"])!=null?to:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(ro=r["--persona-components-markdown-blockquote-background"])!=null?ro:"transparent",r["--persona-md-blockquote-text-color"]=(Ur=r["--persona-components-markdown-blockquote-textColor"])!=null?Ur:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(dn=r["--persona-components-collapsibleWidget-container"])!=null?dn:r["--persona-surface"],r["--cw-surface"]=(qo=r["--persona-components-collapsibleWidget-surface"])!=null?qo:r["--persona-surface"],r["--cw-border"]=(cn=r["--persona-components-collapsibleWidget-border"])!=null?cn:r["--persona-border"],r["--persona-message-border"]=(qr=r["--persona-components-message-border"])!=null?qr:r["--persona-border"];let p=e.components,f=p==null?void 0:p.iconButton;f&&(f.background&&(r["--persona-icon-btn-bg"]=f.background),f.border&&(r["--persona-icon-btn-border"]=f.border),f.color&&(r["--persona-icon-btn-color"]=f.color),f.padding&&(r["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(r["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(r["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(r["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(r["--persona-icon-btn-active-border"]=f.activeBorder));let u=p==null?void 0:p.labelButton;u&&(u.background&&(r["--persona-label-btn-bg"]=u.background),u.border&&(r["--persona-label-btn-border"]=u.border),u.color&&(r["--persona-label-btn-color"]=u.color),u.padding&&(r["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(r["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(r["--persona-label-btn-gap"]=u.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(r["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(r["--persona-toggle-group-radius"]=m.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let ye=x.toolbar;ye.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,r["--persona-dropdown-bg"]=(It=r["--persona-dropdown-bg"])!=null?It:ye.copyMenuBackground),ye.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,r["--persona-dropdown-border"]=(Tr=r["--persona-dropdown-border"])!=null?Tr:ye.copyMenuBorder),ye.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,r["--persona-dropdown-shadow"]=(oo=r["--persona-dropdown-shadow"])!=null?oo:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(pn=r["--persona-dropdown-radius"])!=null?pn:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Vo=r["--persona-dropdown-item-hover-bg"])!=null?Vo:ye.copyMenuItemHoverBackground),ye.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(x!=null&&x.tab){let ye=x.tab;ye.background&&(r["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(r["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(r["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(r["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(r["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(r["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(r["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(x!=null&&x.pane){let ye=x.pane;if(ye.toolbarBackground){let Wr=(un=Wa(e,ye.toolbarBackground))!=null?un:ye.toolbarBackground;r["--persona-artifact-toolbar-bg"]=Wr}}return r}var ih={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Pb={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},lh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},vs=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Rb=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":vs()},Vc=e=>Rb(e),Ib=e=>Ha(e),Wb=e=>{var r;let t=Ha(void 0,{validate:!1});return Ha({...e,palette:{...t.palette,colors:{...Pb.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Ba=e=>{let t=Vc(e),r=lh(e==null?void 0:e.theme),o=lh(e==null?void 0:e.darkTheme);return t==="dark"?Wb(bs(r!=null?r:{},o!=null?o:{})):Ib(r)},Hb=e=>Ri(e),Tn=(e,t)=>{let r=Ba(t),o=Hb(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},Ii=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(vs())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(vs());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(r=>r())}};var dh=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:u=>u.getAttribute("im-preserve")==="true",shouldReAppend:u=>u.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(u,m,x={}){u=p(u);let b=f(m),L=l(u,b,x),E=n(L,()=>i(L,u,b,A=>A.morphStyle==="innerHTML"?(a(A,u,b),Array.from(u.childNodes)):o(A,u,b)));return L.pantry.remove(),E}function o(u,m,x){let b=f(m);return a(u,b,x,m,m.nextSibling),Array.from(b.childNodes)}function n(u,m){var T;if(!u.config.restoreFocus)return m();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return m();let{id:b,selectionStart:L,selectionEnd:E}=x,A=m();return b&&b!==((T=document.activeElement)==null?void 0:T.getAttribute("id"))&&(x=u.target.querySelector(`[id="${b}"]`),x==null||x.focus()),x&&!x.selectionEnd&&E&&x.setSelectionRange(L,E),A}let a=(function(){function u(y,S,v,M=null,W=null){S instanceof HTMLTemplateElement&&v instanceof HTMLTemplateElement&&(S=S.content,v=v.content),M||(M=S.firstChild);for(let H of v.childNodes){if(M&&M!=W){let D=x(y,H,M,W);if(D){D!==M&&L(y,M,D),s(D,H,y),M=D.nextSibling;continue}}if(H instanceof Element){let D=H.getAttribute("id");if(y.persistentIds.has(D)){let O=E(S,D,M,y);s(O,H,y),M=O.nextSibling;continue}}let I=m(S,H,M,y);I&&(M=I.nextSibling)}for(;M&&M!=W;){let H=M;M=M.nextSibling,b(y,H)}}function m(y,S,v,M){if(M.callbacks.beforeNodeAdded(S)===!1)return null;if(M.idMap.has(S)){let W=document.createElement(S.tagName);return y.insertBefore(W,v),s(W,S,M),M.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(S,!0);return y.insertBefore(W,v),M.callbacks.afterNodeAdded(W),W}}let x=(function(){function y(M,W,H,I){let D=null,O=W.nextSibling,J=0,me=H;for(;me&&me!=I;){if(v(me,W)){if(S(M,me,W))return me;D===null&&(M.idMap.has(me)||(D=me))}if(D===null&&O&&v(me,O)&&(J++,O=O.nextSibling,J>=2&&(D=void 0)),M.activeElementAndParents.includes(me))break;me=me.nextSibling}return D||null}function S(M,W,H){let I=M.idMap.get(W),D=M.idMap.get(H);if(!D||!I)return!1;for(let O of I)if(D.has(O))return!0;return!1}function v(M,W){var D,O,J;let H=M,I=W;return H.nodeType===I.nodeType&&H.tagName===I.tagName&&(!((D=H.getAttribute)!=null&&D.call(H,"id"))||((O=H.getAttribute)==null?void 0:O.call(H,"id"))===((J=I.getAttribute)==null?void 0:J.call(I,"id")))}return y})();function b(y,S){var v;if(y.idMap.has(S))T(y.pantry,S,null);else{if(y.callbacks.beforeNodeRemoved(S)===!1)return;(v=S.parentNode)==null||v.removeChild(S),y.callbacks.afterNodeRemoved(S)}}function L(y,S,v){let M=S;for(;M&&M!==v;){let W=M;M=M.nextSibling,b(y,W)}return M}function E(y,S,v,M){var H,I;let W=((I=(H=M.target).getAttribute)==null?void 0:I.call(H,"id"))===S&&M.target||M.target.querySelector(`[id="${S}"]`)||M.pantry.querySelector(`[id="${S}"]`);return A(W,M),T(y,W,v),W}function A(y,S){let v=y.getAttribute("id");for(;y=y.parentNode;){let M=S.idMap.get(y);M&&(M.delete(v),M.size||S.idMap.delete(y))}}function T(y,S,v){if(y.moveBefore)try{y.moveBefore(S,v)}catch{y.insertBefore(S,v)}else y.insertBefore(S,v)}return u})(),s=(function(){function u(A,T,y){return y.ignoreActive&&A===document.activeElement?null:(y.callbacks.beforeNodeMorphed(A,T)===!1||(A instanceof HTMLHeadElement&&y.head.ignore||(A instanceof HTMLHeadElement&&y.head.style!=="morph"?c(A,T,y):(m(A,T,y),E(A,y)||a(y,A,T))),y.callbacks.afterNodeMorphed(A,T)),A)}function m(A,T,y){let S=T.nodeType;if(S===1){let v=A,M=T,W=v.attributes,H=M.attributes;for(let I of H)L(I.name,v,"update",y)||v.getAttribute(I.name)!==I.value&&v.setAttribute(I.name,I.value);for(let I=W.length-1;0<=I;I--){let D=W[I];if(D&&!M.hasAttribute(D.name)){if(L(D.name,v,"remove",y))continue;v.removeAttribute(D.name)}}E(v,y)||x(v,M,y)}(S===8||S===3)&&A.nodeValue!==T.nodeValue&&(A.nodeValue=T.nodeValue)}function x(A,T,y){if(A instanceof HTMLInputElement&&T instanceof HTMLInputElement&&T.type!=="file"){let S=T.value,v=A.value;b(A,T,"checked",y),b(A,T,"disabled",y),T.hasAttribute("value")?v!==S&&(L("value",A,"update",y)||(A.setAttribute("value",S),A.value=S)):L("value",A,"remove",y)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&T instanceof HTMLOptionElement)b(A,T,"selected",y);else if(A instanceof HTMLTextAreaElement&&T instanceof HTMLTextAreaElement){let S=T.value,v=A.value;if(L("value",A,"update",y))return;S!==v&&(A.value=S),A.firstChild&&A.firstChild.nodeValue!==S&&(A.firstChild.nodeValue=S)}}function b(A,T,y,S){let v=T[y],M=A[y];if(v!==M){let W=L(y,A,"update",S);W||(A[y]=T[y]),v?W||A.setAttribute(y,""):L(y,A,"remove",S)||A.removeAttribute(y)}}function L(A,T,y,S){return A==="value"&&S.ignoreActiveValue&&T===document.activeElement?!0:S.callbacks.beforeAttributeUpdated(A,T,y)===!1}function E(A,T){return!!T.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return u})();function i(u,m,x,b){if(u.head.block){let L=m.querySelector("head"),E=x.querySelector("head");if(L&&E){let A=c(L,E,u);return Promise.all(A).then(()=>{let T=Object.assign(u,{head:{block:!1,ignore:!0}});return b(T)})}}return b(u)}function c(u,m,x){let b=[],L=[],E=[],A=[],T=new Map;for(let S of m.children)T.set(S.outerHTML,S);for(let S of u.children){let v=T.has(S.outerHTML),M=x.head.shouldReAppend(S),W=x.head.shouldPreserve(S);v||W?M?L.push(S):(T.delete(S.outerHTML),E.push(S)):x.head.style==="append"?M&&(L.push(S),A.push(S)):x.head.shouldRemove(S)!==!1&&L.push(S)}A.push(...T.values());let y=[];for(let S of A){let v=document.createRange().createContextualFragment(S.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(v)!==!1){if("href"in v&&v.href||"src"in v&&v.src){let M,W=new Promise(function(H){M=H});v.addEventListener("load",function(){M()}),y.push(W)}u.appendChild(v),x.callbacks.afterNodeAdded(v),b.push(v)}}for(let S of L)x.callbacks.beforeNodeRemoved(S)!==!1&&(u.removeChild(S),x.callbacks.afterNodeRemoved(S));return x.head.afterHeadMorphed(u,{added:b,kept:E,removed:L}),y}let l=(function(){function u(y,S,v){let{persistentIds:M,idMap:W}=A(y,S),H=m(v),I=H.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(I))throw`Do not understand how to morph style ${I}`;return{target:y,newContent:S,config:H,morphStyle:I,ignoreActive:H.ignoreActive,ignoreActiveValue:H.ignoreActiveValue,restoreFocus:H.restoreFocus,idMap:W,persistentIds:M,pantry:x(),activeElementAndParents:b(y),callbacks:H.callbacks,head:H.head}}function m(y){let S=Object.assign({},t);return Object.assign(S,y),S.callbacks=Object.assign({},t.callbacks,y.callbacks),S.head=Object.assign({},t.head,y.head),S}function x(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function b(y){let S=[],v=document.activeElement;if((v==null?void 0:v.tagName)!=="BODY"&&y.contains(v))for(;v&&(S.push(v),v!==y);)v=v.parentElement;return S}function L(y){var v;let S=Array.from(y.querySelectorAll("[id]"));return(v=y.getAttribute)!=null&&v.call(y,"id")&&S.push(y),S}function E(y,S,v,M){for(let W of M){let H=W.getAttribute("id");if(S.has(H)){let I=W;for(;I;){let D=y.get(I);if(D==null&&(D=new Set,y.set(I,D)),D.add(H),I===v)break;I=I.parentElement}}}}function A(y,S){let v=L(y),M=L(S),W=T(v,M),H=new Map;E(H,W,y,v);let I=S.__idiomorphRoot||S;return E(H,W,I,M),{persistentIds:W,idMap:H}}function T(y,S){let v=new Set,M=new Map;for(let{id:H,tagName:I}of y)M.has(H)?v.add(H):M.set(H,I);let W=new Set;for(let{id:H,tagName:I}of S)W.has(H)?v.add(H):M.get(H)===I&&W.add(H);for(let H of v)W.delete(H);return W}return u})(),{normalizeElement:p,normalizeParent:f}=(function(){let u=new WeakSet;function m(E){return E instanceof Document?E.documentElement:E}function x(E){if(E==null)return document.createElement("div");if(typeof E=="string")return x(L(E));if(u.has(E))return E;if(E instanceof Node){if(E.parentNode)return new b(E);{let A=document.createElement("div");return A.append(E),A}}else{let A=document.createElement("div");for(let T of[...E])A.append(T);return A}}class b{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],T=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;T&&T!=this.nextSibling;)A.push(T),T=T.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((T,y)=>{if(y instanceof Element){y.matches(A)&&T.push(y);let S=y.querySelectorAll(A);for(let v=0;v<S.length;v++)T.push(S[v])}return T},[])}insertBefore(A,T){return this.realParentNode.insertBefore(A,T)}moveBefore(A,T){return this.realParentNode.moveBefore(A,T)}get __idiomorphRoot(){return this.originalNode}}function L(E){let A=new DOMParser,T=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(T.match(/<\/html>/)||T.match(/<\/head>/)||T.match(/<\/body>/)){let y=A.parseFromString(E,"text/html");if(T.match(/<\/html>/))return u.add(y),y;{let S=y.firstChild;return S&&u.add(S),S}}else{let S=A.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return u.add(S),S}}return{normalizeElement:m,normalizeParent:x}})();return{morph:r,defaults:t}})();var Wi=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;dh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",l=(i=a.textContent)!=null?i:"";if(c!==l)return}return!1}}}}})};var ch=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Hi={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:{...Hi}}}function uh(e,t){var r,o,n,a,s,i,c,l,p,f,u,m,x,b,L,E,A,T,y,S,v,M,W,H,I,D,O,J,me,de,te,Ae,Ie,le,Ce,se,ie,pe;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(u=(f=e.approval)==null?void 0:f.status)!=null?u:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(L=(b=e.toolCall)==null?void 0:b.name)!=null?L:"",(T=(A=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:A.length)!=null?T:0,(M=(v=(S=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:S[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?M:"",typeof((W=e.toolCall)==null?void 0:W.args)=="string"?e.toolCall.args.length:(H=e.toolCall)!=null&&H.args?JSON.stringify(e.toolCall.args).length:0,(O=(D=(I=e.reasoning)==null?void 0:I.chunks)==null?void 0:D.length)!=null?O:0,(te=(de=(me=(J=e.reasoning)==null?void 0:J.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:de.length)!=null?te:0,(Ce=(le=(Ie=(Ae=e.reasoning)==null?void 0:Ae.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:le.slice(-32))!=null?Ce:"",(ie=(se=e.contentParts)==null?void 0:se.length)!=null?ie:0,(pe=e.stopReason)!=null?pe:"",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 Bi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function en(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ta(e,t){return en(e)-e.scrollTop<=t}function Di(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,p=r-o;return s||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:r}:!t&&n&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function Fi(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 Cr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Sr=1e5,En=Sr+1;var ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Bb=["pre","code","a","script","style"],Ni=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}},wh=[{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"}],Cs=new Map;for(let e of wh)Cs.set(e.name,e);var ra=e=>{Cs.set(e.name,e)},jc=e=>{wh.some(t=>t.name===e)||Cs.delete(e)},Gc=()=>Array.from(Cs.keys()),Ss=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Cs.get(e))!=null?o:null},Oi=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
20
- `);return a<0?"":e.slice(0,a)}return e},Db=(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},Fb=(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},zc=/\s/,Nb=(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},Ob=(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(zc.test(a[i])){let l=i;for(;l<a.length&&zc.test(a[l]);)l+=1;s.appendChild(o.createTextNode(a.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<a.length&&!zc.test(a[p]);)l.appendChild(Db(o,a[p],t,r.value)),r.value+=1,p+=1;s.appendChild(l),i=p}n.replaceChild(s,e)},_b=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?s.appendChild(o.createTextNode(l)):(s.appendChild(Fb(o,l,t,r.value)),r.value+=1));n.replaceChild(s,e)},As=(e,t,r,o)=>{var f,u;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((f=o==null?void 0:o.skipTags)!=null?f:Bb).map(m=>m.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)Nb(c,a)||i.push(c),c=s.nextNode();let l={value:(u=o==null?void 0:o.startIndex)!=null?u:0},p=t==="char"?Ob:_b;for(let m of i)p(m,r,l);return n.innerHTML},_i=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ms=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},vh=new WeakMap,Ub=(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)},$c=new WeakMap,qb=(e,t)=>{if(!e.onAttach)return;let r=$c.get(t);if(r||(r=new Map,$c.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},Ch=e=>{let t=$c.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},Kc=(e,t)=>{Ub(e,t),qb(e,t)};function Xc(e,t=Sr){let r=e.style.position,o=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=o,e.style.isolation=n}}var Ts=0,kn=null;function Jc(e=document){var r;if(Ts++,Ts===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;kn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Ts=Math.max(0,Ts-1),Ts===0&&kn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=kn.originalOverflow,n.style.position=kn.originalPosition,n.style.top=kn.originalTop,n.style.width=kn.originalWidth,a.scrollTo(0,kn.scrollY),kn=null}}}var Es={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},nr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Ln=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},Qr=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Es.side,width:(n=t==null?void 0:t.width)!=null?n:Es.width,animate:(a=t==null?void 0:t.animate)!=null?a:Es.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:Es.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Es.maxHeight}};var wo={"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 Vb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ui=(e,t={})=>{var L,E,A,T,y,S;let{showClose:r=!0,wrapperClassName:o=Vb,buttonSize:n,iconSize:a="28px"}=t,s=(L=e==null?void 0:e.launcher)!=null?L:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=w("div",o),l=(A=s.closeButtonTooltipText)!=null?A:"Close chat",p=(T=s.closeButtonShowTooltip)!=null?T:!0,f=(y=s.closeButtonIconName)!=null?y:"x",u=(S=s.closeButtonIconText)!=null?S:"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=At("button",{className:ss("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||Pr.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),b=fe(f,a,"currentColor",1);if(b?(b.style.display="block",x.appendChild(b)):x.textContent=u,c.appendChild(x),p&&l){let v=null,M=()=>{if(v)return;let H=x.ownerDocument,I=H.body;if(!I)return;v=No(H,"div","persona-clear-chat-tooltip"),v.textContent=l;let D=No(H,"div");D.className="persona-clear-chat-tooltip-arrow",v.appendChild(D);let O=x.getBoundingClientRect();v.style.position="fixed",v.style.zIndex=String(En),v.style.left=`${O.left+O.width/2}px`,v.style.top=`${O.top-8}px`,v.style.transform="translate(-50%, -100%)",I.appendChild(v)},W=()=>{v&&v.parentNode&&(v.parentNode.removeChild(v),v=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}},zb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",qi=(e,t={})=>{var v,M,W,H,I,D,O,J,me,de,te,Ae,Ie;let{wrapperClassName:r=zb,buttonSize:o,iconSize:n="20px"}=t,s=(M=((v=e==null?void 0:e.launcher)!=null?v:{}).clearChat)!=null?M:{},i=(W=o!=null?o:s.size)!=null?W:"32px",c=(H=s.iconName)!=null?H:"refresh-cw",l=(I=s.iconColor)!=null?I:"",p=(D=s.backgroundColor)!=null?D:"",f=(O=s.borderWidth)!=null?O:"",u=(J=s.borderColor)!=null?J:"",m=(me=s.borderRadius)!=null?me:"",x=(de=s.paddingX)!=null?de:"",b=(te=s.paddingY)!=null?te:"",L=(Ae=s.tooltipText)!=null?Ae:"Clear chat",E=(Ie=s.showTooltip)!=null?Ie:!0,A=w("div",r),T=!!(f||u),y=At("button",{className:ss("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":L},style:{height:i,width:i,color:l||Pr.actionIconColor,backgroundColor:p||void 0,border:T?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:b||void 0,paddingBottom:b||void 0}}),S=fe(c,n,"currentColor",1);if(S&&(S.style.display="block",y.appendChild(S)),A.appendChild(y),E&&L){let le=null,Ce=()=>{if(le)return;let ie=y.ownerDocument,pe=ie.body;if(!pe)return;le=No(ie,"div","persona-clear-chat-tooltip"),le.textContent=L;let Ee=No(ie,"div");Ee.className="persona-clear-chat-tooltip-arrow",le.appendChild(Ee);let De=y.getBoundingClientRect();le.style.position="fixed",le.style.zIndex=String(En),le.style.left=`${De.left+De.width/2}px`,le.style.top=`${De.top-8}px`,le.style.transform="translate(-50%, -100%)",pe.appendChild(le)},se=()=>{le&&le.parentNode&&(le.parentNode.removeChild(le),le=null)};A.addEventListener("mouseenter",Ce),A.addEventListener("mouseleave",se),y.addEventListener("focus",Ce),y.addEventListener("blur",se),A._cleanupTooltip=()=>{se(),A.removeEventListener("mouseenter",Ce),A.removeEventListener("mouseleave",se),y.removeEventListener("focus",Ce),y.removeEventListener("blur",se)}}return{button:y,wrapper:A}};var Pr={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))"},tn=e=>{var S,v,M,W,H,I,D,O,J,me,de,te,Ae,Ie,le,Ce;let{config:t,showClose:r=!0}=e,o=At("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),n=(S=t==null?void 0:t.launcher)!=null?S:{},a=(v=n.headerIconSize)!=null?v:"48px",s=(M=n.closeButtonPlacement)!=null?M:"inline",i=(W=n.headerIconHidden)!=null?W:!1,c=n.headerIconName,l=At("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(c){let se=parseFloat(a)||24,ie=fe(c,se*.6,"currentColor",1);ie?l.replaceChildren(ie):l.textContent=(I=(H=t==null?void 0:t.launcher)==null?void 0:H.agentIconText)!=null?I:"\u{1F4AC}"}else if((D=t==null?void 0:t.launcher)!=null&&D.iconUrl){let se=w("img");se.src=t.launcher.iconUrl,se.alt="",se.className="persona-rounded-xl persona-object-cover",se.style.height=a,se.style.width=a,l.replaceChildren(se)}else l.textContent=(J=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?J:"\u{1F4AC}";let p=w("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=At("span",{className:"persona-text-base persona-font-semibold",text:(de=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?de:"Chat Assistant",style:{color:Pr.titleColor}}),u=At("span",{className:"persona-text-xs",text:(Ae=(te=t==null?void 0:t.launcher)==null?void 0:te.subtitle)!=null?Ae:"Here to help you get answers fast",style:{color:Pr.subtitleColor}});p.append(f,u),i?o.append(p):o.append(l,p);let m=(Ie=n.clearChat)!=null?Ie:{},x=(le=m.enabled)!=null?le:!0,b=(Ce=m.placement)!=null?Ce:"inline",L=null,E=null;if(x){let ie=qi(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});L=ie.button,E=ie.wrapper,b==="top-right"&&(E.style.right="48px"),b==="inline"&&o.appendChild(E)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&b==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:T,wrapper:y}=Ui(t,{showClose:r,wrapperClassName:A});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:l,headerTitle:f,headerSubtitle:u,closeButton:T,closeButtonWrapper:y,clearChatButton:L,clearChatButtonWrapper:E}},oa=(e,t,r)=>{var s,i,c,l;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(l=(c=o.clearChat)==null?void 0:c.placement)!=null?l:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Pn(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=w("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(En)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of t){if(m.dividerBefore){let L=document.createElement("hr");s.appendChild(L)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let L=fe(m.icon,16,"currentColor",1.5);L&&x.appendChild(L)}let b=document.createElement("span");b.textContent=m.label,x.appendChild(b),x.addEventListener("click",L=>{L.stopPropagation(),p(),r(m.id)}),s.appendChild(x)}let i=null;function c(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function l(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!s.contains(x.target)&&!o.contains(x.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){s.classList.add("persona-hidden"),i==null||i(),i=null}function f(){s.classList.contains("persona-hidden")?l():p()}function u(){p(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:p,toggle:f,destroy:u}}function cr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=w("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let l=fe(t,o!=null?o:16,"currentColor",n!=null?n:2);if(l&&c.appendChild(l),s&&c.addEventListener("click",s),i)for(let[p,f]of Object.entries(i))c.setAttribute(p,f);return c}function ks(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+n,s&&(l+=" "+s);let p=w("button",l);if(p.type="button",p.setAttribute("aria-label",r),t){let u=fe(t,a!=null?a:14,"currentColor",2);u&&p.appendChild(u)}let f=w("span");if(f.textContent=r,p.appendChild(f),i&&p.addEventListener("click",i),c)for(let[u,m]of Object.entries(c))p.setAttribute(u,m);return p}function Sh(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=w("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===s?"true":"false")}for(let p of t){let f;p.icon?f=cr({icon:p.icon,label:p.label,onClick:()=>{s=p.id,c(),o(p.id)}}):(f=w("button","persona-icon-btn"),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{s=p.id,c(),o(p.id)})),f.setAttribute("aria-pressed",p.id===s?"true":"false"),i.push({id:p.id,btn:f}),a.appendChild(f)}function l(p){s=p,c()}return{element:a,setSelected:l}}function Vi(e){var m,x;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,l=w("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=w("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let f=fe(r,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",l.appendChild(f)),c&&(l.style.borderRadius=(m=c.borderRadius)!=null?m:"10px",l.style.padding=(x=c.padding)!=null?x:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var b,L;l.style.backgroundColor=(b=c.background)!=null?b:"",l.style.borderColor=(L=c.border)!=null?L:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let u=Pn({items:o,onSelect:b=>{l.setAttribute("aria-expanded","false"),n(b)},anchor:l,position:a,portal:s});return s||l.appendChild(u.element),l.addEventListener("click",b=>{b.stopPropagation();let L=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",L?"false":"true"),u.toggle()}),l.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),l.click())}),{element:l,setLabel:b=>{p.textContent=b,l.setAttribute("aria-label",b)},open:()=>{l.setAttribute("aria-expanded","true"),u.show()},close:()=>{l.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let b=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",b?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),l.remove()}}}var Qc=e=>{var o;let t=tn({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 $b(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=w("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let c=fe(s.icon,14,"currentColor",2);c&&i.appendChild(c)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let c=w("div","persona-relative");c.appendChild(i);let l=Pn({items:s.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:c,position:"bottom-left"});c.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var Yc=e=>{var A,T,y,S,v,M,W,H,I;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(A=t==null?void 0:t.launcher)!=null?A:{},i=w("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=n==null?void 0:n.titleMenu,l,p;if(c)l=Vi({label:(T=s.title)!=null?T:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,l.style.color=Pr.titleColor,p=(y=l.querySelector(".persona-combo-btn-label"))!=null?y:l;else{if(l=w("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=w("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Pr.titleColor,p.textContent=(S=s.title)!=null?S:"Chat Assistant",l.appendChild(p),$b(l,n==null?void 0:n.trailingActions,(v=n==null?void 0:n.onAction)!=null?v:a),n!=null&&n.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let O=n.onTitleClick;l.addEventListener("click",J=>{J.target.closest("button")||O()}),l.addEventListener("keydown",J=>{(J.key==="Enter"||J.key===" ")&&(J.preventDefault(),O())})}let D=n==null?void 0:n.titleRowHover;D&&(l.style.borderRadius=(M=D.borderRadius)!=null?M:"10px",l.style.padding=(W=D.padding)!=null?W:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var O,J;l.style.backgroundColor=(O=D.background)!=null?O:"",l.style.borderColor=(J=D.border)!=null?J:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let f=(H=s.closeButtonSize)!=null?H:"32px",u=w("div",""),m=w("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none",m.style.color=s.closeButtonColor||Pr.actionIconColor;let x=(I=s.closeButtonIconName)!=null?I:"x",b=fe(x,"28px","currentColor",1);b?m.appendChild(b):m.textContent="\xD7",o&&m.addEventListener("click",o),u.appendChild(m),i.appendChild(u);let L=w("div");L.style.display="none";let E=w("span");return E.style.display="none",{header:i,iconHolder:L,headerTitle:p,headerSubtitle:E,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},zi={default:Qc,minimal:Yc},Zc=e=>{var t;return(t=zi[e])!=null?t:zi.default},Da=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let l=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=w("div");p.style.display="none";let f=w("span"),u=w("span"),m=w("button");m.style.display="none";let x=w("div");return x.style.display="none",{header:l,iconHolder:p,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=Zc(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 $i=e=>{var s,i;let t=w("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}},ji=e=>{var S,v,M,W,H,I,D,O,J,me,de,te;let t=(S=e==null?void 0:e.sendButton)!=null?S:{},r=(v=t.useIcon)!=null?v:!1,o=(M=t.iconText)!=null?M:"\u2191",n=t.iconName,a=(W=t.stopIconName)!=null?W:"square",s=(H=t.tooltipText)!=null?H:"Send message",i=(I=t.stopTooltipText)!=null?I:"Stop generating",c=(O=(D=e==null?void 0:e.copy)==null?void 0:D.sendButtonLabel)!=null?O:"Send",l=(me=(J=e==null?void 0:e.copy)==null?void 0:J.stopButtonLabel)!=null?me:"Stop",p=(de=t.showTooltip)!=null?de:!1,f=(te=t.size)!=null?te:"40px",u=t.backgroundColor,m=t.textColor,x=w("div","persona-send-button-wrapper"),b=At("button",{className:ss("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!u&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?f:void 0,height:r?f:void 0,minWidth:r?f:void 0,minHeight:r?f:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:r&&u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),L=null,E=null;if(r){let Ae=parseFloat(f)||24,Ie=(m==null?void 0:m.trim())||"currentColor";n?(L=fe(n,Ae,Ie,2),L?b.appendChild(L):b.textContent=o):b.textContent=o,E=fe(a,Ae,Ie,2)}else b.textContent=c;let A=null;p&&s&&(A=w("div","persona-send-button-tooltip"),A.textContent=s,x.appendChild(A)),b.setAttribute("aria-label",s),x.appendChild(b);let T="send";return{button:b,wrapper:x,setMode:Ae=>{if(Ae===T)return;T=Ae;let Ie=Ae==="stop"?i:s;if(b.setAttribute("aria-label",Ie),A&&(A.textContent=Ie),r){if(L&&E){let le=Ae==="stop"?E:L;b.replaceChildren(le)}}else b.textContent=Ae==="stop"?l:c}}},Gi=e=>{var A,T,y,S,v,M,W,H,I,D,O,J;let t=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((T=t.provider)==null?void 0:T.type)==="runtype";if(!(o||n))return null;let s=(S=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?S:"40px",i=(v=t.iconName)!=null?v:"mic",c=(M=t.iconSize)!=null?M:s,l=parseFloat(c)||24,p=(H=t.backgroundColor)!=null?H:(W=e==null?void 0:e.sendButton)==null?void 0:W.backgroundColor,f=(D=t.iconColor)!=null?D:(I=e==null?void 0:e.sendButton)==null?void 0:I.textColor,u=w("div","persona-send-button-wrapper"),m=At("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),b=fe(i,l,f||"currentColor",1.5);b?m.appendChild(b):m.textContent="\u{1F3A4}",u.appendChild(m);let L=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((J=t.showTooltip)!=null?J:!1)&&L){let me=w("div","persona-send-button-tooltip");me.textContent=L,u.appendChild(me)}return{button:m,wrapper:u}},Ki=e=>{var x,b,L,E,A,T,y,S;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(L=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?L:"40px",o=w("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=w("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:Zo).join(","),n.multiple=((A=t.maxFiles)!=null?A:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(T=t.buttonIconName)!=null?T:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),l=w("div","persona-send-button-wrapper"),p=At("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let f=fe(a,c,"currentColor",1.5);f?p.appendChild(f):p.textContent="\u{1F4CE}",p.addEventListener("click",v=>{v.preventDefault(),n.click()}),l.appendChild(p);let u=(S=t.buttonTooltipText)!=null?S:"Attach file",m=w("div","persona-send-button-tooltip");return m.textContent=u,l.appendChild(m),{button:p,wrapper:l,input:n,previewsContainer:o}},Xi=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=w("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let l=w("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=a,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=a;return o},Ji=()=>At("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Fa=e=>{var x,b,L,E,A,T;let{config:t}=e,r=At("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Ji(),n=At("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=$i(t);s();let i=ji(t),c=Gi(t),l=Ki(t),p=Xi(t);l&&(l.previewsContainer.style.gap="8px",n.append(l.previewsContainer,l.input)),n.append(a);let f=At("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=w("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=w("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&u.append(l.wrapper),c&&m.append(c.wrapper),m.append(i.wrapper),f.append(u,m),n.append(f),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(l==null?void 0:l.button)&&y.target!==(l==null?void 0:l.wrapper)&&a.focus()}),r.append(o,n,p),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:p,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var Ah=()=>{let e=At("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=w("span","persona-pill-peek__icon"),r=fe("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=w("span","persona-pill-peek__text"),n=w("span","persona-pill-peek__caret"),a=fe("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Mh=e=>{var x,b,L,E,A,T;let{config:t}=e,r=At("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ji();o.style.display="none";let n=Xi(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=$i(t);a.style.maxHeight="100px",s();let i=ji(t),c=Gi(t),l=Ki(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=At("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=w("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&f.append(l.wrapper);let u=w("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&u.append(c.wrapper),u.append(i.wrapper),p.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(l==null?void 0:l.button)&&y.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&p.append(l.input),p.append(f,a,u),l&&r.append(l.previewsContainer),r.append(p,o,n);let m=p;return{footer:r,suggestions:o,composerForm:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:n,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var Th=e=>{var p,f,u,m,x,b,L,E,A,T,y,S,v,M,W,H,I;let t=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?f:!0,r=nr(e);if(Ln(e)){let D=(m=(u=e==null?void 0:e.launcher)==null?void 0:u.composerBar)!=null?m:{},O=w("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(x=D.expandedSize)!=null?x:"anchored",O.style.zIndex=String((L=(b=e==null?void 0:e.launcher)==null?void 0:b.zIndex)!=null?L:Sr);let J=w("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");J.style.width="100%",O.appendChild(J);let me=w("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=D.expandedSize)!=null?E:"anchored",me.style.zIndex=String((T=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?T:Sr),{wrapper:O,panel:J,pillRoot:me}}if(r){let D=w("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=w("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return D.appendChild(O),{wrapper:D,panel:O}}if(!t){let D=w("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=w("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),J=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?S:"100%";return D.style.width=J,O.style.width="100%",D.appendChild(O),{wrapper:D,panel:O}}let n=(v=e==null?void 0:e.launcher)!=null?v:{},a=n.position&&wo[n.position]?wo[n.position]:wo["bottom-right"],s=w("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:Sr);let i=w("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(I=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?I:e==null?void 0:e.launcherWidth,l=c!=null?c:Jr;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},jb=(e,t)=>{var y,S,v,M,W,H,I,D,O;let r=w("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}=Ui(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(v=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:S.enabled)!=null?v:!0,s=null,i=null;if(a){let J=qi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=J.button,i=J.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=At("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=At("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});l.style.setProperty("scrollbar-gutter","stable");let p=At("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(W=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?W:"Hello \u{1F44B}"}),f=At("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),u=At("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,f),m=w("div","persona-flex persona-flex-col persona-gap-3"),x=(D=e==null?void 0:e.layout)==null?void 0:D.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let L=At("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=Mh({config:e}),{root:A,textNode:T}=Ah();return r.append(c,n,l,L),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:m,composerOverlay:L,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:p,introSubtitle:f,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:w("span"),headerTitle:w("span"),headerSubtitle:w("span"),header:c,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:A,peekTextNode:T}},Eh=(e,t=!0)=>{var L,E,A,T,y,S,v,M,W;if(Ln(e))return jb(e,t);let r=At("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=(L=e==null?void 0:e.layout)==null?void 0:L.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?Da(e,o,{showClose:t}):tn({config:e,showClose:t}),s=At("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let i=At("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(T=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?T:"Hello \u{1F44B}"}),c=At("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(S=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?S:"Ask anything about your account or products."}),l=At("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:nr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),p=w("div","persona-flex persona-flex-col persona-gap-3"),f=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(l.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(l,p);let m=Fa({config:e}),x=((W=e==null?void 0:e.layout)==null?void 0:W.showFooter)!==!1;n?oa(r,a,e):(a.header.style.display="none",oa(r,a,e)),r.append(s);let b=At("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return x||(m.footer.style.display="none"),r.append(m.footer),r.append(b),{container:r,body:s,messagesWrapper:p,composerOverlay:b,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:c,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var ep=(e,t)=>{let r=w("button");r.type="button",r.innerHTML=`
19
+ _Details: ${r.message}_`:o}var Ts=e=>({isError:!0,content:[{type:"text",text:e}]}),xh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,yh=e=>Tn(e)||e===Co,Na=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 la(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,l,p,f;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall,g=!!(u!=null&&u.name)&&(Tn(u.name)||u.name===Co&&((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&&g&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(f=(p=this.callbacks).onError)==null||f.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new aa(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,l;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=(l=(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)!=null?l:this.config.agentId;!r||!o||!this.config.clientToken||Ql().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ms((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,c;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=Wn.isSupported()?new Wn({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let l=(o=t.host)!=null?o:this.config.apiUrl,p=(c=(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)!=null?c:this.config.agentId,f=this.config.clientToken,u=t.browserFallback!==!1;if(l&&p&&f)return Ql().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:x})=>{let b=new g({host:l,agentId:p,clientToken:f,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return u&&r?new x(b,r,{onFallback:L=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${L.message}`)}):b});if(u&&r)return f&&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,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:c,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,l;(l=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||l.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,l;this.voiceStatus=i,this.voiceActive=i==="listening",(l=(c=this.callbacks).onVoiceStatusChanged)==null||l.call(c,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,o,n,a,s,i,c,l,p,f,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:(a=(n=(o=t.runtype)==null?void 0:o.agentId)!=null?n:this.config.agentId)!=null?a:"",clientToken:(i=(s=t.runtype)==null?void 0:s.clientToken)!=null?i:this.config.clientToken,host:(l=(c=t.runtype)==null?void 0:c.host)!=null?l:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(f=t.runtype)==null?void 0:f.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(!qb(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 aa(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:l=!1,voiceProcessing:p,rawContent:f}=t,g={id:s!=null?s:r==="user"?Da():r==="assistant"?sa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:l,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...f!==void 0&&{rawContent:f}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:l,sequence:p,streaming:f=!1,voiceProcessing:u,rawContent:g}=o,b={id:c!=null?c:n==="user"?Da():n==="assistant"?sa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:f,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};r.push(b)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,l={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var l,p,f,u,g;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let n=Da(),a=sa(),s={id:n,role:"user",content:o||yi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(x){let b=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!b){let L=hh(x,this.config.errorMessage);if(L){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:L,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(x instanceof Error?(f=(p=this.callbacks).onError)==null||f.call(p,x):(g=(u=this.callbacks).onError)==null||g.call(u,new Error(String(x))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort();let t=sa();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let f=hh(l,this.config.errorMessage);if(f){let u={id:t,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,l):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(l))))}}async connectStream(t,r){var n,a,s;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(n=this.abortController)==null||n.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var p,f,u,g,x;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(b=>b.id===n),i={id:n,role:"assistant",content:"",createdAt:(p=s==null?void 0:s.createdAt)!=null?p:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,l=c&&typeof c=="object"?c.onDecision:void 0;try{let b;if(l?b=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):b=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),b){let L=null;if(b instanceof Response){if(!b.ok){let E=await b.json().catch(()=>null);throw new Error((u=E==null?void 0:E.error)!=null?u:`Approval request failed: ${b.status}`)}L=b.body}else b instanceof ReadableStream&&(L=b);L?await this.connectStream(L,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(b){let L=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,L||(x=(g=this.callbacks).onError)==null||x.call(g,b instanceof Error?b:new Error(String(b)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var p,f,u,g,x,b,L,E,A,T,y,S;let o=this.messages.find(v=>v.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let n=(f=t.agentMetadata)==null?void 0:f.executionId,a=(u=t.toolCall)==null?void 0:u.name;if(!n||!a){(x=(g=this.callbacks).onError)==null||x.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let v=(b=t.toolCall)==null?void 0:b.args,M=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(M.length===1){let W=typeof((L=M[0])==null?void 0:L.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=(A=t.toolCall)==null?void 0:A.args,l=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(l.length===0){let v=typeof r=="string"?r:Object.entries(r).map(([M,W])=>`${M}: ${Array.isArray(W)?W.join(", "):W}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=s!=null?s:{};l.forEach((M,W)=>{let H=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!H)return;let I=v[H],F=Array.isArray(I)?I.join(", "):typeof I=="string"?I:"";this.appendMessage({id:`ask-user-q-${i}-${W}`,role:"assistant",content:H,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${W}`,role:"user",content:F||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(n,{[a]:r});if(!v.ok){let M=await v.json().catch(()=>null);throw new Error((T=M==null?void 0:M.error)!=null?T:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(S=(y=this.callbacks).onError)==null||S.call(y,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==Co)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,l,p,f;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async u=>{var S,v,M,W,H,I,F;let g=(S=u.toolCall)==null?void 0:S.name,x=(v=u.toolCall)==null?void 0:v.id;if(!g||!x)return null;let b=`${t}:${x}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(b),o.push(b);let L=this.markWebMcpToolRunning(u),E=(W=(M=u.agentMetadata)==null?void 0:M.webMcpToolCallId)!=null?W:g;if(g===Co)return{dedupeKey:b,resumeKey:E,output:ql(),toolMessage:u,startedAt:L,completedAt:Date.now()};let A=new AbortController;this.webMcpResolveControllers.add(A),n.push(A);let T=this.client.executeWebMcpToolCall(g,(H=u.toolCall)==null?void 0:H.args,A.signal),y;if(!T)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await T}catch(O){let Q=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Q||(F=(I=this.callbacks).onError)==null||F.call(I,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(u,Ts(Q?"Aborted by cancel()":xh(O)),L),this.webMcpInflightKeys.delete(b),null}return A.signal.aborted?(this.markWebMcpToolComplete(u,Ts("Aborted by cancel()"),L),this.webMcpInflightKeys.delete(b),null):{dedupeKey:b,resumeKey:E,output:y,toolMessage:u,startedAt:L,completedAt:Date.now()}})),i=[];try{if(i=s.filter(x=>x!==null),i.length===0)return;let u={};for(let x of i)u[x.resumeKey]=x.output;let g=await this.client.resumeFlow(t,u,{signal:a.signal});if(!g.ok){let x=await g.json().catch(()=>null);throw new Error((c=x==null?void 0:x.error)!=null?c:`Resume failed: ${g.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((l=x.toolMessage.toolCall)==null?void 0:l.name)===Co?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(p=this.callbacks).onError)==null||f.call(p,u instanceof Error?u:new Error(String(u)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,Ts("Aborted by cancel()"),x.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of n)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,b,L,E,A,T,y,S,v,M,W,H;let r=(x=t.agentMetadata)==null?void 0:x.executionId,o=(b=t.toolCall)==null?void 0:b.name,n=(L=t.toolCall)==null?void 0:L.id;if(!r){(A=(E=this.callbacks).onError)==null||A.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let I=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(I)||this.webMcpResolvedKeys.has(I))return;this.webMcpInflightKeys.add(I);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(I)}catch(F){(y=(T=this.callbacks).onError)==null||y.call(T,F instanceof Error?F:new Error(String(F)))}finally{this.webMcpInflightKeys.delete(I)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let l=o===Co,p=(S=t.toolCall)==null?void 0:S.args,f=l?null:this.client.executeWebMcpToolCall(o,p,c),u="execute",g=s;try{let I;if(l?I=ql():f?I=await f:I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),c.aborted){this.markWebMcpToolComplete(t,Ts("Aborted by cancel()"),s);return}let F=(M=(v=t.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?M:o;u="resume",await this.resumeWithToolOutput(r,F,I,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,I,s,g,l?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(I){let F=I instanceof Error&&(I.name==="AbortError"||I.message.includes("aborted")||I.message.includes("abort"));(u==="execute"||F||c.aborted)&&this.markWebMcpToolComplete(t,Ts(F||c.aborted?"Aborted by cancel()":xh(I)),s),F||(H=(W=this.callbacks).onError)==null||H.call(W,I instanceof Error?I:new Error(String(I)))}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=Kl(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Fa(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=Kl(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var p,f,u,g,x,b,L,E,A,T,y,S,v,M,W;if(a!==o)return n;let s={...n,...r};if(((p=n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=n.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(u=s.agentMetadata)!=null?u:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let H=n.approval,I=r.approval;s.approval={...H,...I,executionId:I.executionId||H.executionId,toolName:I.toolName||H.toolName,description:I.description||H.description,toolType:(g=I.toolType)!=null?g:H.toolType,reason:(x=I.reason)!=null?x:H.reason,parameters:(b=I.parameters)!=null?b:H.parameters}}let i=(L=r.toolCall)==null?void 0:L.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,l=(A=r.toolCall)==null?void 0:A.id;if(i&&yh(i)&&c&&l&&((T=r.agentMetadata)==null?void 0:T.awaitingLocalTool)===!0){let H=`${c}:${l}`,I=this.webMcpInflightKeys.has(H),F=this.webMcpResolvedKeys.has(H),O=(y=n.toolCall)==null?void 0:y.name,Q=((S=n.agentMetadata)==null?void 0:S.executionId)===c&&((v=n.toolCall)==null?void 0:v.id)===l&&O!==void 0&&yh(O)&&((M=n.toolCall)==null?void 0:M.status)==="complete";(I||F||Q)&&(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,l;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(l=o.sequence)!=null?l:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var Jl=[["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 Yl=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Zl=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var ed=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var td=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var rd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var od=[["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 nd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var ad=[["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 sd=[["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 id=[["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 ld=[["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 dd=[["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 pd=[["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 ud=[["path",{d:"M20 6 9 17l-5-5"}]];var fd=[["path",{d:"m6 9 6 6 6-6"}]];var md=[["path",{d:"m15 18-6-6 6-6"}]];var gd=[["path",{d:"m9 18 6-6-6-6"}]];var hd=[["path",{d:"m18 15-6-6-6 6"}]];var Ci=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var Si=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var xd=[["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 yd=[["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 bd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var vd=[["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 wd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Cd=[["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 Sd=[["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 Ai=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Mi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Ad=[["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 Md=[["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 Td=[["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 Ed=[["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 kd=[["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 Ld=[["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 Pd=[["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 Rd=[["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 Id=[["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 Wd=[["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 Hd=[["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 Bd=[["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 Ti=[["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 Dd=[["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 Fd=[["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 Nd=[["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 Od=[["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 _d=[["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 Ud=[["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 Ei=[["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 qd=[["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 Vd=[["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 $d=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var zd=[["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 jd=[["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 ki=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Gd=[["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 Kd=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Xd=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var Qd=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Jd=[["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 Yd=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Zd=[["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 ec=[["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 tc=[["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 rc=[["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 oc=[["path",{d:"M5 12h14"}]];var nc=[["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 ac=[["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 sc=[["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 ic=[["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 lc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var dc=[["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 pc=[["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 uc=[["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 fc=[["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 gc=[["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 hc=[["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 xc=[["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 yc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var bc=[["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 vc=[["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 wc=[["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 Cc=[["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 Sc=[["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 Li=[["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 Ac=[["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 Mc=[["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 Tc=[["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 Ec=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Pi=[["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 kc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Lc=[["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 Pc=[["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 Rc=[["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 Ic=[["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 Wc=[["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 Hc=[["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 Bc=[["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 Dc=[["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 Fc=[["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 Ri=[["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 Nc=[["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 Oc=[["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 _c=[["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 Uc=[["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 qc=[["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 Vc=[["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 $c=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var zc=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var Vb={activity:Jl,"arrow-down":Yl,"arrow-up":rd,"arrow-up-right":td,bot:id,"chevron-down":fd,"chevron-up":hd,"chevron-right":gd,"chevron-left":md,check:ud,clipboard:yd,"clipboard-copy":xd,copy:vd,file:Pd,"file-code":Ed,"file-spreadsheet":kd,"file-text":Ld,"image-plus":qd,loader:Gd,"loader-circle":ki,mic:tc,paperclip:ic,"refresh-cw":gc,search:yc,send:bc,"shield-alert":Cc,"shield-check":Sc,"shield-x":Li,square:kc,"thumbs-down":Wc,"thumbs-up":Hc,upload:Oc,"volume-2":Uc,x:$c,user:_c,mail:Xd,phone:pc,calendar:cd,clock:bd,building:ld,"map-pin":Qd,lock:Kd,key:zd,"credit-card":wd,"at-sign":od,hash:Nd,globe:Fd,link:jd,"circle-check":Ci,"circle-x":Si,"triangle-alert":Ri,info:$d,ban:nd,shield:Ac,"arrow-left":Zl,"arrow-right":ed,"external-link":Md,ellipsis:Mi,"ellipsis-vertical":Ai,menu:Yd,house:Ei,plus:fc,minus:oc,pencil:dc,trash:Fc,"trash-2":Dc,save:xc,download:Sd,share:wc,funnel:Ti,settings:vc,"rotate-cw":hc,maximize:Jd,minimize:rc,"shopping-cart":Tc,"shopping-bag":Mc,package:sc,truck:Nc,tag:Ic,gift:Dd,receipt:mc,wallet:Vc,store:Pc,"dollar-sign":Cd,percent:cc,play:uc,pause:lc,"volume-x":qc,camera:pd,image:Vd,film:Id,headphones:Od,"message-circle":Zd,"message-square":ec,bell:ad,heart:_d,star:Lc,eye:Td,"eye-off":Ad,bookmark:sd,"calendar-days":dd,history:Ud,timer:Bc,folder:Bd,"folder-open":Hd,files:Rd,sparkles:Pi,zap:zc,sun:Rc,moon:ac,flag:Wd,monitor:nc,smartphone:Ec},ge=(e,t=24,r="currentColor",o=2)=>{let n=Vb[e];return n?$b(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 $b(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&c.setAttribute(l,String(p))}),n.appendChild(c)}),n}var Ii={allowedTypes:an,maxFileSize:10*1024*1024,maxFiles:4};function zb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function jb(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 da=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ii.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ii.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Ii.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:Ii.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,o,n,a,s,i,c;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,l,"count");continue}let p=ph(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let f=(n=p.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,f);continue}try{let f=await ch(l),u=bi(l)?URL.createObjectURL(l):null,g={id:zb(),file:l,previewUrl:u,contentPart:f};this.attachments.push(g),this.renderPreview(g)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=bi(t.file),o=w("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=w("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=w("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=jb(t.file.type),c=ge(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let l=w("span");l.textContent=uh(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",s.appendChild(l),o.appendChild(s)}let n=w("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=ge("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 bh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Es(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];bh(a)&&bh(n)?r[o]=Es(a,n):r[o]=n}return r}var jr="min(440px, calc(100vw - 24px))",Wi="440px",Gb={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:jr,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)"},It={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Gb,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:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},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 vh(e,t){if(!(!e&&!t))return e?t?Es(e,t):e:t}function Hi(e){var t,r,o,n,a,s,i,c,l,p,f,u,g,x,b,L,E,A,T,y,S;return e?{...It,...e,theme:vh(It.theme,e.theme),darkTheme:vh(It.darkTheme,e.darkTheme),launcher:{...It.launcher,...e.launcher,dock:{...(t=It.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=It.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{...It.copy,...e.copy},sendButton:{...It.sendButton,...e.sendButton},statusIndicator:{...It.statusIndicator,...e.statusIndicator},voiceRecognition:{...It.voiceRecognition,...e.voiceRecognition},features:(()=>{var ne,le,ue,ke,Fe,j,J,Ne,K,pe;let v=(ne=It.features)==null?void 0:ne.artifacts,M=(le=e.features)==null?void 0:le.artifacts,W=(ue=It.features)==null?void 0:ue.scrollToBottom,H=(ke=e.features)==null?void 0:ke.scrollToBottom,I=(Fe=It.features)==null?void 0:Fe.scrollBehavior,F=(j=e.features)==null?void 0:j.scrollBehavior,O=(J=It.features)==null?void 0:J.streamAnimation,Q=(Ne=e.features)==null?void 0:Ne.streamAnimation,he=(K=It.features)==null?void 0:K.askUserQuestion,ce=(pe=e.features)==null?void 0:pe.askUserQuestion,te=v===void 0&&M===void 0?void 0:{...v,...M,layout:{...v==null?void 0:v.layout,...M==null?void 0:M.layout}},Te=W===void 0&&H===void 0?void 0:{...W,...H},We=I===void 0&&F===void 0?void 0:{...I,...F},de=O===void 0&&Q===void 0?void 0:{...O,...Q},Ae=he===void 0&&ce===void 0?void 0:{...he,...ce,styles:{...he==null?void 0:he.styles,...ce==null?void 0:ce.styles}};return{...It.features,...e.features,...Te!==void 0?{scrollToBottom:Te}:{},...We!==void 0?{scrollBehavior:We}:{},...te!==void 0?{artifacts:te}:{},...de!==void 0?{streamAnimation:de}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...It.layout,...e.layout,header:{...(s=It.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=It.layout)==null?void 0:c.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(f=(p=It.layout)==null?void 0:p.messages)==null?void 0:f.avatar,...(g=(u=e.layout)==null?void 0:u.messages)==null?void 0:g.avatar},timestamp:{...(b=(x=It.layout)==null?void 0:x.messages)==null?void 0:b.timestamp,...(E=(L=e.layout)==null?void 0:L.messages)==null?void 0:E.timestamp}},slots:{...(A=It.layout)==null?void 0:A.slots,...(T=e.layout)==null?void 0:T.slots}},markdown:{...It.markdown,...e.markdown,options:{...(y=It.markdown)==null?void 0:y.options,...(S=e.markdown)==null?void 0:S.options}},messageActions:{...It.messageActions,...e.messageActions}}:It}var jc={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"}},Gc={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"}},Kc={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:jr,maxWidth:Wi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Oa(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."))?Oa(e,o):o}function Bi(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=Oa(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 Xc(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 wh(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]=wh(a,n):r[o]=n}return r}function Kb(e,t){return t?wh(e,t):e}function _a(e,t={}){var n,a,s,i,c,l,p,f,u,g,x,b,L;let r={palette:jc,semantic:Gc,components:Kc},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(u=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...r.semantic.colors.feedback,...(x=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(b=e==null?void 0:e.semantic)==null?void 0:b.spacing},typography:{...r.semantic.typography,...(L=e==null?void 0:e.semantic)==null?void 0:L.typography}},components:Kb(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=Xc(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Di(e){var b,L,E,A,T,y,S,v,M,W,H,I,F,O,Q,he,ce,te,Te,We,de,Ae,ne,le,ue,ke,Fe,j,J,Ne,K,pe,qe,ot,xt,Ft,Qt,Ye,xe,X,dt,$e,Ce,be,et,Lt,Z,Ue,Sr,yt,xr,Ao,Mo,P,ee,Me,He,Le,Be,Ge,at,Pt,se,N,ye,Oe,bt,Qe,Wt,At,gt,kt,Xt,Ot,tr,To,zo,lo,co,dn,$t,po,jo,Hr,Rr,Br,uo,Eo,cn,Xr,pn,vt,ko,Lo,Go,fo,pt,_n,Po,Un,Ir,xa,un,Ko,fn,mn,qn,Vn,gn,ht,Dr,Fr,Ar,wt,Qr,Jr,Nr,hn;let t=Bi(e),r={};for(let[we,Xo]of Object.entries(t)){let Yr=we.replace(/\./g,"-");r[`--persona-${Yr}`]=Xo.value}r["--persona-primary"]=(b=r["--persona-semantic-colors-primary"])!=null?b:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(L=r["--persona-semantic-colors-secondary"])!=null?L:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(E=r["--persona-semantic-colors-accent"])!=null?E:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(A=r["--persona-semantic-colors-surface"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(T=r["--persona-semantic-colors-background"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(S=r["--persona-semantic-colors-text"])!=null?S:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(v=r["--persona-semantic-colors-text-muted"])!=null?v:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(M=r["--persona-semantic-colors-text-inverse"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(W=r["--persona-semantic-colors-border"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(H=r["--persona-semantic-colors-divider"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(I=r["--persona-components-voice-recording-indicator"])!=null?I:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(F=r["--persona-components-voice-recording-background"])!=null?F:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(O=r["--persona-components-voice-processing-icon"])!=null?O:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Q=r["--persona-components-voice-speaking-icon"])!=null?Q:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(he=r["--persona-components-approval-requested-background"])!=null?he:r["--persona-surface"],r["--persona-approval-border"]=(ce=r["--persona-components-approval-requested-border"])!=null?ce:r["--persona-border"],r["--persona-approval-text"]=(te=r["--persona-components-approval-requested-text"])!=null?te:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Te=r["--persona-components-approval-requested-shadow"])!=null?Te:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",r["--persona-approval-approve-bg"]=(We=r["--persona-components-approval-approve-background"])!=null?We:r["--persona-button-primary-bg"],r["--persona-approval-deny-bg"]=(de=r["--persona-components-approval-deny-background"])!=null?de:r["--persona-container"],r["--persona-attachment-image-bg"]=(Ae=r["--persona-components-attachment-image-background"])!=null?Ae:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(ne=r["--persona-components-attachment-image-border"])!=null?ne:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(le=r["--persona-semantic-typography-fontFamily"])!=null?le:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(ue=r["--persona-semantic-typography-fontSize"])!=null?ue:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(ke=r["--persona-semantic-typography-fontWeight"])!=null?ke:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(Fe=r["--persona-semantic-typography-lineHeight"])!=null?Fe: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"]=(J=r["--persona-palette-radius-md"])!=null?J:"0.375rem",r["--persona-radius-lg"]=(Ne=r["--persona-palette-radius-lg"])!=null?Ne:"0.5rem",r["--persona-radius-xl"]=(K=r["--persona-palette-radius-xl"])!=null?K:"0.75rem",r["--persona-radius-full"]=(pe=r["--persona-palette-radius-full"])!=null?pe:"9999px",r["--persona-launcher-radius"]=(ot=(qe=r["--persona-components-launcher-borderRadius"])!=null?qe:r["--persona-palette-radius-full"])!=null?ot:"9999px",r["--persona-launcher-bg"]=(xt=r["--persona-components-launcher-background"])!=null?xt:r["--persona-primary"],r["--persona-launcher-fg"]=(Ft=r["--persona-components-launcher-foreground"])!=null?Ft:r["--persona-text-inverse"],r["--persona-launcher-border"]=(Qt=r["--persona-components-launcher-border"])!=null?Qt:r["--persona-border"],r["--persona-button-primary-bg"]=(Ye=r["--persona-components-button-primary-background"])!=null?Ye:r["--persona-primary"],r["--persona-button-primary-fg"]=(xe=r["--persona-components-button-primary-foreground"])!=null?xe:r["--persona-text-inverse"],r["--persona-button-radius"]=(dt=(X=r["--persona-components-button-primary-borderRadius"])!=null?X:r["--persona-palette-radius-full"])!=null?dt:"9999px",r["--persona-panel-radius"]=(Ce=($e=r["--persona-components-panel-borderRadius"])!=null?$e:r["--persona-radius-xl"])!=null?Ce:"0.75rem",r["--persona-panel-border"]=(be=r["--persona-components-panel-border"])!=null?be:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Lt=(et=r["--persona-components-panel-shadow"])!=null?et:r["--persona-palette-shadows-xl"])!=null?Lt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(Z=r["--persona-components-launcher-shadow"])!=null?Z:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(Sr=(Ue=r["--persona-components-input-borderRadius"])!=null?Ue:r["--persona-radius-lg"])!=null?Sr:"0.5rem",r["--persona-message-user-radius"]=(xr=(yt=r["--persona-components-message-user-borderRadius"])!=null?yt:r["--persona-radius-lg"])!=null?xr:"0.5rem",r["--persona-message-assistant-radius"]=(Mo=(Ao=r["--persona-components-message-assistant-borderRadius"])!=null?Ao:r["--persona-radius-lg"])!=null?Mo:"0.5rem",r["--persona-header-bg"]=(P=r["--persona-components-header-background"])!=null?P:r["--persona-surface"],r["--persona-header-border"]=(ee=r["--persona-components-header-border"])!=null?ee:r["--persona-divider"],r["--persona-header-icon-bg"]=(Me=r["--persona-components-header-iconBackground"])!=null?Me: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"]=(Le=r["--persona-components-header-titleForeground"])!=null?Le:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Be=r["--persona-components-header-subtitleForeground"])!=null?Be:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(Ge=r["--persona-components-header-actionIconForeground"])!=null?Ge:r["--persona-muted"];let o=(at=e.components)==null?void 0:at.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(Pt=e.components)==null?void 0:Pt.introCard;r["--persona-intro-card-bg"]=(se=r["--persona-components-introCard-background"])!=null?se:r["--persona-surface"],r["--persona-intro-card-radius"]=(N=r["--persona-components-introCard-borderRadius"])!=null?N:"1rem",r["--persona-intro-card-padding"]=(ye=r["--persona-components-introCard-padding"])!=null?ye:"1.5rem",r["--persona-intro-card-shadow"]=(bt=(Oe=n==null?void 0:n.shadow)!=null?Oe:r["--persona-components-introCard-shadow"])!=null?bt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Qe=r["--persona-components-input-background"])!=null?Qe:r["--persona-surface"],r["--persona-input-placeholder"]=(Wt=r["--persona-components-input-placeholder"])!=null?Wt:r["--persona-text-muted"],r["--persona-message-user-bg"]=(At=r["--persona-components-message-user-background"])!=null?At:r["--persona-accent"],r["--persona-message-user-text"]=(gt=r["--persona-components-message-user-text"])!=null?gt:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(kt=r["--persona-components-message-user-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Xt=r["--persona-components-message-assistant-background"])!=null?Xt:r["--persona-surface"],r["--persona-message-assistant-text"]=(Ot=r["--persona-components-message-assistant-text"])!=null?Ot: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"]=(To=r["--persona-components-message-assistant-shadow"])!=null?To:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(lo=(zo=r["--persona-components-scrollToBottom-background"])!=null?zo:r["--persona-button-primary-bg"])!=null?lo:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(dn=(co=r["--persona-components-scrollToBottom-foreground"])!=null?co:r["--persona-button-primary-fg"])!=null?dn:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=($t=r["--persona-components-scrollToBottom-border"])!=null?$t:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(po=r["--persona-components-scrollToBottom-size"])!=null?po:"40px",r["--persona-scroll-to-bottom-radius"]=(Rr=(Hr=(jo=r["--persona-components-scrollToBottom-borderRadius"])!=null?jo:r["--persona-button-radius"])!=null?Hr:r["--persona-radius-full"])!=null?Rr:"9999px",r["--persona-scroll-to-bottom-shadow"]=(uo=(Br=r["--persona-components-scrollToBottom-shadow"])!=null?Br:r["--persona-palette-shadows-sm"])!=null?uo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Eo=r["--persona-components-scrollToBottom-padding"])!=null?Eo:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(cn=r["--persona-components-scrollToBottom-gap"])!=null?cn:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(pn=(Xr=r["--persona-components-scrollToBottom-fontSize"])!=null?Xr:r["--persona-palette-typography-fontSize-sm"])!=null?pn:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(vt=r["--persona-components-scrollToBottom-iconSize"])!=null?vt:"14px",r["--persona-tool-bubble-shadow"]=(ko=r["--persona-components-toolBubble-shadow"])!=null?ko:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(Lo=r["--persona-components-reasoningBubble-shadow"])!=null?Lo:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Go=r["--persona-components-composer-shadow"])!=null?Go:"none",r["--persona-md-inline-code-bg"]=(fo=r["--persona-components-markdown-inlineCode-background"])!=null?fo:r["--persona-container"],r["--persona-md-inline-code-color"]=(pt=r["--persona-components-markdown-inlineCode-foreground"])!=null?pt:r["--persona-text"],r["--persona-md-link-color"]=(Po=(_n=r["--persona-components-markdown-link-foreground"])!=null?_n:r["--persona-accent"])!=null?Po:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let l=r["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(r["--persona-md-prose-font-family"]=l),r["--persona-md-code-block-bg"]=(Un=r["--persona-components-markdown-codeBlock-background"])!=null?Un:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Ir=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Ir:r["--persona-border"],r["--persona-md-code-block-text-color"]=(xa=r["--persona-components-markdown-codeBlock-textColor"])!=null?xa:"inherit",r["--persona-md-table-header-bg"]=(un=r["--persona-components-markdown-table-headerBackground"])!=null?un:r["--persona-container"],r["--persona-md-table-border-color"]=(Ko=r["--persona-components-markdown-table-borderColor"])!=null?Ko:r["--persona-border"],r["--persona-md-hr-color"]=(fn=r["--persona-components-markdown-hr-color"])!=null?fn:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(mn=r["--persona-components-markdown-blockquote-borderColor"])!=null?mn:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(qn=r["--persona-components-markdown-blockquote-background"])!=null?qn:"transparent",r["--persona-md-blockquote-text-color"]=(Vn=r["--persona-components-markdown-blockquote-textColor"])!=null?Vn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(gn=r["--persona-components-collapsibleWidget-container"])!=null?gn:r["--persona-surface"],r["--cw-surface"]=(ht=r["--persona-components-collapsibleWidget-surface"])!=null?ht:r["--persona-surface"],r["--cw-border"]=(Dr=r["--persona-components-collapsibleWidget-border"])!=null?Dr:r["--persona-border"],r["--persona-message-border"]=(Fr=r["--persona-components-message-border"])!=null?Fr:r["--persona-border"];let p=e.components,f=p==null?void 0:p.iconButton;f&&(f.background&&(r["--persona-icon-btn-bg"]=f.background),f.border&&(r["--persona-icon-btn-border"]=f.border),f.color&&(r["--persona-icon-btn-color"]=f.color),f.padding&&(r["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(r["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(r["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(r["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(r["--persona-icon-btn-active-border"]=f.activeBorder));let u=p==null?void 0:p.labelButton;u&&(u.background&&(r["--persona-label-btn-bg"]=u.background),u.border&&(r["--persona-label-btn-border"]=u.border),u.color&&(r["--persona-label-btn-color"]=u.color),u.padding&&(r["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(r["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(r["--persona-label-btn-gap"]=u.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(r["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(r["--persona-toggle-group-radius"]=g.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let we=x.toolbar;we.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=we.iconHoverColor),we.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=we.iconHoverBackground),we.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=we.iconPadding),we.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=we.iconBorderRadius),we.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=we.iconBorder),we.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=we.toggleGroupGap),we.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=we.toggleBorderRadius),we.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=we.copyBackground),we.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=we.copyBorder),we.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=we.copyColor),we.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=we.copyBorderRadius),we.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=we.copyPadding),we.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=we.copyMenuBackground,r["--persona-dropdown-bg"]=(Ar=r["--persona-dropdown-bg"])!=null?Ar:we.copyMenuBackground),we.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=we.copyMenuBorder,r["--persona-dropdown-border"]=(wt=r["--persona-dropdown-border"])!=null?wt:we.copyMenuBorder),we.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=we.copyMenuShadow,r["--persona-dropdown-shadow"]=(Qr=r["--persona-dropdown-shadow"])!=null?Qr:we.copyMenuShadow),we.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=we.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Jr=r["--persona-dropdown-radius"])!=null?Jr:we.copyMenuBorderRadius),we.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=we.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Nr=r["--persona-dropdown-item-hover-bg"])!=null?Nr:we.copyMenuItemHoverBackground),we.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=we.iconBackground),we.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=we.toolbarBorder)}if(x!=null&&x.tab){let we=x.tab;we.background&&(r["--persona-artifact-tab-bg"]=we.background),we.activeBackground&&(r["--persona-artifact-tab-active-bg"]=we.activeBackground),we.activeBorder&&(r["--persona-artifact-tab-active-border"]=we.activeBorder),we.borderRadius&&(r["--persona-artifact-tab-radius"]=we.borderRadius),we.textColor&&(r["--persona-artifact-tab-color"]=we.textColor),we.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=we.hoverBackground),we.listBackground&&(r["--persona-artifact-tab-list-bg"]=we.listBackground),we.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=we.listBorderColor),we.listPadding&&(r["--persona-artifact-tab-list-padding"]=we.listPadding)}if(x!=null&&x.pane){let we=x.pane;if(we.toolbarBackground){let Xo=(hn=Oa(e,we.toolbarBackground))!=null?hn:we.toolbarBackground;r["--persona-artifact-toolbar-bg"]=Xo}}return r}var Ch={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 Xb={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"}}},Sh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ks=()=>{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"},Qb=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":ks()},Qc=e=>Qb(e),Jb=e=>_a(e),Yb=e=>{var r;let t=_a(void 0,{validate:!1});return _a({...e,palette:{...t.palette,colors:{...Xb.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Ua=e=>{let t=Qc(e),r=Sh(e==null?void 0:e.theme),o=Sh(e==null?void 0:e.darkTheme);return t==="dark"?Yb(Es(r!=null?r:{},o!=null?o:{})):Jb(r)},Zb=e=>Di(e),Hn=(e,t)=>{let r=Ua(t),o=Zb(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},Fi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(ks())});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(ks());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 Ah=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:u=>u.getAttribute("im-preserve")==="true",shouldReAppend:u=>u.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(u,g,x={}){u=p(u);let b=f(g),L=l(u,b,x),E=n(L,()=>i(L,u,b,A=>A.morphStyle==="innerHTML"?(a(A,u,b),Array.from(u.childNodes)):o(A,u,b)));return L.pantry.remove(),E}function o(u,g,x){let b=f(g);return a(u,b,x,g,g.nextSibling),Array.from(b.childNodes)}function n(u,g){var T;if(!u.config.restoreFocus)return g();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return g();let{id:b,selectionStart:L,selectionEnd:E}=x,A=g();return b&&b!==((T=document.activeElement)==null?void 0:T.getAttribute("id"))&&(x=u.target.querySelector(`[id="${b}"]`),x==null||x.focus()),x&&!x.selectionEnd&&E&&x.setSelectionRange(L,E),A}let a=(function(){function u(y,S,v,M=null,W=null){S instanceof HTMLTemplateElement&&v instanceof HTMLTemplateElement&&(S=S.content,v=v.content),M||(M=S.firstChild);for(let H of v.childNodes){if(M&&M!=W){let F=x(y,H,M,W);if(F){F!==M&&L(y,M,F),s(F,H,y),M=F.nextSibling;continue}}if(H instanceof Element){let F=H.getAttribute("id");if(y.persistentIds.has(F)){let O=E(S,F,M,y);s(O,H,y),M=O.nextSibling;continue}}let I=g(S,H,M,y);I&&(M=I.nextSibling)}for(;M&&M!=W;){let H=M;M=M.nextSibling,b(y,H)}}function g(y,S,v,M){if(M.callbacks.beforeNodeAdded(S)===!1)return null;if(M.idMap.has(S)){let W=document.createElement(S.tagName);return y.insertBefore(W,v),s(W,S,M),M.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(S,!0);return y.insertBefore(W,v),M.callbacks.afterNodeAdded(W),W}}let x=(function(){function y(M,W,H,I){let F=null,O=W.nextSibling,Q=0,he=H;for(;he&&he!=I;){if(v(he,W)){if(S(M,he,W))return he;F===null&&(M.idMap.has(he)||(F=he))}if(F===null&&O&&v(he,O)&&(Q++,O=O.nextSibling,Q>=2&&(F=void 0)),M.activeElementAndParents.includes(he))break;he=he.nextSibling}return F||null}function S(M,W,H){let I=M.idMap.get(W),F=M.idMap.get(H);if(!F||!I)return!1;for(let O of I)if(F.has(O))return!0;return!1}function v(M,W){var F,O,Q;let H=M,I=W;return H.nodeType===I.nodeType&&H.tagName===I.tagName&&(!((F=H.getAttribute)!=null&&F.call(H,"id"))||((O=H.getAttribute)==null?void 0:O.call(H,"id"))===((Q=I.getAttribute)==null?void 0:Q.call(I,"id")))}return y})();function b(y,S){var v;if(y.idMap.has(S))T(y.pantry,S,null);else{if(y.callbacks.beforeNodeRemoved(S)===!1)return;(v=S.parentNode)==null||v.removeChild(S),y.callbacks.afterNodeRemoved(S)}}function L(y,S,v){let M=S;for(;M&&M!==v;){let W=M;M=M.nextSibling,b(y,W)}return M}function E(y,S,v,M){var H,I;let W=((I=(H=M.target).getAttribute)==null?void 0:I.call(H,"id"))===S&&M.target||M.target.querySelector(`[id="${S}"]`)||M.pantry.querySelector(`[id="${S}"]`);return A(W,M),T(y,W,v),W}function A(y,S){let v=y.getAttribute("id");for(;y=y.parentNode;){let M=S.idMap.get(y);M&&(M.delete(v),M.size||S.idMap.delete(y))}}function T(y,S,v){if(y.moveBefore)try{y.moveBefore(S,v)}catch{y.insertBefore(S,v)}else y.insertBefore(S,v)}return u})(),s=(function(){function u(A,T,y){return y.ignoreActive&&A===document.activeElement?null:(y.callbacks.beforeNodeMorphed(A,T)===!1||(A instanceof HTMLHeadElement&&y.head.ignore||(A instanceof HTMLHeadElement&&y.head.style!=="morph"?c(A,T,y):(g(A,T,y),E(A,y)||a(y,A,T))),y.callbacks.afterNodeMorphed(A,T)),A)}function g(A,T,y){let S=T.nodeType;if(S===1){let v=A,M=T,W=v.attributes,H=M.attributes;for(let I of H)L(I.name,v,"update",y)||v.getAttribute(I.name)!==I.value&&v.setAttribute(I.name,I.value);for(let I=W.length-1;0<=I;I--){let F=W[I];if(F&&!M.hasAttribute(F.name)){if(L(F.name,v,"remove",y))continue;v.removeAttribute(F.name)}}E(v,y)||x(v,M,y)}(S===8||S===3)&&A.nodeValue!==T.nodeValue&&(A.nodeValue=T.nodeValue)}function x(A,T,y){if(A instanceof HTMLInputElement&&T instanceof HTMLInputElement&&T.type!=="file"){let S=T.value,v=A.value;b(A,T,"checked",y),b(A,T,"disabled",y),T.hasAttribute("value")?v!==S&&(L("value",A,"update",y)||(A.setAttribute("value",S),A.value=S)):L("value",A,"remove",y)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&T instanceof HTMLOptionElement)b(A,T,"selected",y);else if(A instanceof HTMLTextAreaElement&&T instanceof HTMLTextAreaElement){let S=T.value,v=A.value;if(L("value",A,"update",y))return;S!==v&&(A.value=S),A.firstChild&&A.firstChild.nodeValue!==S&&(A.firstChild.nodeValue=S)}}function b(A,T,y,S){let v=T[y],M=A[y];if(v!==M){let W=L(y,A,"update",S);W||(A[y]=T[y]),v?W||A.setAttribute(y,""):L(y,A,"remove",S)||A.removeAttribute(y)}}function L(A,T,y,S){return A==="value"&&S.ignoreActiveValue&&T===document.activeElement?!0:S.callbacks.beforeAttributeUpdated(A,T,y)===!1}function E(A,T){return!!T.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return u})();function i(u,g,x,b){if(u.head.block){let L=g.querySelector("head"),E=x.querySelector("head");if(L&&E){let A=c(L,E,u);return Promise.all(A).then(()=>{let T=Object.assign(u,{head:{block:!1,ignore:!0}});return b(T)})}}return b(u)}function c(u,g,x){let b=[],L=[],E=[],A=[],T=new Map;for(let S of g.children)T.set(S.outerHTML,S);for(let S of u.children){let v=T.has(S.outerHTML),M=x.head.shouldReAppend(S),W=x.head.shouldPreserve(S);v||W?M?L.push(S):(T.delete(S.outerHTML),E.push(S)):x.head.style==="append"?M&&(L.push(S),A.push(S)):x.head.shouldRemove(S)!==!1&&L.push(S)}A.push(...T.values());let y=[];for(let S of A){let v=document.createRange().createContextualFragment(S.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(v)!==!1){if("href"in v&&v.href||"src"in v&&v.src){let M,W=new Promise(function(H){M=H});v.addEventListener("load",function(){M()}),y.push(W)}u.appendChild(v),x.callbacks.afterNodeAdded(v),b.push(v)}}for(let S of L)x.callbacks.beforeNodeRemoved(S)!==!1&&(u.removeChild(S),x.callbacks.afterNodeRemoved(S));return x.head.afterHeadMorphed(u,{added:b,kept:E,removed:L}),y}let l=(function(){function u(y,S,v){let{persistentIds:M,idMap:W}=A(y,S),H=g(v),I=H.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(I))throw`Do not understand how to morph style ${I}`;return{target:y,newContent:S,config:H,morphStyle:I,ignoreActive:H.ignoreActive,ignoreActiveValue:H.ignoreActiveValue,restoreFocus:H.restoreFocus,idMap:W,persistentIds:M,pantry:x(),activeElementAndParents:b(y),callbacks:H.callbacks,head:H.head}}function g(y){let S=Object.assign({},t);return Object.assign(S,y),S.callbacks=Object.assign({},t.callbacks,y.callbacks),S.head=Object.assign({},t.head,y.head),S}function x(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function b(y){let S=[],v=document.activeElement;if((v==null?void 0:v.tagName)!=="BODY"&&y.contains(v))for(;v&&(S.push(v),v!==y);)v=v.parentElement;return S}function L(y){var v;let S=Array.from(y.querySelectorAll("[id]"));return(v=y.getAttribute)!=null&&v.call(y,"id")&&S.push(y),S}function E(y,S,v,M){for(let W of M){let H=W.getAttribute("id");if(S.has(H)){let I=W;for(;I;){let F=y.get(I);if(F==null&&(F=new Set,y.set(I,F)),F.add(H),I===v)break;I=I.parentElement}}}}function A(y,S){let v=L(y),M=L(S),W=T(v,M),H=new Map;E(H,W,y,v);let I=S.__idiomorphRoot||S;return E(H,W,I,M),{persistentIds:W,idMap:H}}function T(y,S){let v=new Set,M=new Map;for(let{id:H,tagName:I}of y)M.has(H)?v.add(H):M.set(H,I);let W=new Set;for(let{id:H,tagName:I}of S)W.has(H)?v.add(H):M.get(H)===I&&W.add(H);for(let H of v)W.delete(H);return W}return u})(),{normalizeElement:p,normalizeParent:f}=(function(){let u=new WeakSet;function g(E){return E instanceof Document?E.documentElement:E}function x(E){if(E==null)return document.createElement("div");if(typeof E=="string")return x(L(E));if(u.has(E))return E;if(E instanceof Node){if(E.parentNode)return new b(E);{let A=document.createElement("div");return A.append(E),A}}else{let A=document.createElement("div");for(let T of[...E])A.append(T);return A}}class b{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],T=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;T&&T!=this.nextSibling;)A.push(T),T=T.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((T,y)=>{if(y instanceof Element){y.matches(A)&&T.push(y);let S=y.querySelectorAll(A);for(let v=0;v<S.length;v++)T.push(S[v])}return T},[])}insertBefore(A,T){return this.realParentNode.insertBefore(A,T)}moveBefore(A,T){return this.realParentNode.moveBefore(A,T)}get __idiomorphRoot(){return this.originalNode}}function L(E){let A=new DOMParser,T=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(T.match(/<\/html>/)||T.match(/<\/head>/)||T.match(/<\/body>/)){let y=A.parseFromString(E,"text/html");if(T.match(/<\/html>/))return u.add(y),y;{let S=y.firstChild;return S&&u.add(S),S}}else{let S=A.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return u.add(S),S}}return{normalizeElement:g,normalizeParent:x}})();return{morph:r,defaults:t}})();var Ni=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;Ah.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",l=(i=a.textContent)!=null?i:"";if(c!==l)return}return!1}}}}})};var Mh=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Oi={index:-1,draft:""};function Th(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...Oi}}}function Eh(e,t){var r,o,n,a,s,i,c,l,p,f,u,g,x,b,L,E,A,T,y,S,v,M,W,H,I,F,O,Q,he,ce,te,Te,We,de,Ae,ne,le,ue;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(u=(f=e.approval)==null?void 0:f.status)!=null?u:"",(x=(g=e.toolCall)==null?void 0:g.status)!=null?x:"",(L=(b=e.toolCall)==null?void 0:b.name)!=null?L:"",(T=(A=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:A.length)!=null?T:0,(M=(v=(S=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:S[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?M:"",typeof((W=e.toolCall)==null?void 0:W.args)=="string"?e.toolCall.args.length:(H=e.toolCall)!=null&&H.args?JSON.stringify(e.toolCall.args).length:0,(O=(F=(I=e.reasoning)==null?void 0:I.chunks)==null?void 0:F.length)!=null?O:0,(te=(ce=(he=(Q=e.reasoning)==null?void 0:Q.chunks)==null?void 0:he[e.reasoning.chunks.length-1])==null?void 0:ce.length)!=null?te:0,(Ae=(de=(We=(Te=e.reasoning)==null?void 0:Te.chunks)==null?void 0:We[e.reasoning.chunks.length-1])==null?void 0:de.slice(-32))!=null?Ae:"",(le=(ne=e.contentParts)==null?void 0:ne.length)!=null?le:0,(ue=e.stopReason)!=null?ue:"",t].join("\0")}function kh(){return new Map}function Lh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function Ph(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function Rh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function _i(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Vo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Bn(e,t){return Vo(e)-e.scrollTop<=t}function Ui(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,p=r-o;return s||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:r}:!t&&n&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function qi(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}function Ih(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Wh(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),r=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:r}}function Hh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var wr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Cr=1e5,Dn=Cr+1;var Ls={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ev=["pre","code","a","script","style"],Vi=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:Ls.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Ls.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ls.speed,duration:(n=e==null?void 0:e.duration)!=null?n:Ls.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:Ls.buffer}},Dh=[{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"}],Ps=new Map;for(let e of Dh)Ps.set(e.name,e);var ca=e=>{Ps.set(e.name,e)},Zc=e=>{Dh.some(t=>t.name===e)||Ps.delete(e)},ep=()=>Array.from(Ps.keys()),Rs=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Ps.get(e))!=null?o:null},$i=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
20
+ `);return a<0?"":e.slice(0,a)}return e},tv=(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},rv=(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},Jc=/\s/,ov=(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},nv=(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(Jc.test(a[i])){let l=i;for(;l<a.length&&Jc.test(a[l]);)l+=1;s.appendChild(o.createTextNode(a.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<a.length&&!Jc.test(a[p]);)l.appendChild(tv(o,a[p],t,r.value)),r.value+=1,p+=1;s.appendChild(l),i=p}n.replaceChild(s,e)},av=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?s.appendChild(o.createTextNode(l)):(s.appendChild(rv(o,l,t,r.value)),r.value+=1));n.replaceChild(s,e)},Is=(e,t,r,o)=>{var f,u;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((f=o==null?void 0:o.skipTags)!=null?f:ev).map(g=>g.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)ov(c,a)||i.push(c),c=s.nextNode();let l={value:(u=o==null?void 0:o.startIndex)!=null?u:0},p=t==="char"?nv:av;for(let g of i)p(g,r,l);return n.innerHTML},zi=(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},Ws=(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},Bh=new WeakMap,sv=(e,t)=>{var a;if(!e.styles)return;let r=Bh.get(t);if(r||(r=new Set,Bh.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)},Yc=new WeakMap,iv=(e,t)=>{if(!e.onAttach)return;let r=Yc.get(t);if(r||(r=new Map,Yc.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},Fh=e=>{let t=Yc.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},tp=(e,t)=>{sv(e,t),iv(e,t)};function rp(e,t=Cr){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 Hs=0,Fn=null;function op(e=document){var r;if(Hs++,Hs===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Fn={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,Hs=Math.max(0,Hs-1),Hs===0&&Fn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Fn.originalOverflow,n.style.position=Fn.originalPosition,n.style.top=Fn.originalTop,n.style.width=Fn.originalWidth,a.scrollTo(0,Fn.scrollY),Fn=null}}}var Bs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},nr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Nn=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},Gr=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:Bs.side,width:(n=t==null?void 0:t.width)!=null?n:Bs.width,animate:(a=t==null?void 0:t.animate)!=null?a:Bs.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:Bs.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Bs.maxHeight}};var So={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var lv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ji=(e,t={})=>{var L,E,A,T,y,S;let{showClose:r=!0,wrapperClassName:o=lv,buttonSize:n,iconSize:a="28px"}=t,s=(L=e==null?void 0:e.launcher)!=null?L:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=w("div",o),l=(A=s.closeButtonTooltipText)!=null?A:"Close chat",p=(T=s.closeButtonShowTooltip)!=null?T:!0,f=(y=s.closeButtonIconName)!=null?y:"x",u=(S=s.closeButtonIconText)!=null?S:"\xD7",g=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=St("button",{className:ms("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||Pr.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:g?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),b=ge(f,a,"currentColor",1);if(b?(b.style.display="block",x.appendChild(b)):x.textContent=u,c.appendChild(x),p&&l){let v=null,M=()=>{if(v)return;let H=x.ownerDocument,I=H.body;if(!I)return;v=qo(H,"div","persona-clear-chat-tooltip"),v.textContent=l;let F=qo(H,"div");F.className="persona-clear-chat-tooltip-arrow",v.appendChild(F);let O=x.getBoundingClientRect();v.style.position="fixed",v.style.zIndex=String(Dn),v.style.left=`${O.left+O.width/2}px`,v.style.top=`${O.top-8}px`,v.style.transform="translate(-50%, -100%)",I.appendChild(v)},W=()=>{v&&v.parentNode&&(v.parentNode.removeChild(v),v=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}},dv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Gi=(e,t={})=>{var v,M,W,H,I,F,O,Q,he,ce,te,Te,We;let{wrapperClassName:r=dv,buttonSize:o,iconSize:n="20px"}=t,s=(M=((v=e==null?void 0:e.launcher)!=null?v:{}).clearChat)!=null?M:{},i=(W=o!=null?o:s.size)!=null?W:"32px",c=(H=s.iconName)!=null?H:"refresh-cw",l=(I=s.iconColor)!=null?I:"",p=(F=s.backgroundColor)!=null?F:"",f=(O=s.borderWidth)!=null?O:"",u=(Q=s.borderColor)!=null?Q:"",g=(he=s.borderRadius)!=null?he:"",x=(ce=s.paddingX)!=null?ce:"",b=(te=s.paddingY)!=null?te:"",L=(Te=s.tooltipText)!=null?Te:"Clear chat",E=(We=s.showTooltip)!=null?We:!0,A=w("div",r),T=!!(f||u),y=St("button",{className:ms("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":L},style:{height:i,width:i,color:l||Pr.actionIconColor,backgroundColor:p||void 0,border:T?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:b||void 0,paddingBottom:b||void 0}}),S=ge(c,n,"currentColor",1);if(S&&(S.style.display="block",y.appendChild(S)),A.appendChild(y),E&&L){let de=null,Ae=()=>{if(de)return;let le=y.ownerDocument,ue=le.body;if(!ue)return;de=qo(le,"div","persona-clear-chat-tooltip"),de.textContent=L;let ke=qo(le,"div");ke.className="persona-clear-chat-tooltip-arrow",de.appendChild(ke);let Fe=y.getBoundingClientRect();de.style.position="fixed",de.style.zIndex=String(Dn),de.style.left=`${Fe.left+Fe.width/2}px`,de.style.top=`${Fe.top-8}px`,de.style.transform="translate(-50%, -100%)",ue.appendChild(de)},ne=()=>{de&&de.parentNode&&(de.parentNode.removeChild(de),de=null)};A.addEventListener("mouseenter",Ae),A.addEventListener("mouseleave",ne),y.addEventListener("focus",Ae),y.addEventListener("blur",ne),A._cleanupTooltip=()=>{ne(),A.removeEventListener("mouseenter",Ae),A.removeEventListener("mouseleave",ne),y.removeEventListener("focus",Ae),y.removeEventListener("blur",ne)}}return{button:y,wrapper:A}};var Pr={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))"},sn=e=>{var S,v,M,W,H,I,F,O,Q,he,ce,te,Te,We,de,Ae;let{config:t,showClose:r=!0}=e,o=St("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),n=(S=t==null?void 0:t.launcher)!=null?S:{},a=(v=n.headerIconSize)!=null?v:"48px",s=(M=n.closeButtonPlacement)!=null?M:"inline",i=(W=n.headerIconHidden)!=null?W:!1,c=n.headerIconName,l=St("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 ne=parseFloat(a)||24,le=ge(c,ne*.6,"currentColor",1);le?l.replaceChildren(le):l.textContent=(I=(H=t==null?void 0:t.launcher)==null?void 0:H.agentIconText)!=null?I:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let ne=w("img");ne.src=t.launcher.iconUrl,ne.alt="",ne.className="persona-rounded-xl persona-object-cover",ne.style.height=a,ne.style.width=a,l.replaceChildren(ne)}else l.textContent=(Q=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?Q:"\u{1F4AC}";let p=w("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=St("span",{className:"persona-text-base persona-font-semibold",text:(ce=(he=t==null?void 0:t.launcher)==null?void 0:he.title)!=null?ce:"Chat Assistant",style:{color:Pr.titleColor}}),u=St("span",{className:"persona-text-xs",text:(Te=(te=t==null?void 0:t.launcher)==null?void 0:te.subtitle)!=null?Te:"Here to help you get answers fast",style:{color:Pr.subtitleColor}});p.append(f,u),i?o.append(p):o.append(l,p);let g=(We=n.clearChat)!=null?We:{},x=(de=g.enabled)!=null?de:!0,b=(Ae=g.placement)!=null?Ae:"inline",L=null,E=null;if(x){let le=Gi(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});L=le.button,E=le.wrapper,b==="top-right"&&(E.style.right="48px"),b==="inline"&&o.appendChild(E)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&b==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:T,wrapper:y}=ji(t,{showClose:r,wrapperClassName:A});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:l,headerTitle:f,headerSubtitle:u,closeButton:T,closeButtonWrapper:y,clearChatButton:L,clearChatButtonWrapper:E}},pa=(e,t,r)=>{var s,i,c,l;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(l=(c=o.clearChat)==null?void 0:c.placement)!=null?l:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function On(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=w("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(Dn)):(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 g of t){if(g.dividerBefore){let L=document.createElement("hr");s.appendChild(L)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",g.id),g.destructive&&x.setAttribute("data-destructive",""),g.icon){let L=ge(g.icon,16,"currentColor",1.5);L&&x.appendChild(L)}let b=document.createElement("span");b.textContent=g.label,x.appendChild(b),x.addEventListener("click",L=>{L.stopPropagation(),p(),r(g.id)}),s.appendChild(x)}let i=null;function c(){if(!a)return;let g=o.getBoundingClientRect();s.style.top=`${g.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-g.right}px`,s.style.left="auto"):(s.style.left=`${g.left}px`,s.style.right="auto")}function l(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=x=>{!s.contains(x.target)&&!o.contains(x.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){s.classList.add("persona-hidden"),i==null||i(),i=null}function f(){s.classList.contains("persona-hidden")?l():p()}function u(){p(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:p,toggle:f,destroy:u}}function pr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=w("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let l=ge(t,o!=null?o:16,"currentColor",n!=null?n:2);if(l&&c.appendChild(l),s&&c.addEventListener("click",s),i)for(let[p,f]of Object.entries(i))c.setAttribute(p,f);return c}function Ds(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+n,s&&(l+=" "+s);let p=w("button",l);if(p.type="button",p.setAttribute("aria-label",r),t){let u=ge(t,a!=null?a:14,"currentColor",2);u&&p.appendChild(u)}let f=w("span");if(f.textContent=r,p.appendChild(f),i&&p.addEventListener("click",i),c)for(let[u,g]of Object.entries(c))p.setAttribute(u,g);return p}function Nh(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=w("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===s?"true":"false")}for(let p of t){let f;p.icon?f=pr({icon:p.icon,label:p.label,onClick:()=>{s=p.id,c(),o(p.id)}}):(f=w("button","persona-icon-btn"),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{s=p.id,c(),o(p.id)})),f.setAttribute("aria-pressed",p.id===s?"true":"false"),i.push({id:p.id,btn:f}),a.appendChild(f)}function l(p){s=p,c()}return{element:a,setSelected:l}}function Ki(e){var g,x;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,l=w("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=w("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let f=ge(r,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",l.appendChild(f)),c&&(l.style.borderRadius=(g=c.borderRadius)!=null?g:"10px",l.style.padding=(x=c.padding)!=null?x:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var b,L;l.style.backgroundColor=(b=c.background)!=null?b:"",l.style.borderColor=(L=c.border)!=null?L:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let u=On({items:o,onSelect:b=>{l.setAttribute("aria-expanded","false"),n(b)},anchor:l,position:a,portal:s});return s||l.appendChild(u.element),l.addEventListener("click",b=>{b.stopPropagation();let L=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",L?"false":"true"),u.toggle()}),l.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),l.click())}),{element:l,setLabel:b=>{p.textContent=b,l.setAttribute("aria-label",b)},open:()=>{l.setAttribute("aria-expanded","true"),u.show()},close:()=>{l.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let b=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",b?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),l.remove()}}}var np=e=>{var o;let t=sn({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 cv(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=w("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=ge(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=w("div","persona-relative");c.appendChild(i);let l=On({items:s.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:c,position:"bottom-left"});c.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var ap=e=>{var A,T,y,S,v,M,W,H,I;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(A=t==null?void 0:t.launcher)!=null?A:{},i=w("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=n==null?void 0:n.titleMenu,l,p;if(c)l=Ki({label:(T=s.title)!=null?T:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,l.style.color=Pr.titleColor,p=(y=l.querySelector(".persona-combo-btn-label"))!=null?y:l;else{if(l=w("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=w("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Pr.titleColor,p.textContent=(S=s.title)!=null?S:"Chat Assistant",l.appendChild(p),cv(l,n==null?void 0:n.trailingActions,(v=n==null?void 0:n.onAction)!=null?v:a),n!=null&&n.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let O=n.onTitleClick;l.addEventListener("click",Q=>{Q.target.closest("button")||O()}),l.addEventListener("keydown",Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),O())})}let F=n==null?void 0:n.titleRowHover;F&&(l.style.borderRadius=(M=F.borderRadius)!=null?M:"10px",l.style.padding=(W=F.padding)!=null?W:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var O,Q;l.style.backgroundColor=(O=F.background)!=null?O:"",l.style.borderColor=(Q=F.border)!=null?Q:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let f=(H=s.closeButtonSize)!=null?H:"32px",u=w("div",""),g=w("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=f,g.style.width=f,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=r?"":"none",g.style.color=s.closeButtonColor||Pr.actionIconColor;let x=(I=s.closeButtonIconName)!=null?I:"x",b=ge(x,"28px","currentColor",1);b?g.appendChild(b):g.textContent="\xD7",o&&g.addEventListener("click",o),u.appendChild(g),i.appendChild(u);let L=w("div");L.style.display="none";let E=w("span");return E.style.display="none",{header:i,iconHolder:L,headerTitle:p,headerSubtitle:E,closeButton:g,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Xi={default:np,minimal:ap},sp=e=>{var t;return(t=Xi[e])!=null?t:Xi.default},qa=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let l=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=w("div");p.style.display="none";let f=w("span"),u=w("span"),g=w("button");g.style.display="none";let x=w("div");return x.style.display="none",{header:l,iconHolder:p,headerTitle:f,headerSubtitle:u,closeButton:g,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=sp(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 Qi=e=>{var s,i;let t=w("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}},Ji=e=>{var S,v,M,W,H,I,F,O,Q,he,ce,te;let t=(S=e==null?void 0:e.sendButton)!=null?S:{},r=(v=t.useIcon)!=null?v:!1,o=(M=t.iconText)!=null?M:"\u2191",n=t.iconName,a=(W=t.stopIconName)!=null?W:"square",s=(H=t.tooltipText)!=null?H:"Send message",i=(I=t.stopTooltipText)!=null?I:"Stop generating",c=(O=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?O:"Send",l=(he=(Q=e==null?void 0:e.copy)==null?void 0:Q.stopButtonLabel)!=null?he:"Stop",p=(ce=t.showTooltip)!=null?ce:!1,f=(te=t.size)!=null?te:"40px",u=t.backgroundColor,g=t.textColor,x=w("div","persona-send-button-wrapper"),b=St("button",{className:ms("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!u&&"persona-bg-persona-primary",!r&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?f:void 0,height:r?f:void 0,minWidth:r?f:void 0,minHeight:r?f:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:r&&u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),L=null,E=null;if(r){let Te=parseFloat(f)||24,We=(g==null?void 0:g.trim())||"currentColor";n?(L=ge(n,Te,We,2),L?b.appendChild(L):b.textContent=o):b.textContent=o,E=ge(a,Te,We,2)}else b.textContent=c;let A=null;p&&s&&(A=w("div","persona-send-button-tooltip"),A.textContent=s,x.appendChild(A)),b.setAttribute("aria-label",s),x.appendChild(b);let T="send";return{button:b,wrapper:x,setMode:Te=>{if(Te===T)return;T=Te;let We=Te==="stop"?i:s;if(b.setAttribute("aria-label",We),A&&(A.textContent=We),r){if(L&&E){let de=Te==="stop"?E:L;b.replaceChildren(de)}}else b.textContent=Te==="stop"?l:c}}},Yi=e=>{var A,T,y,S,v,M,W,H,I,F,O,Q;let t=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((T=t.provider)==null?void 0:T.type)==="runtype";if(!(o||n))return null;let s=(S=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?S:"40px",i=(v=t.iconName)!=null?v:"mic",c=(M=t.iconSize)!=null?M:s,l=parseFloat(c)||24,p=(H=t.backgroundColor)!=null?H:(W=e==null?void 0:e.sendButton)==null?void 0:W.backgroundColor,f=(F=t.iconColor)!=null?F:(I=e==null?void 0:e.sendButton)==null?void 0:I.textColor,u=w("div","persona-send-button-wrapper"),g=St("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),b=ge(i,l,f||"currentColor",1.5);b?g.appendChild(b):g.textContent="\u{1F3A4}",u.appendChild(g);let L=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((Q=t.showTooltip)!=null?Q:!1)&&L){let he=w("div","persona-send-button-tooltip");he.textContent=L,u.appendChild(he)}return{button:g,wrapper:u}},Zi=e=>{var x,b,L,E,A,T,y,S;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(L=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?L:"40px",o=w("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=w("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:an).join(","),n.multiple=((A=t.maxFiles)!=null?A:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(T=t.buttonIconName)!=null?T:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),l=w("div","persona-send-button-wrapper"),p=St("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let f=ge(a,c,"currentColor",1.5);f?p.appendChild(f):p.textContent="\u{1F4CE}",p.addEventListener("click",v=>{v.preventDefault(),n.click()}),l.appendChild(p);let u=(S=t.buttonTooltipText)!=null?S:"Attach file",g=w("div","persona-send-button-tooltip");return g.textContent=u,l.appendChild(g),{button:p,wrapper:l,input:n,previewsContainer:o}},el=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=w("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let l=w("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=a,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=a;return o},tl=()=>St("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Va=e=>{var x,b,L,E,A,T;let{config:t}=e,r=St("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=tl(),n=St("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}=Qi(t);s();let i=Ji(t),c=Yi(t),l=Zi(t),p=el(t);l&&(l.previewsContainer.style.gap="8px",n.append(l.previewsContainer,l.input)),n.append(a);let f=St("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=w("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=w("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&u.append(l.wrapper),c&&g.append(c.wrapper),g.append(i.wrapper),f.append(u,g),n.append(f),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(l==null?void 0:l.button)&&y.target!==(l==null?void 0:l.wrapper)&&a.focus()}),r.append(o,n,p),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:p,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Oh=()=>{let e=St("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=w("span","persona-pill-peek__icon"),r=ge("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=w("span","persona-pill-peek__text"),n=w("span","persona-pill-peek__caret"),a=ge("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},_h=e=>{var x,b,L,E,A,T;let{config:t}=e,r=St("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=tl();o.style.display="none";let n=el(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=Qi(t);a.style.maxHeight="100px",s();let i=Ji(t),c=Yi(t),l=Zi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=St("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=w("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&f.append(l.wrapper);let u=w("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&u.append(c.wrapper),u.append(i.wrapper),p.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(l==null?void 0:l.button)&&y.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&p.append(l.input),p.append(f,a,u),l&&r.append(l.previewsContainer),r.append(p,o,n);let g=p;return{footer:r,suggestions:o,composerForm:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:n,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:g,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var Uh=e=>{var p,f,u,g,x,b,L,E,A,T,y,S,v,M,W,H,I;let t=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?f:!0,r=nr(e);if(Nn(e)){let F=(g=(u=e==null?void 0:e.launcher)==null?void 0:u.composerBar)!=null?g:{},O=w("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(x=F.expandedSize)!=null?x:"anchored",O.style.zIndex=String((L=(b=e==null?void 0:e.launcher)==null?void 0:b.zIndex)!=null?L:Cr);let Q=w("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Q.style.width="100%",O.appendChild(Q);let he=w("div","persona-widget-pill-root");return he.setAttribute("data-persona-composer-bar",""),he.dataset.state="collapsed",he.dataset.expandedSize=(E=F.expandedSize)!=null?E:"anchored",he.style.zIndex=String((T=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?T:Cr),{wrapper:O,panel:Q,pillRoot:he}}if(r){let F=w("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=w("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild(O),{wrapper:F,panel:O}}if(!t){let F=w("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=w("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Q=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?S:"100%";return F.style.width=Q,O.style.width="100%",F.appendChild(O),{wrapper:F,panel:O}}let n=(v=e==null?void 0:e.launcher)!=null?v:{},a=n.position&&So[n.position]?So[n.position]:So["bottom-right"],s=w("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:Cr);let i=w("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(I=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?I:e==null?void 0:e.launcherWidth,l=c!=null?c:jr;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},pv=(e,t)=>{var y,S,v,M,W,H,I,F,O;let r=w("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}=ji(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(v=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:S.enabled)!=null?v:!0,s=null,i=null;if(a){let Q=Gi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=Q.button,i=Q.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=St("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=St("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});l.style.setProperty("scrollbar-gutter","stable");let p=St("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}"}),f=St("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),u=St("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,f),g=w("div","persona-flex persona-flex-col persona-gap-3"),x=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;x&&(g.style.maxWidth=x,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,g);let L=St("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=_h({config:e}),{root:A,textNode:T}=Oh();return r.append(c,n,l,L),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:g,composerOverlay:L,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:p,introSubtitle:f,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:w("span"),headerTitle:w("span"),headerSubtitle:w("span"),header:c,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:A,peekTextNode:T}},qh=(e,t=!0)=>{var L,E,A,T,y,S,v,M,W;if(Nn(e))return pv(e,t);let r=St("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=(L=e==null?void 0:e.layout)==null?void 0:L.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?qa(e,o,{showClose:t}):sn({config:e,showClose:t}),s=St("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=St("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(T=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?T:"Hello \u{1F44B}"}),c=St("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(S=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?S:"Ask anything about your account or products."}),l=St("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:nr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),p=w("div","persona-flex persona-flex-col persona-gap-3"),f=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(l.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(l,p);let g=Va({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 b=St("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||(g.footer.style.display="none"),r.append(g.footer),r.append(b),{container:r,body:s,messagesWrapper:p,composerOverlay:b,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle: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:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var ip=(e,t)=>{let r=w("button");r.type="button",r.innerHTML=`
21
21
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
22
22
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
23
23
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -25,14 +25,14 @@ _Details: ${r.message}_`:o}var ys=e=>({isError:!0,content:[{type:"text",text:e}]
25
25
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
26
26
  </span>
27
27
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
28
- `,r.addEventListener("click",t);let o=a=>{var T,y,S,v,M,W,H,I,D,O,J,me,de;let s=(T=a.launcher)!=null?T:{},i=nr(a),c=r.querySelector("[data-role='launcher-title']");if(c){let te=(y=s.title)!=null?y:"Chat Assistant";c.textContent=te,c.setAttribute("title",te)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let te=(S=s.subtitle)!=null?S:"Here to help you get answers fast";l.textContent=te,l.setAttribute("title",te)}let p=r.querySelector(".persona-flex-col");p&&(s.textHidden||i?p.style.display="none":p.style.display="");let f=r.querySelector("[data-role='launcher-icon']");if(f)if(s.agentIconHidden)f.style.display="none";else{let te=(v=s.agentIconSize)!=null?v:"40px";if(f.style.height=te,f.style.width=te,s.agentIconBackgroundColor?(f.style.backgroundColor=s.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",s.agentIconName){let Ae=parseFloat(te)||24,Ie=fe(s.agentIconName,Ae*.6,"var(--persona-text-inverse, #ffffff)",2);Ie?(f.appendChild(Ie),f.style.display=""):(f.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}",f.style.display="")}else s.iconUrl?f.style.display="none":(f.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}",f.style.display="")}let u=r.querySelector("[data-role='launcher-image']");if(u){let te=(H=s.agentIconSize)!=null?H:"40px";u.style.height=te,u.style.width=te,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(u.src=s.iconUrl,u.style.display="block"):u.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let te=(I=s.callToActionIconSize)!=null?I:"32px";m.style.height=te,m.style.width=te,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 Ae=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,Ae=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let Ie=parseFloat(te)||24,le=Math.max(Ie-Ae,8),Ce=fe(s.callToActionIconName,le,"currentColor",2);Ce?m.appendChild(Ce):m.textContent=(D=s.callToActionIconText)!=null?D:"\u2197"}else m.textContent=(O=s.callToActionIconText)!=null?O:"\u2197"}let x=s.position&&wo[s.position]?wo[s.position]:wo["bottom-right"],b="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",L="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";r.className=i?L:`${b} ${x}`,i||(r.style.zIndex=String((J=s.zIndex)!=null?J:Sr));let E="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(me=s.border)!=null?me:E,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(de=s.collapsedMaxWidth)!=null?de:"",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},l={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:c,composer:l,replaceHeader:u=>(c.element.replaceWith(u.header),c.element=u.header,c.iconHolder=u.iconHolder,c.headerTitle=u.headerTitle,c.headerSubtitle=u.headerSubtitle,c.closeButton=u.closeButton,c.closeButtonWrapper=u.closeButtonWrapper,c.clearChatButton=u.clearChatButton,c.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{l.footer.replaceWith(u),l.footer=u}}},tp=({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:()=>ep(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=ep(e,r);return{instance:n,element:n.element}};var Gb=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=Gb(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},Xb=(e,t)=>{let r=w("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},Jb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},rp=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(":"))},op=320,Ph=320,Qb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Yb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Zb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),ev=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),tv=(e,t,r)=>{if(e.length===0)return null;try{let o=w("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,c)=>{var f;let l=w("img");l.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${c+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${op}px`,l.style.maxHeight=`${Ph}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;n+=1,l.addEventListener("error",()=>{p||(p=!0,n=Math.max(0,n-1),l.remove(),n===0&&s())}),l.addEventListener("load",()=>{p=!0}),Jb(i.image)?(l.src=i.image,o.appendChild(l)):(p=!0,n=Math.max(0,n-1),l.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},rv=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!rp(o.audio))return;let n=w("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${op}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},ov=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!rp(o.video))return;let n=w("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${op}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}},nv=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!rp(o.data))return;let n=w("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}},na=()=>{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},np=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:na};if(t){let n=t(o);if(n!==null)return n}return na()},av=(e,t)=>{let r=w("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=w("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=w(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},sv=(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},ap=(e,t,r)=>{var x,b,L,E,A,T,y;let o=(x=t.showCopy)!=null?x:!0,n=(b=t.showUpvote)!=null?b:!0,a=(L=t.showDownvote)!=null?L:!0,s=(E=t.showReadAloud)!=null?E:!1;if(!o&&!n&&!a&&!s){let S=w("div");return S.style.display="none",S.id=`actions-${e.id}`,S.setAttribute("data-actions-for",e.id),S}let i=(A=t.visibility)!=null?A:"hover",c=(T=t.align)!=null?T:"right",l=(y=t.layout)!=null?y:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[c],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[l],u=w("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let m=(S,v,M)=>{let W=cr({icon:S,label:v,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",M),W};return o&&u.appendChild(m("copy","Copy message","copy")),s&&u.appendChild(m("volume-2","Read aloud","read-aloud")),n&&u.appendChild(m("thumbs-up","Upvote","upvote")),a&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},Na=(e,t,r,o,n,a)=>{var se,ie,pe,Ee,De,j,Q,Fe,K,ce,qe,ot,yt,Ot,Qt,Ye,ge;let s=r!=null?r:{},i=(se=s.layout)!=null?se:"bubble",c=s.avatar,l=s.timestamp,p=(ie=c==null?void 0:c.show)!=null?ie:!1,f=(pe=l==null?void 0:l.show)!=null?pe:!1,u=(Ee=c==null?void 0:c.position)!=null?Ee:"left",m=(De=l==null?void 0:l.position)!=null?De:"below",x=sv(e.role,i),b=w("div",x.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=Qb(e),E=(Q=(j=e.content)==null?void 0:j.trim())!=null?Q:"",T=L.length>0&&E===fi,y=Ni((K=(Fe=a==null?void 0:a.widgetConfig)==null?void 0:Fe.features)==null?void 0:K.streamAnimation),S=(ot=(qe=(ce=a==null?void 0:a.widgetConfig)==null?void 0:ce.features)==null?void 0:qe.streamAnimation)==null?void 0:ot.plugins,v=e.role==="assistant"&&y.type!=="none"?Ss(y.type,S):null,M=e.role==="assistant"&&((yt=v==null?void 0:v.isAnimating)==null?void 0:yt.call(v,e))===!0,W=e.role==="assistant"&&v!==null&&(!!e.streaming||M);W&&(v!=null&&v.bubbleClass)&&b.classList.add(v.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),e.streaming&&H.classList.add("persona-content-streaming"),W&&v&&(v.containerClass&&H.classList.add(v.containerClass),H.style.setProperty("--persona-stream-step",`${y.speed}ms`),H.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let I=W?Oi((Ot=e.content)!=null?Ot:"",y.buffer,v,e,!!e.streaming):(Qt=e.content)!=null?Qt:"",D=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=D;W&&(v==null?void 0:v.wrap)==="char"?O=As(D,"char",e.id,{skipTags:v.skipTags}):W&&(v==null?void 0:v.wrap)==="word"&&(O=As(D,"word",e.id,{skipTags:v.skipTags}));let J=null;if(T?(J=document.createElement("div"),J.innerHTML=O,J.style.display="none",H.appendChild(J)):H.innerHTML=O,W&&(v!=null&&v.useCaret)&&!T&&E){let X=_i(),dt=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),ze=dt[dt.length-1];if(ze!=null&&ze.parentNode)ze.parentNode.insertBefore(X,ze.nextSibling);else{let ve=H.lastElementChild;ve?ve.appendChild(X):H.appendChild(X)}}if(f&&m==="inline"&&e.createdAt){let X=Lh(e,l,"span");X.classList.add("persona-timestamp-inline");let dt=H.lastElementChild;dt?dt.appendChild(X):H.appendChild(X)}if(L.length>0){let X=tv(L,!T&&!!E,()=>{T&&J&&(J.style.display="")});X?b.appendChild(X):T&&J&&(J.style.display="")}let me=Yb(e);if(me.length>0){let X=rv(me);X&&b.appendChild(X)}let de=Zb(e);if(de.length>0){let X=ov(de);X&&b.appendChild(X)}let te=ev(e);if(te.length>0){let X=nv(te);X&&b.appendChild(X)}if(b.appendChild(H),f&&m==="below"&&e.createdAt){let X=Lh(e,l);X.classList.add("persona-mt-1"),b.appendChild(X)}let Ae=e.role==="assistant"?Kb(e.stopReason,(ge=(Ye=a==null?void 0:a.widgetConfig)==null?void 0:Ye.copy)==null?void 0:ge.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(I&&I.trim()),dt=y.placeholder==="skeleton",ze=dt&&y.buffer==="line"&&X;if(X)ze&&b.appendChild(Ms());else if(dt)b.appendChild(Ms());else{let ve=np("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);ve&&b.appendChild(ve)}}if(Ae&&e.stopReason&&!e.streaming&&(E||(H.style.display="none"),b.appendChild(Xb(e.stopReason,Ae))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let X=ap(e,o,n);b.appendChild(X)}if(!p||e.role==="system")return b;let le=w("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ce=av(c,e.role);return u==="right"||u==="left"&&e.role==="user"?le.append(b,Ce):le.append(Ce,b),b.classList.remove("persona-max-w-[85%]"),b.classList.add("persona-max-w-[calc(85%-2.5rem)]"),le},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}):Na(e,t,r,o,n,a)};var Oa=new Set,iv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),lv=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
29
- `):""},Ih=(e,t)=>{let r=Oa.has(e),o=t.querySelector('button[data-expand-header="true"]'),n=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!n)return;o.setAttribute("aria-expanded",r?"true":"false");let s=o.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=fe(r?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=r?"Hide":"Show"}n.style.display=r?"":"none",a&&(a.style.display=r?"none":a.textContent||a.childNodes.length?"":"none")},sp=(e,t)=>{var de,te,Ae,Ie,le,Ce,se,ie,pe,Ee,De;let r=e.reasoning,o=w("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=(te=(de=t==null?void 0:t.features)==null?void 0:de.reasoningDisplay)!=null?te:{},a=n.expandable!==!1,s=a&&Oa.has(e.id),i=r.status!=="complete",c=lv(e,(Ae=n.previewMaxLines)!=null?Ae:3),l=w("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",a&&(l.setAttribute("aria-expanded",s?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=w("div","persona-flex persona-flex-col persona-text-left"),f=w("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",m=(Ie=t==null?void 0:t.reasoning)!=null?Ie:{},x=String((le=r.startedAt)!=null?le:Date.now()),b=()=>{let j=w("span","");return j.setAttribute("data-tool-elapsed",x),j.textContent=si(r),j},L=(Ce=m.renderCollapsedSummary)==null?void 0:Ce.call(m,{message:e,reasoning:r,defaultSummary:u,previewText:c,isActive:i,config:t!=null?t:{},elapsed:si(r),createElapsedElement:b});typeof L=="string"&&L.trim()?(f.textContent=L,p.appendChild(f)):L instanceof HTMLElement?p.appendChild(L):(f.textContent=u,p.appendChild(f));let E=w("span","persona-text-xs persona-text-persona-primary");E.textContent=Bg(r),p.appendChild(E);let A=(se=n.loadingAnimation)!=null?se:"none",T=m.activeTextTemplate,y=m.completeTextTemplate,S=i?T:y,v=L instanceof HTMLElement,M=(j,Q,Fe)=>{let K=Fe;for(let ce of Q){let qe=w("span","persona-tool-char");qe.style.setProperty("--char-index",String(K)),qe.textContent=ce===" "?"\xA0":ce,j.appendChild(qe),K++}return K},W=(j,Q)=>{f.textContent="";let Fe=ii(j,""),K=0;for(let ce of Fe){let qe=ce.styles.length>0?(()=>{let ot=w("span",ce.styles.map(yt=>`persona-tool-text-${yt}`).join(" "));return f.appendChild(ot),ot})():f;if(ce.isDuration&&i)qe.appendChild(b());else{let ot=ce.isDuration?si(r):ce.text;Q?K=M(qe,ot,K):qe.appendChild(document.createTextNode(ot))}}};if(!v&&S)if(E.style.display="none",f.style.display="",i&&A!=="none"){let j=(ie=m.loadingAnimationDuration)!=null?ie:2e3;f.setAttribute("data-preserve-animation","true"),A==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`),W(S,!1)):(f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),W(S,!0))}else W(S,!1);else if(!v&&i&&A!=="none"){f.style.display="";let j=(pe=m.loadingAnimationDuration)!=null?pe:2e3;if(f.setAttribute("data-preserve-animation","true"),A==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`);else{f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let Q=f.textContent||u;f.textContent="",M(f,Q,0)}r.status==="complete"&&(f.style.display="none")}else v||(r.status==="complete"?f.style.display="none":f.style.display="");let H=null;if(a){H=w("div","persona-flex persona-items-center");let Q=fe(s?"chevron-up":"chevron-down",16,"currentColor",2);Q?H.appendChild(Q):H.textContent=s?"Hide":"Show";let Fe=w("div","persona-flex persona-items-center persona-ml-auto");Fe.append(H),l.append(p,Fe)}else l.append(p);let I=w("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(I.setAttribute("data-persona-collapsed-preview","reasoning"),I.style.display="none",I.style.whiteSpace="pre-wrap",!s&&i&&n.activePreview&&c){let j=(De=(Ee=t==null?void 0:t.reasoning)==null?void 0:Ee.renderCollapsedPreview)==null?void 0:De.call(Ee,{message:e,reasoning:r,defaultPreview:c,isActive:i,config:t!=null?t:{}});iv(I,j)||(I.textContent=c),I.style.display=""}if(!s&&i&&n.activeMinHeight&&(o.style.minHeight=n.activeMinHeight),!a)return o.append(l,I),o;let D=w("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");D.style.display=s?"":"none";let O=r.chunks.join(""),J=w("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return J.textContent=O||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),D.appendChild(J),(()=>{if(l.setAttribute("aria-expanded",s?"true":"false"),H){H.innerHTML="";let Q=fe(s?"chevron-up":"chevron-down",16,"currentColor",2);Q?H.appendChild(Q):H.textContent=s?"Hide":"Show"}D.style.display=s?"":"none",I.style.display=s?"none":I.textContent||I.childNodes.length?"":"none"})(),o.append(l,I,D),o};var _a=new Set,dv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),cv=(e,t)=>{var a;let r=e.toolCall;if(!r)return"";let o=((a=r.chunks)!=null?a:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
30
- `);let n=Sn(r.args).trim();return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
31
- `):""},ip=(e,t)=>{var r,o,n;e.style.backgroundColor=(r=t.codeBlockBackgroundColor)!=null?r:"var(--persona-container, #f3f4f6)",e.style.borderColor=(o=t.codeBlockBorderColor)!=null?o:"var(--persona-border, #e5e7eb)",e.style.color=(n=t.codeBlockTextColor)!=null?n:"var(--persona-text, #171717)"},pv=(e,t)=>{var p,f,u,m,x;let r=e.toolCall,o=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,n=(f=o==null?void 0:o.collapsedMode)!=null?f:"tool-call",a=cv(e,(u=o==null?void 0:o.previewMaxLines)!=null?u:3),s=r?Dg(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i=r.status!=="complete",c=(m=t==null?void 0:t.toolCall)!=null?m:{},l=s;return n==="tool-name"?l=((x=r.name)==null?void 0:x.trim())||s:n==="tool-preview"&&a&&(l=a),i&&c.activeTextTemplate?l=Ol(r,c.activeTextTemplate,l):!i&&c.completeTextTemplate&&(l=Ol(r,c.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},Wh=(e,t,r)=>{var p;let o=_a.has(e),n=(p=r==null?void 0:r.toolCall)!=null?p:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto"),l=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let f=n.toggleTextColor||n.headerTextColor||"var(--persona-primary, #171717)",u=fe(o?"chevron-up":"chevron-down",16,f,2);u?l.appendChild(u):l.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},lp=(e,t)=>{var O,J,me,de,te,Ae,Ie,le,Ce;let r=e.toolCall,o=(O=t==null?void 0:t.toolCall)!=null?O:{},n=w("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=(J=t==null?void 0:t.features)==null?void 0:J.toolCallDisplay)!=null?me:{},s=a.expandable!==!1,i=s&&_a.has(e.id),{summary:c,previewText:l,isActive:p}=pv(e,t),f=w("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",s&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let u=w("div","persona-flex persona-flex-col persona-text-left"),m=w("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let x=String((de=r.startedAt)!=null?de:Date.now()),b=()=>{let se=w("span","");return se.setAttribute("data-tool-elapsed",x),se.textContent=fs(r),se},L=(Ae=o.renderCollapsedSummary)==null?void 0:Ae.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:l,collapsedMode:(te=a.collapsedMode)!=null?te:"tool-call",isActive:p,config:t!=null?t:{},elapsed:fs(r),createElapsedElement:b});typeof L=="string"&&L.trim()?(m.textContent=L,u.appendChild(m)):L instanceof HTMLElement?u.appendChild(L):(m.textContent=c,u.appendChild(m));let E=(Ie=a.loadingAnimation)!=null?Ie:"none",A=o.activeTextTemplate,T=o.completeTextTemplate,y=p?A:T,S=L instanceof HTMLElement,v=(se,ie,pe)=>{let Ee=pe;for(let De of ie){let j=w("span","persona-tool-char");j.style.setProperty("--char-index",String(Ee)),j.textContent=De===" "?"\xA0":De,se.appendChild(j),Ee++}return Ee},M=(se,ie)=>{var j;m.textContent="";let pe=((j=r.name)==null?void 0:j.trim())||"tool",Ee=ii(se,pe),De=0;for(let Q of Ee){let Fe=Q.styles.length>0?(()=>{let K=w("span",Q.styles.map(ce=>`persona-tool-text-${ce}`).join(" "));return m.appendChild(K),K})():m;if(Q.isDuration&&p)Fe.appendChild(b());else{let K=Q.isDuration?fs(r):Q.text;ie?De=v(Fe,K,De):Fe.appendChild(document.createTextNode(K))}}};if(!S)if(p&&E!=="none"){let se=(le=o.loadingAnimationDuration)!=null?le:2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${se}ms`),y&&M(y,!1);else if(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${se}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 ie=m.textContent||c;m.textContent="",v(m,ie,0)}}else y&&M(y,!1);let W=null;if(s){W=w("div","persona-flex persona-items-center");let se=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",ie=fe(i?"chevron-up":"chevron-down",16,se,2);ie?W.appendChild(ie):W.textContent=i?"Hide":"Show";let pe=w("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");pe.append(W),f.append(u,pe)}else f.append(u);let H=w("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","tool"),H.style.display="none",H.style.whiteSpace="pre-wrap",!i&&p&&a.activePreview&&l){let se=(Ce=o.renderCollapsedPreview)==null?void 0:Ce.call(o,{message:e,toolCall:r,defaultPreview:l,isActive:p,config:t!=null?t:{}});dv(H,se)||(H.textContent=l),H.style.display=""}if(!i&&p&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(f,H),n;let I=w("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(I.style.display=i?"":"none",o.contentBackgroundColor&&(I.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(I.style.color=o.contentTextColor),o.contentPaddingX&&(I.style.paddingLeft=o.contentPaddingX,I.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(I.style.paddingTop=o.contentPaddingY,I.style.paddingBottom=o.contentPaddingY),r.name){let se=w("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?se.style.color=o.contentTextColor:o.headerTextColor&&(se.style.color=o.headerTextColor),se.textContent=r.name,I.appendChild(se)}if(r.args!==void 0){let se=w("div","persona-space-y-1"),ie=w("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(ie.style.color=o.labelTextColor),ie.textContent="Arguments";let pe=w("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",ip(pe,o),pe.textContent=Sn(r.args),se.append(ie,pe),I.appendChild(se)}if(r.chunks&&r.chunks.length){let se=w("div","persona-space-y-1"),ie=w("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(ie.style.color=o.labelTextColor),ie.textContent="Activity";let pe=w("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",ip(pe,o),pe.textContent=r.chunks.join(""),se.append(ie,pe),I.appendChild(se)}if(r.status==="complete"&&r.result!==void 0){let se=w("div","persona-space-y-1"),ie=w("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(ie.style.color=o.labelTextColor),ie.textContent="Result";let pe=w("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",ip(pe,o),pe.textContent=Sn(r.result),se.append(ie,pe),I.appendChild(se)}if(r.status==="complete"&&typeof r.duration=="number"){let se=w("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(se.style.color=o.contentTextColor),se.textContent=`Duration: ${r.duration}ms`,I.appendChild(se)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let se=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",ie=fe(i?"chevron-up":"chevron-down",16,se,2);ie?W.appendChild(ie):W.textContent=i?"Hide":"Show"}I.style.display=i?"":"none",H.style.display=i?"none":H.textContent||H.childNodes.length?"":"none"})(),n.append(f,H,I),n};var aa=new Map,Qi=e=>{let r=(e.startsWith(bo)?e.slice(bo.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=aa.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=fe(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 Yi=(e,t)=>{var M,W,H,I,D,O,J,me,de,te,Ae,Ie,le,Ce,se;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=w("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=w("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=w("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let c=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",l=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(H=o==null?void 0:o.titleColor)!=null?H:"currentColor",p=fe(c,20,l,2);p&&i.appendChild(p);let f=w("div","persona-flex-1 persona-min-w-0"),u=w("div","persona-flex persona-items-center persona-gap-2"),m=w("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(I=o==null?void 0:o.title)!=null?I:"Approval Required",u.appendChild(m),!n){let ie=w("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");ie.setAttribute("data-approval-status",r.status),r.status==="approved"?(ie.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",ie.style.color="var(--persona-palette-colors-success-700, #15803d)",ie.textContent="Approved"):r.status==="denied"?(ie.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",ie.style.color="var(--persona-palette-colors-error-700, #b91c1c)",ie.textContent="Denied"):r.status==="timeout"&&(ie.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",ie.style.color="var(--persona-palette-colors-warning-700, #b45309)",ie.textContent="Timeout"),u.appendChild(ie)}f.appendChild(u);let b=r.toolType==="webmcp"||r.toolName.startsWith(bo)?as(r.toolName):void 0,L=(D=o==null?void 0:o.formatDescription)==null?void 0:D.call(o,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...b?{displayTitle:b}:{},...r.reason?{reason:r.reason}:{}}),E=!r.toolName,A=L||(E?r.description:`The assistant wants to use \u201C${b!=null?b:Qi(r.toolName)}\u201D.`),T=w("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=A,f.appendChild(T),r.reason){let ie=w("p","persona-text-sm persona-mt-1 persona-text-persona-muted");ie.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?ie.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(ie.style.color=o.descriptionColor);let pe=w("span","persona-font-medium");pe.textContent=`${(O=o==null?void 0:o.reasonLabel)!=null?O:"Agent's stated reason:"} `,ie.appendChild(pe),ie.appendChild(document.createTextNode(r.reason)),f.appendChild(ie)}let y=(J=o==null?void 0:o.detailsDisplay)!=null?J:"collapsed",S=!!r.description&&!E,v=S||!!r.parameters;if(y!=="hidden"&&v){let ie=Bh(e.id,t),pe=w("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");pe.type="button",pe.setAttribute("data-expand-header","true"),pe.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(pe.style.color=o.descriptionColor);let Ee=w("span");Ee.setAttribute("data-approval-details-label","true");let De=w("span","persona-inline-flex persona-items-center");De.setAttribute("data-approval-details-chevron","true"),pe.append(Ee,De),Dh(pe,ie,t),f.appendChild(pe);let j=w("div");if(j.setAttribute("data-approval-details","true"),j.style.display=ie?"":"none",S){let Q=w("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(Q.style.color=o.descriptionColor),Q.textContent=r.description,j.appendChild(Q)}if(r.parameters){let Q=w("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&&(Q.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(Q.style.color=o.parameterTextColor),Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Q.textContent=Sn(r.parameters),j.appendChild(Q)}f.appendChild(j)}if(n){let ie=w("div","persona-flex persona-gap-2 persona-mt-2");ie.setAttribute("data-approval-buttons","true");let pe=w("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");pe.type="button",pe.style.backgroundColor=(me=o==null?void 0:o.approveButtonColor)!=null?me:"var(--persona-approval-approve-bg, #22c55e)",pe.style.color=(de=o==null?void 0:o.approveButtonTextColor)!=null?de:"#ffffff",pe.setAttribute("data-approval-action","approve");let Ee=fe("shield-check",14,(te=o==null?void 0:o.approveButtonTextColor)!=null?te:"#ffffff",2);Ee&&(Ee.style.marginRight="4px",pe.appendChild(Ee));let De=document.createTextNode((Ae=o==null?void 0:o.approveLabel)!=null?Ae:"Approve");pe.appendChild(De);let j=w("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=(Ie=o==null?void 0:o.denyButtonColor)!=null?Ie:"transparent",j.style.color=(le=o==null?void 0:o.denyButtonTextColor)!=null?le:"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 Q=fe("shield-x",14,(Ce=o==null?void 0:o.denyButtonTextColor)!=null?Ce:"var(--persona-feedback-error, #dc2626)",2);Q&&(Q.style.marginRight="4px",j.appendChild(Q));let Fe=document.createTextNode((se=o==null?void 0:o.denyLabel)!=null?se:"Deny");j.appendChild(Fe),ie.append(pe,j),f.appendChild(ie)}return s.append(i,f),a.appendChild(s),a};function uv(e){var r,o;let t=(r=e.getRootNode)==null?void 0:r.call(e);return t instanceof ShadowRoot?t:((o=e.ownerDocument)!=null?o:document).body}function Nh(e){var b;let{anchor:t,content:r,placement:o="bottom-start",offset:n=6,matchAnchorWidth:a=!1,zIndex:s=2147483e3,onOpen:i,onDismiss:c}=e,l=(b=e.container)!=null?b:uv(t),p=!1,f=null,u=()=>{if(!p)return;let L=t.getBoundingClientRect();r.style.position="fixed",a&&(r.style.minWidth=`${L.width}px`);let E=o==="top-start"||o==="top-end"?L.top-n-r.getBoundingClientRect().height:L.bottom+n,A=o==="bottom-end"||o==="top-end"?L.right-r.getBoundingClientRect().width:L.left;r.style.top=`${E}px`,r.style.left=`${A}px`},m=()=>{p&&(p=!1,f&&(f(),f=null),r.remove())},x=()=>{var S,v,M;if(p)return;p=!0,s!=null&&(r.style.zIndex=String(s)),l.appendChild(r),u();let L=(v=((S=t.ownerDocument)!=null?S:document).defaultView)!=null?v:window,E=(M=t.ownerDocument)!=null?M:document,A=()=>{if(!t.isConnected){m(),c==null||c("anchor-removed");return}u()},T=W=>{let H=typeof W.composedPath=="function"?W.composedPath():[];H.includes(r)||H.includes(t)||(m(),c==null||c("outside"))},y=L.setTimeout(()=>{E.addEventListener("pointerdown",T,!0)},0);L.addEventListener("scroll",A,!0),L.addEventListener("resize",A),f=()=>{L.clearTimeout(y),E.removeEventListener("pointerdown",T,!0),L.removeEventListener("scroll",A,!0),L.removeEventListener("resize",A)},i==null||i()};return{get isOpen(){return p},open:x,close:m,toggle:()=>p?m():x(),reposition:u,destroy:m}}function Oh(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(r=>r instanceof HTMLElement&&(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable))}var fv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),_h=(e,t)=>{let r=e.keyHandlers.get(t);r&&(document.removeEventListener("keydown",r),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},sa=(e,t)=>{_h(e,t);let r=e.pendingOrder.indexOf(t);r!==-1&&e.pendingOrder.splice(r,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},mv=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,gv=(e,t)=>{var o,n;let r=(o=t==null?void 0:t.detailsDisplay)!=null?o:"collapsed";return(n=aa.get(e))!=null?n:r==="expanded"},dp=e=>{let t=w("span","persona-approval-kbd");return t.textContent=e,t},hv=(e,t)=>{var l,p;let r=w("span","persona-approval-title");t!=null&&t.titleColor&&(r.style.color=t.titleColor);let n=e.toolType==="webmcp"||e.toolName.startsWith(bo)?as(e.toolName):void 0,a=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(l=e.description)!=null?l:"",parameters:e.parameters,...n?{displayTitle:n}:{},...e.reason?{reason:e.reason}:{}});if(a)return r.textContent=a,r;let s=n!=null?n:Qi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;r.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=s,r.appendChild(c),i){r.append(" from ");let f=document.createElement("strong");f.textContent=i,r.appendChild(f)}return r},xv=e=>{let t=w("div","persona-approval-resolved"),r=fe("ban",15,"currentColor",2);r&&t.appendChild(r);let o=w("span","persona-approval-resolved-name");return o.textContent=e.toolName?Qi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},yv=(e,t,r,o,n,a,s)=>{var W,H,I,D,O,J,me;let i=w("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o!=null&&o.backgroundColor&&(i.style.background=o.backgroundColor),o!=null&&o.borderColor&&(i.style.borderColor=o.borderColor),(o==null?void 0:o.shadow)!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let c=(W=o==null?void 0:o.detailsDisplay)!=null?W:"collapsed",l=!!r.description&&c!=="hidden",p=r.parameters!=null&&c!=="hidden",f=l||p,u=f&&gv(t.id,o),m=(H=o==null?void 0:o.showDetailsLabel)!=null?H:"Show details",x=(I=o==null?void 0:o.hideDetailsLabel)!=null?I:"Hide details",b=w("button","persona-approval-head");b.type="button",f?(b.setAttribute("data-action","toggle-params"),b.setAttribute("aria-expanded",u?"true":"false"),b.setAttribute("aria-label",u?x:m)):b.setAttribute("data-static","true");let L=w("span","persona-approval-logo"),E=fe("shield-check",16,"currentColor",2);E&&L.appendChild(E),b.appendChild(L);let A=hv(r,o);if(f){let de=w("span","persona-approval-toggle");de.setAttribute("aria-hidden","true");let te=fe("chevron-down",14,"currentColor",2);te&&de.appendChild(te),A.append(" "),A.appendChild(de)}b.appendChild(A),i.appendChild(b);let T=w("div","persona-approval-body");if(f){let de=w("div","persona-approval-details");if(de.setAttribute("data-role","params"),de.hidden=!u,l){let te=w("p","persona-approval-desc");o!=null&&o.descriptionColor&&(te.style.color=o.descriptionColor),te.textContent=r.description,de.appendChild(te)}if(p){let te=w("pre","persona-approval-params");o!=null&&o.parameterBackgroundColor&&(te.style.background=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(te.style.color=o.parameterTextColor),te.textContent=Sn(r.parameters),de.appendChild(te)}T.appendChild(de)}if(r.reason){let de=w("p","persona-approval-reason");o!=null&&o.reasonColor?de.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(de.style.color=o.descriptionColor);let te=w("span","persona-approval-reason-label");te.textContent=`${(D=o==null?void 0:o.reasonLabel)!=null?D:"Agent's stated reason:"} `,de.append(te,document.createTextNode(r.reason)),T.appendChild(de)}let y=w("div","persona-approval-actions"),S=null,v=de=>{o!=null&&o.approveButtonColor&&(de.style.background=o.approveButtonColor),o!=null&&o.approveButtonTextColor&&(de.style.color=o.approveButtonTextColor)},M=w("button","persona-approval-deny");if(M.type="button",M.setAttribute("data-action","deny"),o!=null&&o.denyButtonColor&&(M.style.background=o.denyButtonColor),o!=null&&o.denyButtonTextColor&&(M.style.color=o.denyButtonTextColor),M.append((O=o==null?void 0:o.denyLabel)!=null?O:"Deny"),s){let de=w("div","persona-approval-split"),te=w("button","persona-approval-primary");te.type="button",te.setAttribute("data-action","always"),v(te),te.append((J=o==null?void 0:o.approveLabel)!=null?J:"Always allow",dp("\u23CE"));let Ae=w("button","persona-approval-caret");Ae.type="button",Ae.setAttribute("data-action","toggle-menu"),Ae.setAttribute("aria-label","More options"),v(Ae);let Ie=fe("chevron-down",15,"currentColor",2);Ie&&Ae.appendChild(Ie),de.append(te,Ae),y.append(de,M),M.append(dp("Esc"));let le=w("div","persona-approval-menu"),Ce=w("button","persona-approval-menu-item");Ce.type="button",Ce.append("Allow once",dp("\u2318\u23CE")),le.appendChild(Ce),S=Nh({anchor:de,content:le,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,S),Ce.addEventListener("click",()=>{sa(e,t.id),n()})}else{let de=w("button","persona-approval-primary persona-approval-primary--solo");de.type="button",de.setAttribute("data-action","allow"),v(de),de.append((me=o==null?void 0:o.approveLabel)!=null?me:"Allow"),y.append(de,M)}return T.appendChild(y),i.appendChild(T),i.addEventListener("click",de=>{let te=de.target instanceof Element?de.target.closest("[data-action]"):null;if(!te)return;let Ae=te.getAttribute("data-action");if(Ae==="toggle-params"){let Ie=i.querySelector('[data-role="params"]');if(Ie){let le=Ie.hidden;Ie.hidden=!le,b.setAttribute("aria-expanded",le?"true":"false"),b.setAttribute("aria-label",le?x:m),aa.set(t.id,le)}return}if(Ae==="toggle-menu"){S==null||S.toggle();return}if(Ae==="always"){sa(e,t.id),n({remember:!0});return}if(Ae==="allow"){sa(e,t.id),n();return}if(Ae==="deny"){sa(e,t.id),a();return}}),i},Uh=()=>{let e=fv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:n,deny:a,config:s})=>{let i=o==null?void 0:o.approval;if(!i)return null;let c=mv(s);if(i.status!=="pending"){if(sa(e,o.id),i.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return xv(i)}_h(e,o.id);let l=(c==null?void 0:c.enableAlwaysAllow)===!0,p=yv(e,o,i,c,n,a,l);if(l){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let f=u=>{Oh(u)||o.id===e.latestPendingApprovalId&&(u.key!=="Escape"&&u.key!=="Enter"||(u.preventDefault(),u.stopImmediatePropagation(),sa(e,o.id),u.key==="Escape"?a():u.metaKey||u.ctrlKey?n():n({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return p}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])sa(e,o);e.latestPendingApprovalId=null}}};var qh=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(r=null),!n||!n.length||!p&&(i!=null?i:a?a.getMessages():[]).some(L=>L.role==="user"))return;let f=document.createDocumentFragment(),u=a?a.isStreaming():!1,m=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(n.forEach(x=>{let b=w("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");b.type="button",b.textContent=x,b.disabled=u,c!=null&&c.fontFamily&&(b.style.fontFamily=m(c.fontFamily)),c!=null&&c.fontWeight&&(b.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(b.style.paddingLeft=c.paddingX,b.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(b.style.paddingTop=c.paddingY,b.style.paddingBottom=c.paddingY),b.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),a.sendMessage(x))}),f.appendChild(b),t.push(b)}),e.appendChild(f),p){let x=JSON.stringify(n);x!==r&&(r=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var Ls=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of r)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ps=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let n=o.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(o){r(o)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}};var bv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),vv=new Set(["step_start","execution_start"]),wv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Cv=new Set(["step_complete","agent_turn_complete"]),Sv=new Set(["flow_complete","agent_complete"]),Vh=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),$h=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ia=(e,t)=>{let r=e[t];return $h(r)?r:void 0};function cp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Zi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Av(e,t){return typeof t.type=="string"?t.type:e}function Mv(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 Tv(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 zh(e){var o,n,a,s,i;let t=ia(e,"result"),r=[ia(e,"tokens"),ia(e,"totalTokens"),t?ia(t,"tokens"):void 0,ia(e,"usage"),t?ia(t,"usage"):void 0];for(let c of r){if(!c)continue;let l=(n=(o=Yr(c.output))!=null?o:Yr(c.outputTokens))!=null?n:Yr(c.completionTokens);if(l!==void 0)return l}return(i=(a=Yr(e.outputTokens))!=null?a:Yr(e.completionTokens))!=null?i:t?(s=Yr(t.outputTokens))!=null?s:Yr(t.completionTokens):void 0}function Ev(e){var r,o,n,a,s;let t=ia(e,"result");return(s=(n=(o=(r=Yr(e.executionTime))!=null?r:Yr(e.executionTimeMs))!=null?o:Yr(e.execution_time))!=null?n:Yr(e.duration))!=null?s:t?(a=Yr(t.executionTime))!=null?a:Yr(t.executionTimeMs):void 0}function kv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Rs=class{constructor(t=kv){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:Zi(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)){Vh.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Av(t,r),n=this.now();if(bv.has(o)){this.startRun(n);return}if(vv.has(o)){this.run||this.startRun(n);return}if(wv.has(o)){if(!Tv(o,r))return;let s=Mv(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+cp(i.visibleCharCount),l=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Zi(c,l),outputTokens:c,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Cv.has(o)){if(!this.run)return;let s=this.run,i=zh(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,l=s.exactOutputTokens+cp(s.visibleCharCount),p=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:Zi(l,p),outputTokens:l,durationMs:p,source:c?"usage":"estimate"};return}if(Sv.has(o)){if(!this.run)return;let s=this.run,i=zh(r),c=i!=null?i:s.exactOutputTokens+cp(s.visibleCharCount),l=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:Zi(c,p),outputTokens:c,durationMs:p,source:l},this.run=null;return}if(Vh.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=Ev(r);return a!=null?a:o-t.startedAt}};function Ua(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var Lv={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)"}},Pv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Rv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Iv=100;function Wv(e,t){let r={...Lv,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return Pv}function Hv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Bv(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 Dv(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 Fv(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 Nv(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 Ov(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function _v(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 Uv(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=w("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=w("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 pp(e,t,r,o,n,a,s,i){var u;let c=n.has(e.id),l=w("div","persona-border-b persona-border-persona-divider persona-text-xs");Ua(l,(u=o.classNames)==null?void 0:u.eventRow);let p=s.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>f(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(f()),l;function f(){var O,J;let m=w("div",""),x=w("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let b=w("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),L=fe(c?"chevron-down":"chevron-right","14px","currentColor",2);L&&b.appendChild(L);let E=w("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(O=o.timestampFormat)!=null?O:"relative";E.textContent=A==="relative"?Hv(e.timestamp,r):Bv(e.timestamp);let T=null;o.showSequenceNumbers!==!1&&(T=w("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(t+1));let y=Wv(e.type,o.badgeColors),S=w("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");S.style.backgroundColor=y.bg,S.style.color=y.text,S.style.borderColor=y.text+"50",S.textContent=e.type;let v=(J=o.descriptionFields)!=null?J:Rv,M=Dv(e.payload,v),W=null;M&&(W=w("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=M);let H=w("div","persona-flex-1 persona-min-w-0"),I=w("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),D=fe("clipboard","12px","currentColor",1.5);return D&&I.appendChild(D),I.addEventListener("click",async me=>{me.stopPropagation(),await Fv(Nv(e)),I.innerHTML="";let de=fe("check","12px","currentColor",1.5);de&&I.appendChild(de),setTimeout(()=>{I.innerHTML="";let te=fe("clipboard","12px","currentColor",1.5);te&&I.appendChild(te)},1500)}),x.appendChild(b),x.appendChild(E),T&&x.appendChild(T),x.appendChild(S),W&&x.appendChild(W),x.appendChild(H),x.appendChild(I),m.appendChild(x),c&&m.appendChild(Uv(e,s,i)),m}}function jh(e){var x,b,L,E,A;let{buffer:t,getFullHistory:r,onClose:o,config:n,plugins:a=[],getThroughput:s}=e,i=(x=n==null?void 0:n.features)==null?void 0:x.scrollToBottom,c=(i==null?void 0:i.enabled)!==!1,l=(b=i==null?void 0:i.iconName)!=null?b:"arrow-down",p=(L=i==null?void 0:i.label)!=null?L:"",f=(A=(E=n==null?void 0:n.features)==null?void 0:E.eventStream)!=null?A:{},u=a.find(T=>T.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&n){let T=u.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(T)return{element:T,update:()=>{},destroy:()=>{}}}return m();function m(){let T=f.classNames,y=w("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ua(y,T==null?void 0:T.panel);let S=[],v="",M="",W=null,H=[],I={},D=0,O=Bi(),J=0,me=0,de=!1,te=null,Ae=!1,Ie=0,le=new Set,Ce=new Map,se="",ie="",pe=null,Ee,De,j,Q,Fe=null,K=null,ce=null;function qe(){let ae=w("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),F=w("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");if(Ua(F,T==null?void 0:T.headerBar),s){K=w("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),K.style.cursor="help",Fe=w("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"),Fe.textContent="-- tok/s",ce=w("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ce.style.display="none",ce.style.pointerEvents="none";let _t=K,Fr=ce,qt=()=>{if(!Fr.textContent)return;let Zr=_t.getBoundingClientRect(),br=ae.getBoundingClientRect();Fr.style.left=`${Zr.left-br.left}px`,Fr.style.top=`${Zr.bottom-br.top+4}px`,Fr.style.display="block"},Nr=()=>{Fr.style.display="none"};K.addEventListener("mouseenter",qt),K.addEventListener("mouseleave",Nr),K.appendChild(Fe)}let he=w("div","persona-flex-1");Ee=w("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 Ne=w("option","");Ne.value="",Ne.textContent="All events (0)",Ee.appendChild(Ne),De=w("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"),De.type="button",De.title="Copy All";let Je=fe("clipboard-copy","12px","currentColor",1.5);Je&&De.appendChild(Je);let Bt=w("span","persona-event-copy-all persona-text-xs");Bt.textContent="Copy All",De.appendChild(Bt),K&&F.appendChild(K),F.appendChild(he),F.appendChild(Ee),F.appendChild(De);let Mt=w("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ua(Mt,T==null?void 0:T.searchBar);let gt=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),Lt=w("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");gt&&Lt.appendChild(gt),j=w("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"),Ua(j,T==null?void 0:T.searchInput),j.type="text",j.placeholder="Search event payloads...",Q=w("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"),Q.type="button",Q.style.display="none";let Jt=fe("x","12px","currentColor",2);return Jt&&Q.appendChild(Jt),Mt.appendChild(Lt),Mt.appendChild(j),Mt.appendChild(Q),ae.appendChild(F),ae.appendChild(Mt),ce&&ae.appendChild(ce),ae}let ot,yt=a.find(ae=>ae.renderEventStreamToolbar);if(yt!=null&&yt.renderEventStreamToolbar&&n){let ae=yt.renderEventStreamToolbar({config:n,defaultRenderer:()=>qe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:F=>{v=F,Z(),bt()},onSearchChange:F=>{M=F,Z(),bt()}});ot=ae!=null?ae:qe()}else ot=qe();let Ot=w("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");Ot.style.display="none";function Qt(){if(!s||!Fe||!K)return;let ae=s(),F=Ov(ae);Fe.textContent=F;let he=_v(ae);ce&&(ce.textContent=he,he||(ce.style.display="none")),K.setAttribute("aria-label",he?`Throughput: ${F}, ${he}`:`Throughput: ${F}`)}let Ye=w("div","persona-flex-1 persona-min-h-0 persona-relative"),ge=w("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ge.style.height="100%";let X=w("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");Ua(X,T==null?void 0:T.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let dt=fe(l,"14px","currentColor",2);dt&&X.appendChild(dt);let ze=w("span","");ze.textContent=p,X.appendChild(ze);let ve=w("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ve.style.display="none",Ye.appendChild(ge),Ye.appendChild(ve),Ye.appendChild(X),y.setAttribute("tabindex","0"),y.appendChild(ot),y.appendChild(Ot),y.appendChild(Ye);function Me(){let ae=t.getAll(),F={};for(let Mt of ae)F[Mt.type]=(F[Mt.type]||0)+1;let he=Object.keys(F).sort(),Ne=he.length!==H.length||!he.every((Mt,gt)=>Mt===H[gt]),vt=!Ne&&he.some(Mt=>F[Mt]!==I[Mt]),Je=ae.length!==Object.values(I).reduce((Mt,gt)=>Mt+gt,0);if(!Ne&&!vt&&!Je||(H=he,I=F,!Ee))return;let Bt=Ee.value;if(Ee.options[0].textContent=`All events (${ae.length})`,Ne){for(;Ee.options.length>1;)Ee.remove(1);for(let Mt of he){let gt=w("option","");gt.value=Mt,gt.textContent=`${Mt} (${F[Mt]||0})`,Ee.appendChild(gt)}Bt&&he.includes(Bt)?Ee.value=Bt:Bt&&(Ee.value="",v="")}else for(let Mt=1;Mt<Ee.options.length;Mt++){let gt=Ee.options[Mt];gt.textContent=`${gt.value} (${F[gt.value]||0})`}}function et(){let ae=t.getAll();if(v&&(ae=ae.filter(F=>F.type===v)),M){let F=M.toLowerCase();ae=ae.filter(he=>he.type.toLowerCase().includes(F)||he.payload.toLowerCase().includes(F))}return ae}function Pt(){return v!==""||M!==""}function Z(){D=0,J=0,O.resume(),X.style.display="none"}function Ue(ae){le.has(ae)?le.delete(ae):le.add(ae),pe=ae;let F=ge.scrollTop,he=O.isFollowing();Ae=!0,O.pause(),bt(),ge.scrollTop=F,he&&O.resume(),Ae=!1}function Ar(){return ta(ge,50)}function bt(){me=Date.now(),de=!1,Qt(),Me();let ae=t.getEvictedCount();ae>0?(Ot.textContent=`${ae.toLocaleString()} older events truncated`,Ot.style.display=""):Ot.style.display="none",S=et();let F=S.length,he=t.getSize()>0;F===0&&he&&Pt()?(ve.textContent=M?`No events matching '${M}'`:"No events matching filter",ve.style.display="",ge.style.display="none"):(ve.style.display="none",ge.style.display=""),De&&(De.title=Pt()?`Copy Filtered (${F})`:"Copy All"),c&&!O.isFollowing()&&F>D&&(J+=F-D,ze.textContent=p?`${p}${J>0?` (${J})`:""}`:"",X.style.display=""),D=F;let Ne=t.getAll(),vt=Ne.length>0?Ne[0].timestamp:0,Je=new Set(S.map(gt=>gt.id));for(let gt of le)Je.has(gt)||le.delete(gt);let Bt=v!==se||M!==ie,Mt=Ce.size===0&&S.length>0;if(Bt||Mt||S.length===0){ge.innerHTML="",Ce.clear();let gt=document.createDocumentFragment();for(let Lt=0;Lt<S.length;Lt++){let Jt=pp(S[Lt],Lt,vt,f,le,Ue,a,n);Ce.set(S[Lt].id,Jt),gt.appendChild(Jt)}ge.appendChild(gt),se=v,ie=M,pe=null}else{if(pe!==null){let Lt=Ce.get(pe);if(Lt&&Lt.parentNode===ge){let Jt=S.findIndex(_t=>_t.id===pe);if(Jt>=0){let _t=pp(S[Jt],Jt,vt,f,le,Ue,a,n);ge.insertBefore(_t,Lt),Lt.remove(),Ce.set(pe,_t)}}pe=null}let gt=new Set(S.map(Lt=>Lt.id));for(let[Lt,Jt]of Ce)gt.has(Lt)||(Jt.remove(),Ce.delete(Lt));for(let Lt=0;Lt<S.length;Lt++){let Jt=S[Lt];if(!Ce.has(Jt.id)){let _t=pp(Jt,Lt,vt,f,le,Ue,a,n);Ce.set(Jt.id,_t),ge.appendChild(_t)}}}O.isFollowing()&&(ge.scrollTop=ge.scrollHeight)}function yr(){if(Date.now()-me>=Iv){te!==null&&(cancelAnimationFrame(te),te=null),bt();return}de||(de=!0,te=requestAnimationFrame(()=>{te=null,bt()}))}let Co=(ae,F)=>{if(!De)return;De.innerHTML="";let he=fe(ae,"12px","currentColor",1.5);he&&De.appendChild(he);let Ne=w("span","persona-text-xs");Ne.textContent="Copy All",De.appendChild(Ne),setTimeout(()=>{De.innerHTML="";let vt=fe("clipboard-copy","12px","currentColor",1.5);vt&&De.appendChild(vt);let Je=w("span","persona-text-xs");Je.textContent="Copy All",De.appendChild(Je),De.disabled=!1},F)},So=async()=>{if(De){De.disabled=!0;try{let ae;Pt()?ae=S:r?(ae=await r(),ae.length===0&&(ae=t.getAll())):ae=t.getAll();let F=ae.map(he=>{try{return JSON.parse(he.payload)}catch{return he.payload}});await navigator.clipboard.writeText(JSON.stringify(F,null,2)),Co("check",1500)}catch{Co("x",1500)}}},P=()=>{Ee&&(v=Ee.value,Z(),bt())},ee=()=>{!j||!Q||(Q.style.display=j.value?"":"none",W&&clearTimeout(W),W=setTimeout(()=>{M=j.value,Z(),bt()},150))},Se=()=>{!j||!Q||(j.value="",M="",Q.style.display="none",W&&clearTimeout(W),Z(),bt())},We=()=>{if(Ae)return;let ae=ge.scrollTop,{action:F,nextLastScrollTop:he}=Di({following:O.isFollowing(),currentScrollTop:ae,lastScrollTop:Ie,nearBottom:Ar(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ie=he,F==="resume"?(O.resume(),J=0,X.style.display="none"):F==="pause"&&(O.pause(),c&&(ze.textContent=p,X.style.display=""))},ke=ae=>{let F=Fi({following:O.isFollowing(),deltaY:ae.deltaY,nearBottom:Ar(),resumeWhenNearBottom:!0});F==="pause"?(O.pause(),c&&(ze.textContent=p,X.style.display="")):F==="resume"&&(O.resume(),J=0,X.style.display="none")},He=()=>{c&&(ge.scrollTop=ge.scrollHeight,O.resume(),J=0,X.style.display="none")},Ge=ae=>{let F=ae.target;if(!F||F.closest("button"))return;let he=F.closest("[data-event-id]");if(!he)return;let Ne=he.getAttribute("data-event-id");Ne&&Ue(Ne)},st=ae=>{if((ae.metaKey||ae.ctrlKey)&&ae.key==="f"){ae.preventDefault(),j==null||j.focus(),j==null||j.select();return}ae.key==="Escape"&&(j&&document.activeElement===j?(Se(),j.blur(),y.focus()):o&&o())};De&&De.addEventListener("click",So),Ee&&Ee.addEventListener("change",P),j&&j.addEventListener("input",ee),Q&&Q.addEventListener("click",Se),ge.addEventListener("scroll",We),ge.addEventListener("wheel",ke,{passive:!0}),ge.addEventListener("click",Ge),X.addEventListener("click",He),y.addEventListener("keydown",st);function Rt(){W&&clearTimeout(W),te!==null&&(cancelAnimationFrame(te),te=null),de=!1,Ce.clear(),De&&De.removeEventListener("click",So),Ee&&Ee.removeEventListener("change",P),j&&j.removeEventListener("input",ee),Q&&Q.removeEventListener("click",Se),ge.removeEventListener("scroll",We),ge.removeEventListener("wheel",ke),ge.removeEventListener("click",Ge),X.removeEventListener("click",He),y.removeEventListener("keydown",st)}return{element:y,update:yr,destroy:Rt}}}function Gh(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",n=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(u);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,f.appendChild(m)}else f.textContent=s;if(l.append(p,f),i.append(c,l),n==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${r}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",o),i.append(u)}return i}var Kh=(e,t)=>{var o,n,a;let r=(a=(n=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(r){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",c=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=r({artifact:{artifactId:i,title:s,artifactType:l,status:c},config:t.config,defaultRenderer:()=>Gh(e,t)});if(p)return p}return Gh(e,t)};var up=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)})}},rn=new up;rn.register("PersonaArtifactCard",Kh);function qv(e){var n;let t=w("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=w("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let o=w("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 Xh(e,t){var De,j,Q,Fe;let r=(j=(De=e.features)==null?void 0:De.artifacts)==null?void 0:j.layout,n=((Q=r==null?void 0:r.toolbarPreset)!=null?Q:"default")==="document",a=(Fe=r==null?void 0:r.panePadding)==null?void 0:Fe.trim(),s=e.markdown?Gn(e.markdown):null,i=Ma(e.sanitize),c=K=>{let ce=s?s(K):Fo(K);return i?i(ce):ce},l=typeof document!="undefined"?w("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),D==null||D.hide()};l&&l.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let f=w("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");f.setAttribute("data-persona-theme-zone","artifact-pane"),n&&f.classList.add("persona-artifact-pane-document");let u=w("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&u.classList.add("persona-artifact-toolbar-document");let m=w("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=w("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 K;p(),(K=t.onDismiss)==null||K.call(t)});let b="rendered",L=w("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=n?cr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):cr({icon:"eye",label:"Rendered view"}),A=n?cr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):cr({icon:"code-2",label:"Source"}),T=w("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),y=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,S=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,v=r==null?void 0:r.documentToolbarCopyMenuItems,M=!!(S&&v&&v.length>0),W=null,H,I=null,D=null;if(n&&(y||S)&&!M){if(H=y?ks({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):cr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),S){let K=fe("chevron-down",14,"currentColor",2);K&&H.appendChild(K)}}else n&&M?(W=w("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),H=y?ks({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):cr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I=cr({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),W.append(H,I)):n?H=cr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):H=cr({icon:"copy",label:"Copy"});let O=n?cr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):cr({icon:"refresh-cw",label:"Refresh"}),J=n?cr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):cr({icon:"x",label:"Close"}),me=()=>{var yt,Ot,Qt;let K=(yt=Ce.find(Ye=>Ye.id===se))!=null?yt:Ce[Ce.length-1],ce=(Ot=K==null?void 0:K.id)!=null?Ot:null,qe=(K==null?void 0:K.artifactType)==="markdown"&&(Qt=K.markdown)!=null?Qt:"",ot=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:qe,jsonPayload:ot,id:ce}},de=async()=>{var yt;let{markdown:K,jsonPayload:ce}=me(),qe=(yt=Ce.find(Ot=>Ot.id===se))!=null?yt:Ce[Ce.length-1],ot=(qe==null?void 0:qe.artifactType)==="markdown"?K:qe?ce:"";try{await navigator.clipboard.writeText(ot)}catch{}};if(H.addEventListener("click",async()=>{let K=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(K&&M){let{markdown:ce,jsonPayload:qe,id:ot}=me();try{await K({actionId:"primary",artifactId:ot,markdown:ce,jsonPayload:qe})}catch{}return}await de()}),I&&(v!=null&&v.length)){let K=()=>{var qe;return(qe=f.closest("[data-persona-root]"))!=null?qe:document.body},ce=()=>{D=Pn({items:v.map(qe=>({id:qe.id,label:qe.label})),onSelect:async qe=>{let{markdown:ot,jsonPayload:yt,id:Ot}=me(),Qt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{Qt?await Qt({actionId:qe,artifactId:Ot,markdown:ot,jsonPayload:yt}):qe==="markdown"||qe==="md"?await navigator.clipboard.writeText(ot):qe==="json"||qe==="source"?await navigator.clipboard.writeText(yt):await navigator.clipboard.writeText(ot||yt)}catch{}},anchor:W!=null?W:I,position:"bottom-right",portal:K()})};f.isConnected?ce():requestAnimationFrame(ce),I.addEventListener("click",qe=>{qe.stopPropagation(),D==null||D.toggle()})}O.addEventListener("click",async()=>{var K;try{await((K=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:K.call(r))}catch{}pe()}),J.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let te=()=>{n&&(E.setAttribute("aria-pressed",b==="rendered"?"true":"false"),A.setAttribute("aria-pressed",b==="source"?"true":"false"))};E.addEventListener("click",()=>{b="rendered",te(),pe()}),A.addEventListener("click",()=>{b="source",te(),pe()});let Ae=w("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");n?(u.replaceChildren(),L.append(E,A),W?T.append(W,O,J):T.append(H,O,J),u.append(L,Ae,T),te()):(u.appendChild(m),u.appendChild(x)),a&&(u.style.paddingLeft=a,u.style.paddingRight=a);let Ie=w("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),le=w("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(Ie.style.paddingLeft=a,Ie.style.paddingRight=a,le.style.padding=a),f.appendChild(u),f.appendChild(Ie),f.appendChild(le);let Ce=[],se=null,ie=!1,pe=()=>{var ot,yt,Ot,Qt;let K=n&&Ce.length<=1;Ie.classList.toggle("persona-hidden",K),Ie.replaceChildren();for(let Ye of Ce){let ge=w("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");ge.type="button",ge.textContent=Ye.title||Ye.id.slice(0,8),Ye.id===se&&ge.classList.add("persona-bg-persona-container","persona-border-persona-border"),ge.addEventListener("click",()=>t.onSelect(Ye.id)),Ie.appendChild(ge)}le.replaceChildren();let ce=se&&Ce.find(Ye=>Ye.id===se)||Ce[Ce.length-1];if(!ce)return;if(n){let Ye=ce.artifactType==="markdown"?"MD":(ot=ce.component)!=null?ot:"Component",X=(ce.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ae.textContent=`${X} \xB7 ${Ye}`}else m.textContent="Artifacts";if(ce.artifactType==="markdown"){if(n&&b==="source"){let ge=w("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ge.textContent=(yt=ce.markdown)!=null?yt:"",le.appendChild(ge);return}let Ye=w("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ye.innerHTML=c((Ot=ce.markdown)!=null?Ot:""),le.appendChild(Ye);return}let qe=ce.component?rn.get(ce.component):void 0;if(qe){let ge={message:{id:ce.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=qe((Qt=ce.props)!=null?Qt:{},ge);if(X){le.appendChild(X);return}}catch{}}le.appendChild(qv(ce))},Ee=()=>{var ce;let K=Ce.length>0;if(f.classList.toggle("persona-hidden",!K),l){let qe=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,yt=((ce=qe==null?void 0:qe.classList.contains("persona-artifact-narrow-host"))!=null?ce:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&yt&&ie?(l.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:l,update(K){var ce,qe,ot;Ce=K.artifacts,se=(ot=(qe=K.selectedId)!=null?qe:(ce=K.artifacts[K.artifacts.length-1])==null?void 0:ce.id)!=null?ot:null,Ce.length>0&&(ie=!0),pe(),Ee()},setMobileOpen(K){ie=K,!K&&l?(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):Ee()}}}function po(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"),!po(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 el(e,t){var c,l,p,f,u,m,x,b,L,E;if(!po(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),Jh(e,t);return}let r=(l=(c=t.features)==null?void 0:c.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(f=r==null?void 0:r.paneWidth)!=null?f:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(u=r==null?void 0:r.paneMaxWidth)!=null?u:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=r==null?void 0:r.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let n=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();n?e.style.setProperty("--persona-artifact-pane-padding",n):e.style.removeProperty("--persona-artifact-pane-padding");let a=(b=r==null?void 0:r.documentToolbarIconColor)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(L=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:L.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Jh(e,t)}var Qh=["panel","seamless"];function tl(e,t){var i,c,l,p,f,u;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"),!po(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(l=r==null?void 0:r.paneAppearance)!=null?l:"panel",n=Qh.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${n}`);let a=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(f=r==null?void 0:r.paneShadow)==null?void 0:f.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((u=r.unifiedSplitOuterRadius)==null?void 0:u.trim())||a;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Yh(e,t){var r,o,n;return!t||!po(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function zv(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 $v(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 jv(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function Gv(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function Zh(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 ex(e,t,r,o,n,a){let s=zv(n,200),i=Gv(t,r,o,200);i=Math.max(s,i);let c=$v(a);return c!==null&&(i=Math.min(i,c)),jv(e,s,i)}var tx={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"}},fp=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var x,b,L;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(b=tx[s])!=null?b:tx.init;a.classList.add("persona-form-card","persona-space-y-4");let c=w("div","persona-space-y-1"),l=w("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,c.appendChild(l),i.description){let E=w("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,c.appendChild(E)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var v,M;let A=w("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${E.name}`;let T=w("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=E.label,A.appendChild(T);let y=(v=E.type)!=null?v:"text",S;y==="textarea"?(S=document.createElement("textarea"),S.rows=3):(S=document.createElement("input"),S.type=y),S.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",S.id=`${t.id}-${s}-${E.name}`,S.name=E.name,S.placeholder=(M=E.placeholder)!=null?M:"",E.required&&(S.required=!0),A.appendChild(S),p.appendChild(A)});let f=w("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=w("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=w("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(L=i.submitLabel)!=null?L:"Submit",f.appendChild(u),f.appendChild(m),p.appendChild(f),a.replaceChildren(c,p),p.addEventListener("submit",async E=>{var S,v;E.preventDefault();let A=(S=r.formEndpoint)!=null?S:"/form",T=new FormData(p),y={};T.forEach((M,W)=>{y[W]=M}),y.type=s,m.disabled=!0,u.textContent="Submitting\u2026";try{let M=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let W=await M.json();u.textContent=(v=W.message)!=null?v:"Thanks! We'll be in touch soon.",W.success&&W.nextPrompt&&await o.sendMessage(String(W.nextPrompt))}catch(M){u.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var mp=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var o;let r=this.plugins.get(t);r&&((o=r.onUnregister)==null||o.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var o,n;return((o=r.priority)!=null?o:0)-((n=t.priority)!=null?n:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let o=new Set(t.map(a=>a.id));return[...r.filter(a=>!o.has(a.id)),...t].sort((a,s)=>{var i,c;return((i=s.priority)!=null?i:0)-((c=a.priority)!=null?c:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Is=new mp;var rx=()=>{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 Kv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Xv=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},Ws=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Kv(e),r=Xv(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}},gp=e=>typeof e=="string"?e:e==null?"":String(e),la={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:gp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=gp(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:gp(r.text)}}},ox=e=>Array.isArray(e)?e.map(t=>String(t)):[],Hs=e=>{let t=new Set(ox(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(ox(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),o();let c={action:i,message:a.message};e.emit("action:detected",c);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",c)},f=l(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var Jv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Qv=e=>e.map(t=>({...t,streaming:!1})),Yv=e=>e.map(t=>({...t,status:"complete"})),rl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Jv(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?Qv(r.messages):void 0,artifacts:r.artifacts?Yv(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=Sa(Ys(),1);function Zv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function e0(e,t){if(!Zv(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 ol(){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=e0(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function nx(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function nl(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=rn.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 ax(){let e=ol();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function sx(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 al(e){let t=sx(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 sl(e){let t=sx(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 t0=["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:l=t0}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,m.appendChild(x);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=n,m.appendChild(b),u.appendChild(m);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-csat",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let v=1;v<=5;v++){let M=document.createElement("button");M.type="button",M.className="persona-feedback-rating-btn persona-feedback-star-btn",M.setAttribute("role","radio"),M.setAttribute("aria-checked","false"),M.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),M.title=l[v-1],M.dataset.rating=String(v),M.innerHTML=`
28
+ `,r.addEventListener("click",t);let o=a=>{var T,y,S,v,M,W,H,I,F,O,Q,he,ce;let s=(T=a.launcher)!=null?T:{},i=nr(a),c=r.querySelector("[data-role='launcher-title']");if(c){let te=(y=s.title)!=null?y:"Chat Assistant";c.textContent=te,c.setAttribute("title",te)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let te=(S=s.subtitle)!=null?S:"Here to help you get answers fast";l.textContent=te,l.setAttribute("title",te)}let p=r.querySelector(".persona-flex-col");p&&(s.textHidden||i?p.style.display="none":p.style.display="");let f=r.querySelector("[data-role='launcher-icon']");if(f)if(s.agentIconHidden)f.style.display="none";else{let te=(v=s.agentIconSize)!=null?v:"40px";if(f.style.height=te,f.style.width=te,s.agentIconBackgroundColor?(f.style.backgroundColor=s.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",s.agentIconName){let Te=parseFloat(te)||24,We=ge(s.agentIconName,Te*.6,"var(--persona-text-inverse, #ffffff)",2);We?(f.appendChild(We),f.style.display=""):(f.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}",f.style.display="")}else s.iconUrl?f.style.display="none":(f.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}",f.style.display="")}let u=r.querySelector("[data-role='launcher-image']");if(u){let te=(H=s.agentIconSize)!=null?H:"40px";u.style.height=te,u.style.width=te,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(u.src=s.iconUrl,u.style.display="block"):u.style.display="none"}let g=r.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let te=(I=s.callToActionIconSize)!=null?I:"32px";g.style.height=te,g.style.width=te,s.callToActionIconBackgroundColor?(g.style.backgroundColor=s.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(g.style.color=s.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Te=0;if(s.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=s.callToActionIconPadding,Te=(parseFloat(s.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),s.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",s.callToActionIconName){let We=parseFloat(te)||24,de=Math.max(We-Te,8),Ae=ge(s.callToActionIconName,de,"currentColor",2);Ae?g.appendChild(Ae):g.textContent=(F=s.callToActionIconText)!=null?F:"\u2197"}else g.textContent=(O=s.callToActionIconText)!=null?O:"\u2197"}let x=s.position&&So[s.position]?So[s.position]:So["bottom-right"],b="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",L="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";r.className=i?L:`${b} ${x}`,i||(r.style.zIndex=String((Q=s.zIndex)!=null?Q:Cr));let E="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(he=s.border)!=null?he:E,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(ce=s.collapsedMaxWidth)!=null?ce:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},n=()=>{r.removeEventListener("click",t),r.remove()};return e&&o(e),{element:r,update:o,destroy:n}};var Vh=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=Uh(e),a=qh(e,t),s={wrapper:r,panel:o,pillRoot:n},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},l={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:c,composer:l,replaceHeader:u=>(c.element.replaceWith(u.header),c.element=u.header,c.iconHolder=u.iconHolder,c.headerTitle=u.headerTitle,c.headerSubtitle=u.headerSubtitle,c.closeButton=u.closeButton,c.closeButtonWrapper=u.closeButtonWrapper,c.clearChatButton=u.clearChatButton,c.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{l.footer.replaceWith(u),l.footer=u}}},lp=({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:()=>ip(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=ip(e,r);return{instance:n,element:n.element}};var uv=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}},fv=(e,t)=>{if(!e)return null;let r=uv(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},mv=(e,t)=>{let r=w("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},gv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},dp=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,zh=320,hv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),xv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),yv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),bv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),vv=(e,t,r)=>{if(e.length===0)return null;try{let o=w("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,c)=>{var f;let l=w("img");l.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${c+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${cp}px`,l.style.maxHeight=`${zh}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;n+=1,l.addEventListener("error",()=>{p||(p=!0,n=Math.max(0,n-1),l.remove(),n===0&&s())}),l.addEventListener("load",()=>{p=!0}),gv(i.image)?(l.src=i.image,o.appendChild(l)):(p=!0,n=Math.max(0,n-1),l.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},wv=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!dp(o.audio))return;let n=w("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}},Cv=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!dp(o.video))return;let n=w("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=`${zh}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}},Sv=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!dp(o.data))return;let n=w("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},pp=(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()},Av=(e,t)=>{let r=w("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=w("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},$h=(e,t,r="div")=>{let o=w(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},Mv=(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},up=(e,t,r)=>{var x,b,L,E,A,T,y;let o=(x=t.showCopy)!=null?x:!0,n=(b=t.showUpvote)!=null?b:!0,a=(L=t.showDownvote)!=null?L:!0,s=(E=t.showReadAloud)!=null?E:!1;if(!o&&!n&&!a&&!s){let S=w("div");return S.style.display="none",S.id=`actions-${e.id}`,S.setAttribute("data-actions-for",e.id),S}let i=(A=t.visibility)!=null?A:"hover",c=(T=t.align)!=null?T:"right",l=(y=t.layout)!=null?y:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[c],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[l],u=w("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let g=(S,v,M)=>{let W=pr({icon:S,label:v,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",M),W};return o&&u.appendChild(g("copy","Copy message","copy")),s&&u.appendChild(g("volume-2","Read aloud","read-aloud")),n&&u.appendChild(g("thumbs-up","Upvote","upvote")),a&&u.appendChild(g("thumbs-down","Downvote","downvote")),u},$a=(e,t,r,o,n,a)=>{var ne,le,ue,ke,Fe,j,J,Ne,K,pe,qe,ot,xt,Ft,Qt,Ye,xe;let s=r!=null?r:{},i=(ne=s.layout)!=null?ne:"bubble",c=s.avatar,l=s.timestamp,p=(le=c==null?void 0:c.show)!=null?le:!1,f=(ue=l==null?void 0:l.show)!=null?ue:!1,u=(ke=c==null?void 0:c.position)!=null?ke:"left",g=(Fe=l==null?void 0:l.position)!=null?Fe:"below",x=Mv(e.role,i),b=w("div",x.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=hv(e),E=(J=(j=e.content)==null?void 0:j.trim())!=null?J:"",T=L.length>0&&E===yi,y=Vi((K=(Ne=a==null?void 0:a.widgetConfig)==null?void 0:Ne.features)==null?void 0:K.streamAnimation),S=(ot=(qe=(pe=a==null?void 0:a.widgetConfig)==null?void 0:pe.features)==null?void 0:qe.streamAnimation)==null?void 0:ot.plugins,v=e.role==="assistant"&&y.type!=="none"?Rs(y.type,S):null,M=e.role==="assistant"&&((xt=v==null?void 0:v.isAnimating)==null?void 0:xt.call(v,e))===!0,W=e.role==="assistant"&&v!==null&&(!!e.streaming||M);W&&(v!=null&&v.bubbleClass)&&b.classList.add(v.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),e.streaming&&H.classList.add("persona-content-streaming"),W&&v&&(v.containerClass&&H.classList.add(v.containerClass),H.style.setProperty("--persona-stream-step",`${y.speed}ms`),H.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let I=W?$i((Ft=e.content)!=null?Ft:"",y.buffer,v,e,!!e.streaming):(Qt=e.content)!=null?Qt:"",F=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=F;W&&(v==null?void 0:v.wrap)==="char"?O=Is(F,"char",e.id,{skipTags:v.skipTags}):W&&(v==null?void 0:v.wrap)==="word"&&(O=Is(F,"word",e.id,{skipTags:v.skipTags}));let Q=null;if(T?(Q=document.createElement("div"),Q.innerHTML=O,Q.style.display="none",H.appendChild(Q)):H.innerHTML=O,W&&(v!=null&&v.useCaret)&&!T&&E){let X=zi(),dt=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),$e=dt[dt.length-1];if($e!=null&&$e.parentNode)$e.parentNode.insertBefore(X,$e.nextSibling);else{let Ce=H.lastElementChild;Ce?Ce.appendChild(X):H.appendChild(X)}}if(f&&g==="inline"&&e.createdAt){let X=$h(e,l,"span");X.classList.add("persona-timestamp-inline");let dt=H.lastElementChild;dt?dt.appendChild(X):H.appendChild(X)}if(L.length>0){let X=vv(L,!T&&!!E,()=>{T&&Q&&(Q.style.display="")});X?b.appendChild(X):T&&Q&&(Q.style.display="")}let he=xv(e);if(he.length>0){let X=wv(he);X&&b.appendChild(X)}let ce=yv(e);if(ce.length>0){let X=Cv(ce);X&&b.appendChild(X)}let te=bv(e);if(te.length>0){let X=Sv(te);X&&b.appendChild(X)}if(b.appendChild(H),f&&g==="below"&&e.createdAt){let X=$h(e,l);X.classList.add("persona-mt-1"),b.appendChild(X)}let Te=e.role==="assistant"?fv(e.stopReason,(xe=(Ye=a==null?void 0:a.widgetConfig)==null?void 0:Ye.copy)==null?void 0:xe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(I&&I.trim()),dt=y.placeholder==="skeleton",$e=dt&&y.buffer==="line"&&X;if(X)$e&&b.appendChild(Ws());else if(dt)b.appendChild(Ws());else{let Ce=pp("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Ce&&b.appendChild(Ce)}}if(Te&&e.stopReason&&!e.streaming&&(E||(H.style.display="none"),b.appendChild(mv(e.stopReason,Te))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let X=up(e,o,n);b.appendChild(X)}if(!p||e.role==="system")return b;let de=w("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ae=Av(c,e.role);return u==="right"||u==="left"&&e.role==="user"?de.append(b,Ae):de.append(Ae,b),b.classList.remove("persona-max-w-[85%]"),b.classList.add("persona-max-w-[calc(85%-2.5rem)]"),de},jh=(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}):$a(e,t,r,o,n,a)};var za=new Set,Tv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Ev=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
29
+ `):""},Gh=(e,t)=>{let r=za.has(e),o=t.querySelector('button[data-expand-header="true"]'),n=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!n)return;o.setAttribute("aria-expanded",r?"true":"false");let s=o.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=ge(r?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=r?"Hide":"Show"}n.style.display=r?"":"none",a&&(a.style.display=r?"none":a.textContent||a.childNodes.length?"":"none")},fp=(e,t)=>{var ce,te,Te,We,de,Ae,ne,le,ue,ke,Fe;let r=e.reasoning,o=w("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=(te=(ce=t==null?void 0:t.features)==null?void 0:ce.reasoningDisplay)!=null?te:{},a=n.expandable!==!1,s=a&&za.has(e.id),i=r.status!=="complete",c=Ev(e,(Te=n.previewMaxLines)!=null?Te:3),l=w("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",a&&(l.setAttribute("aria-expanded",s?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=w("div","persona-flex persona-flex-col persona-text-left"),f=w("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",g=(We=t==null?void 0:t.reasoning)!=null?We:{},x=String((de=r.startedAt)!=null?de:Date.now()),b=()=>{let j=w("span","");return j.setAttribute("data-tool-elapsed",x),j.textContent=pi(r),j},L=(Ae=g.renderCollapsedSummary)==null?void 0:Ae.call(g,{message:e,reasoning:r,defaultSummary:u,previewText:c,isActive:i,config:t!=null?t:{},elapsed:pi(r),createElapsedElement:b});typeof L=="string"&&L.trim()?(f.textContent=L,p.appendChild(f)):L instanceof HTMLElement?p.appendChild(L):(f.textContent=u,p.appendChild(f));let E=w("span","persona-text-xs persona-text-persona-primary");E.textContent=Qg(r),p.appendChild(E);let A=(ne=n.loadingAnimation)!=null?ne:"none",T=g.activeTextTemplate,y=g.completeTextTemplate,S=i?T:y,v=L instanceof HTMLElement,M=(j,J,Ne)=>{let K=Ne;for(let pe of J){let qe=w("span","persona-tool-char");qe.style.setProperty("--char-index",String(K)),qe.textContent=pe===" "?"\xA0":pe,j.appendChild(qe),K++}return K},W=(j,J)=>{f.textContent="";let Ne=ui(j,""),K=0;for(let pe of Ne){let qe=pe.styles.length>0?(()=>{let ot=w("span",pe.styles.map(xt=>`persona-tool-text-${xt}`).join(" "));return f.appendChild(ot),ot})():f;if(pe.isDuration&&i)qe.appendChild(b());else{let ot=pe.isDuration?pi(r):pe.text;J?K=M(qe,ot,K):qe.appendChild(document.createTextNode(ot))}}};if(!v&&S)if(E.style.display="none",f.style.display="",i&&A!=="none"){let j=(le=g.loadingAnimationDuration)!=null?le:2e3;f.setAttribute("data-preserve-animation","true"),A==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`),W(S,!1)):(f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`),A==="shimmer-color"&&(g.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),W(S,!0))}else W(S,!1);else if(!v&&i&&A!=="none"){f.style.display="";let j=(ue=g.loadingAnimationDuration)!=null?ue:2e3;if(f.setAttribute("data-preserve-animation","true"),A==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`);else{f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`),A==="shimmer-color"&&(g.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let J=f.textContent||u;f.textContent="",M(f,J,0)}r.status==="complete"&&(f.style.display="none")}else v||(r.status==="complete"?f.style.display="none":f.style.display="");let H=null;if(a){H=w("div","persona-flex persona-items-center");let J=ge(s?"chevron-up":"chevron-down",16,"currentColor",2);J?H.appendChild(J):H.textContent=s?"Hide":"Show";let Ne=w("div","persona-flex persona-items-center persona-ml-auto");Ne.append(H),l.append(p,Ne)}else l.append(p);let I=w("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(I.setAttribute("data-persona-collapsed-preview","reasoning"),I.style.display="none",I.style.whiteSpace="pre-wrap",!s&&i&&n.activePreview&&c){let j=(Fe=(ke=t==null?void 0:t.reasoning)==null?void 0:ke.renderCollapsedPreview)==null?void 0:Fe.call(ke,{message:e,reasoning:r,defaultPreview:c,isActive:i,config:t!=null?t:{}});Tv(I,j)||(I.textContent=c),I.style.display=""}if(!s&&i&&n.activeMinHeight&&(o.style.minHeight=n.activeMinHeight),!a)return o.append(l,I),o;let F=w("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");F.style.display=s?"":"none";let O=r.chunks.join(""),Q=w("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Q.textContent=O||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(Q),(()=>{if(l.setAttribute("aria-expanded",s?"true":"false"),H){H.innerHTML="";let J=ge(s?"chevron-up":"chevron-down",16,"currentColor",2);J?H.appendChild(J):H.textContent=s?"Hide":"Show"}F.style.display=s?"":"none",I.style.display=s?"none":I.textContent||I.childNodes.length?"":"none"})(),o.append(l,I,F),o};var ja=new Set,kv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Lv=(e,t)=>{var a;let r=e.toolCall;if(!r)return"";let o=((a=r.chunks)!=null?a:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
30
+ `);let n=Rn(r.args).trim();return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
31
+ `):""},mp=(e,t)=>{var r,o,n;e.style.backgroundColor=(r=t.codeBlockBackgroundColor)!=null?r:"var(--persona-container, #f3f4f6)",e.style.borderColor=(o=t.codeBlockBorderColor)!=null?o:"var(--persona-border, #e5e7eb)",e.style.color=(n=t.codeBlockTextColor)!=null?n:"var(--persona-text, #171717)"},Pv=(e,t)=>{var p,f,u,g,x;let r=e.toolCall,o=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,n=(f=o==null?void 0:o.collapsedMode)!=null?f:"tool-call",a=Lv(e,(u=o==null?void 0:o.previewMaxLines)!=null?u:3),s=r?Jg(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i=r.status!=="complete",c=(g=t==null?void 0:t.toolCall)!=null?g:{},l=s;return n==="tool-name"?l=((x=r.name)==null?void 0:x.trim())||s:n==="tool-preview"&&a&&(l=a),i&&c.activeTextTemplate?l=jl(r,c.activeTextTemplate,l):!i&&c.completeTextTemplate&&(l=jl(r,c.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},Kh=(e,t,r)=>{var p;let o=ja.has(e),n=(p=r==null?void 0:r.toolCall)!=null?p:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto"),l=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let f=n.toggleTextColor||n.headerTextColor||"var(--persona-primary, #171717)",u=ge(o?"chevron-up":"chevron-down",16,f,2);u?l.appendChild(u):l.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},gp=(e,t)=>{var O,Q,he,ce,te,Te,We,de,Ae;let r=e.toolCall,o=(O=t==null?void 0:t.toolCall)!=null?O:{},n=w("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),o.backgroundColor&&(n.style.backgroundColor=o.backgroundColor),o.borderColor&&(n.style.borderColor=o.borderColor),o.borderWidth&&(n.style.borderWidth=o.borderWidth),o.borderRadius&&(n.style.borderRadius=o.borderRadius),n.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return n;let a=(he=(Q=t==null?void 0:t.features)==null?void 0:Q.toolCallDisplay)!=null?he:{},s=a.expandable!==!1,i=s&&ja.has(e.id),{summary:c,previewText:l,isActive:p}=Pv(e,t),f=w("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",s&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let u=w("div","persona-flex persona-flex-col persona-text-left"),g=w("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let x=String((ce=r.startedAt)!=null?ce:Date.now()),b=()=>{let ne=w("span","");return ne.setAttribute("data-tool-elapsed",x),ne.textContent=ws(r),ne},L=(Te=o.renderCollapsedSummary)==null?void 0:Te.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:l,collapsedMode:(te=a.collapsedMode)!=null?te:"tool-call",isActive:p,config:t!=null?t:{},elapsed:ws(r),createElapsedElement:b});typeof L=="string"&&L.trim()?(g.textContent=L,u.appendChild(g)):L instanceof HTMLElement?u.appendChild(L):(g.textContent=c,u.appendChild(g));let E=(We=a.loadingAnimation)!=null?We:"none",A=o.activeTextTemplate,T=o.completeTextTemplate,y=p?A:T,S=L instanceof HTMLElement,v=(ne,le,ue)=>{let ke=ue;for(let Fe of le){let j=w("span","persona-tool-char");j.style.setProperty("--char-index",String(ke)),j.textContent=Fe===" "?"\xA0":Fe,ne.appendChild(j),ke++}return ke},M=(ne,le)=>{var j;g.textContent="";let ue=((j=r.name)==null?void 0:j.trim())||"tool",ke=ui(ne,ue),Fe=0;for(let J of ke){let Ne=J.styles.length>0?(()=>{let K=w("span",J.styles.map(pe=>`persona-tool-text-${pe}`).join(" "));return g.appendChild(K),K})():g;if(J.isDuration&&p)Ne.appendChild(b());else{let K=J.isDuration?ws(r):J.text;le?Fe=v(Ne,K,Fe):Ne.appendChild(document.createTextNode(K))}}};if(!S)if(p&&E!=="none"){let ne=(de=o.loadingAnimationDuration)!=null?de:2e3;if(g.setAttribute("data-preserve-animation","true"),E==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),y&&M(y,!1);else if(g.classList.add(`persona-tool-loading-${E}`),g.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),E==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),y)M(y,!0);else{let le=g.textContent||c;g.textContent="",v(g,le,0)}}else y&&M(y,!1);let W=null;if(s){W=w("div","persona-flex persona-items-center");let ne=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",le=ge(i?"chevron-up":"chevron-down",16,ne,2);le?W.appendChild(le):W.textContent=i?"Hide":"Show";let ue=w("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ue.append(W),f.append(u,ue)}else f.append(u);let H=w("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","tool"),H.style.display="none",H.style.whiteSpace="pre-wrap",!i&&p&&a.activePreview&&l){let ne=(Ae=o.renderCollapsedPreview)==null?void 0:Ae.call(o,{message:e,toolCall:r,defaultPreview:l,isActive:p,config:t!=null?t:{}});kv(H,ne)||(H.textContent=l),H.style.display=""}if(!i&&p&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(f,H),n;let I=w("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(I.style.display=i?"":"none",o.contentBackgroundColor&&(I.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(I.style.color=o.contentTextColor),o.contentPaddingX&&(I.style.paddingLeft=o.contentPaddingX,I.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(I.style.paddingTop=o.contentPaddingY,I.style.paddingBottom=o.contentPaddingY),r.name){let ne=w("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?ne.style.color=o.contentTextColor:o.headerTextColor&&(ne.style.color=o.headerTextColor),ne.textContent=r.name,I.appendChild(ne)}if(r.args!==void 0){let ne=w("div","persona-space-y-1"),le=w("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(le.style.color=o.labelTextColor),le.textContent="Arguments";let ue=w("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ue.style.fontSize="0.75rem",ue.style.lineHeight="1rem",mp(ue,o),ue.textContent=Rn(r.args),ne.append(le,ue),I.appendChild(ne)}if(r.chunks&&r.chunks.length){let ne=w("div","persona-space-y-1"),le=w("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(le.style.color=o.labelTextColor),le.textContent="Activity";let ue=w("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ue.style.fontSize="0.75rem",ue.style.lineHeight="1rem",mp(ue,o),ue.textContent=r.chunks.join(""),ne.append(le,ue),I.appendChild(ne)}if(r.status==="complete"&&r.result!==void 0){let ne=w("div","persona-space-y-1"),le=w("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(le.style.color=o.labelTextColor),le.textContent="Result";let ue=w("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ue.style.fontSize="0.75rem",ue.style.lineHeight="1rem",mp(ue,o),ue.textContent=Rn(r.result),ne.append(le,ue),I.appendChild(ne)}if(r.status==="complete"&&typeof r.duration=="number"){let ne=w("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(ne.style.color=o.contentTextColor),ne.textContent=`Duration: ${r.duration}ms`,I.appendChild(ne)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let ne=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",le=ge(i?"chevron-up":"chevron-down",16,ne,2);le?W.appendChild(le):W.textContent=i?"Hide":"Show"}I.style.display=i?"":"none",H.style.display=i?"none":H.textContent||H.childNodes.length?"":"none"})(),n.append(f,H,I),n};var fa=new Map,rl=e=>{let r=(e.startsWith(wo)?e.slice(wo.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)},Xh=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Qh=(e,t)=>{var o,n,a;let r=(n=(o=Xh(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=fa.get(e))!=null?a:r==="expanded"},Jh=(e,t,r)=>{var s,i;let o=Xh(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=ge(t?"chevron-up":"chevron-down",14,"currentColor",2);c&&a.appendChild(c)}},Yh=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=Qh(e,r);Jh(o,a,r),n.style.display=a?"":"none"};var ol=(e,t)=>{var M,W,H,I,F,O,Q,he,ce,te,Te,We,de,Ae,ne;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=w("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=w("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=w("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let c=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",l=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(H=o==null?void 0:o.titleColor)!=null?H:"currentColor",p=ge(c,20,l,2);p&&i.appendChild(p);let f=w("div","persona-flex-1 persona-min-w-0"),u=w("div","persona-flex persona-items-center persona-gap-2"),g=w("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(g.style.color=o.titleColor),g.textContent=(I=o==null?void 0:o.title)!=null?I:"Approval Required",u.appendChild(g),!n){let le=w("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");le.setAttribute("data-approval-status",r.status),r.status==="approved"?(le.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",le.style.color="var(--persona-palette-colors-success-700, #15803d)",le.textContent="Approved"):r.status==="denied"?(le.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",le.style.color="var(--persona-palette-colors-error-700, #b91c1c)",le.textContent="Denied"):r.status==="timeout"&&(le.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",le.style.color="var(--persona-palette-colors-warning-700, #b45309)",le.textContent="Timeout"),u.appendChild(le)}f.appendChild(u);let b=r.toolType==="webmcp"||r.toolName.startsWith(wo)?fs(r.toolName):void 0,L=(F=o==null?void 0:o.formatDescription)==null?void 0:F.call(o,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...b?{displayTitle:b}:{},...r.reason?{reason:r.reason}:{}}),E=!r.toolName,A=L||(E?r.description:`The assistant wants to use \u201C${b!=null?b:rl(r.toolName)}\u201D.`),T=w("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=A,f.appendChild(T),r.reason){let le=w("p","persona-text-sm persona-mt-1 persona-text-persona-muted");le.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?le.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(le.style.color=o.descriptionColor);let ue=w("span","persona-font-medium");ue.textContent=`${(O=o==null?void 0:o.reasonLabel)!=null?O:"Agent's stated reason:"} `,le.appendChild(ue),le.appendChild(document.createTextNode(r.reason)),f.appendChild(le)}let y=(Q=o==null?void 0:o.detailsDisplay)!=null?Q:"collapsed",S=!!r.description&&!E,v=S||!!r.parameters;if(y!=="hidden"&&v){let le=Qh(e.id,t),ue=w("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ue.type="button",ue.setAttribute("data-expand-header","true"),ue.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(ue.style.color=o.descriptionColor);let ke=w("span");ke.setAttribute("data-approval-details-label","true");let Fe=w("span","persona-inline-flex persona-items-center");Fe.setAttribute("data-approval-details-chevron","true"),ue.append(ke,Fe),Jh(ue,le,t),f.appendChild(ue);let j=w("div");if(j.setAttribute("data-approval-details","true"),j.style.display=le?"":"none",S){let J=w("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(J.style.color=o.descriptionColor),J.textContent=r.description,j.appendChild(J)}if(r.parameters){let J=w("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(J.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(J.style.color=o.parameterTextColor),J.style.fontSize="0.75rem",J.style.lineHeight="1rem",J.textContent=Rn(r.parameters),j.appendChild(J)}f.appendChild(j)}if(n){let le=w("div","persona-flex persona-gap-2 persona-mt-2");le.setAttribute("data-approval-buttons","true");let ue=w("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ue.type="button",ue.style.backgroundColor=(he=o==null?void 0:o.approveButtonColor)!=null?he:"var(--persona-approval-approve-bg, #22c55e)",ue.style.color=(ce=o==null?void 0:o.approveButtonTextColor)!=null?ce:"#ffffff",ue.setAttribute("data-approval-action","approve");let ke=ge("shield-check",14,(te=o==null?void 0:o.approveButtonTextColor)!=null?te:"#ffffff",2);ke&&(ke.style.marginRight="4px",ue.appendChild(ke));let Fe=document.createTextNode((Te=o==null?void 0:o.approveLabel)!=null?Te:"Approve");ue.appendChild(Fe);let j=w("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=(We=o==null?void 0:o.denyButtonColor)!=null?We:"transparent",j.style.color=(de=o==null?void 0:o.denyButtonTextColor)!=null?de:"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 J=ge("shield-x",14,(Ae=o==null?void 0:o.denyButtonTextColor)!=null?Ae:"var(--persona-feedback-error, #dc2626)",2);J&&(J.style.marginRight="4px",j.appendChild(J));let Ne=document.createTextNode((ne=o==null?void 0:o.denyLabel)!=null?ne:"Deny");j.appendChild(Ne),le.append(ue,j),f.appendChild(le)}return s.append(i,f),a.appendChild(s),a};function Rv(e){var r,o;let t=(r=e.getRootNode)==null?void 0:r.call(e);return t instanceof ShadowRoot?t:((o=e.ownerDocument)!=null?o:document).body}function Zh(e){var b;let{anchor:t,content:r,placement:o="bottom-start",offset:n=6,matchAnchorWidth:a=!1,zIndex:s=2147483e3,onOpen:i,onDismiss:c}=e,l=(b=e.container)!=null?b:Rv(t),p=!1,f=null,u=()=>{if(!p)return;let L=t.getBoundingClientRect();r.style.position="fixed",a&&(r.style.minWidth=`${L.width}px`);let E=o==="top-start"||o==="top-end"?L.top-n-r.getBoundingClientRect().height:L.bottom+n,A=o==="bottom-end"||o==="top-end"?L.right-r.getBoundingClientRect().width:L.left;r.style.top=`${E}px`,r.style.left=`${A}px`},g=()=>{p&&(p=!1,f&&(f(),f=null),r.remove())},x=()=>{var S,v,M;if(p)return;p=!0,s!=null&&(r.style.zIndex=String(s)),l.appendChild(r),u();let L=(v=((S=t.ownerDocument)!=null?S:document).defaultView)!=null?v:window,E=(M=t.ownerDocument)!=null?M:document,A=()=>{if(!t.isConnected){g(),c==null||c("anchor-removed");return}u()},T=W=>{let H=typeof W.composedPath=="function"?W.composedPath():[];H.includes(r)||H.includes(t)||(g(),c==null||c("outside"))},y=L.setTimeout(()=>{E.addEventListener("pointerdown",T,!0)},0);L.addEventListener("scroll",A,!0),L.addEventListener("resize",A),f=()=>{L.clearTimeout(y),E.removeEventListener("pointerdown",T,!0),L.removeEventListener("scroll",A,!0),L.removeEventListener("resize",A)},i==null||i()};return{get isOpen(){return p},open:x,close:g,toggle:()=>p?g():x(),reposition:u,destroy:g}}function ex(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(r=>r instanceof HTMLElement&&(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable))}var Iv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),tx=(e,t)=>{let r=e.keyHandlers.get(t);r&&(document.removeEventListener("keydown",r),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},ma=(e,t)=>{tx(e,t);let r=e.pendingOrder.indexOf(t);r!==-1&&e.pendingOrder.splice(r,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Wv=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Hv=(e,t)=>{var o,n;let r=(o=t==null?void 0:t.detailsDisplay)!=null?o:"collapsed";return(n=fa.get(e))!=null?n:r==="expanded"},hp=e=>{let t=w("span","persona-approval-kbd");return t.textContent=e,t},Bv=(e,t)=>{var l,p;let r=w("span","persona-approval-title");t!=null&&t.titleColor&&(r.style.color=t.titleColor);let n=e.toolType==="webmcp"||e.toolName.startsWith(wo)?fs(e.toolName):void 0,a=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(l=e.description)!=null?l:"",parameters:e.parameters,...n?{displayTitle:n}:{},...e.reason?{reason:e.reason}:{}});if(a)return r.textContent=a,r;let s=n!=null?n:rl(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;r.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=s,r.appendChild(c),i){r.append(" from ");let f=document.createElement("strong");f.textContent=i,r.appendChild(f)}return r},Dv=e=>{let t=w("div","persona-approval-resolved"),r=ge("ban",15,"currentColor",2);r&&t.appendChild(r);let o=w("span","persona-approval-resolved-name");return o.textContent=e.toolName?rl(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Fv=(e,t,r,o,n,a,s)=>{var W,H,I,F,O,Q,he;let i=w("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o!=null&&o.backgroundColor&&(i.style.background=o.backgroundColor),o!=null&&o.borderColor&&(i.style.borderColor=o.borderColor),(o==null?void 0:o.shadow)!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let c=(W=o==null?void 0:o.detailsDisplay)!=null?W:"collapsed",l=!!r.description&&c!=="hidden",p=r.parameters!=null&&c!=="hidden",f=l||p,u=f&&Hv(t.id,o),g=(H=o==null?void 0:o.showDetailsLabel)!=null?H:"Show details",x=(I=o==null?void 0:o.hideDetailsLabel)!=null?I:"Hide details",b=w("button","persona-approval-head");b.type="button",f?(b.setAttribute("data-action","toggle-params"),b.setAttribute("aria-expanded",u?"true":"false"),b.setAttribute("aria-label",u?x:g)):b.setAttribute("data-static","true");let L=w("span","persona-approval-logo"),E=ge("shield-check",16,"currentColor",2);E&&L.appendChild(E),b.appendChild(L);let A=Bv(r,o);if(f){let ce=w("span","persona-approval-toggle");ce.setAttribute("aria-hidden","true");let te=ge("chevron-down",14,"currentColor",2);te&&ce.appendChild(te),A.append(" "),A.appendChild(ce)}b.appendChild(A),i.appendChild(b);let T=w("div","persona-approval-body");if(f){let ce=w("div","persona-approval-details");if(ce.setAttribute("data-role","params"),ce.hidden=!u,l){let te=w("p","persona-approval-desc");o!=null&&o.descriptionColor&&(te.style.color=o.descriptionColor),te.textContent=r.description,ce.appendChild(te)}if(p){let te=w("pre","persona-approval-params");o!=null&&o.parameterBackgroundColor&&(te.style.background=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(te.style.color=o.parameterTextColor),te.textContent=Rn(r.parameters),ce.appendChild(te)}T.appendChild(ce)}if(r.reason){let ce=w("p","persona-approval-reason");o!=null&&o.reasonColor?ce.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(ce.style.color=o.descriptionColor);let te=w("span","persona-approval-reason-label");te.textContent=`${(F=o==null?void 0:o.reasonLabel)!=null?F:"Agent's stated reason:"} `,ce.append(te,document.createTextNode(r.reason)),T.appendChild(ce)}let y=w("div","persona-approval-actions"),S=null,v=ce=>{o!=null&&o.approveButtonColor&&(ce.style.background=o.approveButtonColor),o!=null&&o.approveButtonTextColor&&(ce.style.color=o.approveButtonTextColor)},M=w("button","persona-approval-deny");if(M.type="button",M.setAttribute("data-action","deny"),o!=null&&o.denyButtonColor&&(M.style.background=o.denyButtonColor),o!=null&&o.denyButtonTextColor&&(M.style.color=o.denyButtonTextColor),M.append((O=o==null?void 0:o.denyLabel)!=null?O:"Deny"),s){let ce=w("div","persona-approval-split"),te=w("button","persona-approval-primary");te.type="button",te.setAttribute("data-action","always"),v(te),te.append((Q=o==null?void 0:o.approveLabel)!=null?Q:"Always allow",hp("\u23CE"));let Te=w("button","persona-approval-caret");Te.type="button",Te.setAttribute("data-action","toggle-menu"),Te.setAttribute("aria-label","More options"),v(Te);let We=ge("chevron-down",15,"currentColor",2);We&&Te.appendChild(We),ce.append(te,Te),y.append(ce,M),M.append(hp("Esc"));let de=w("div","persona-approval-menu"),Ae=w("button","persona-approval-menu-item");Ae.type="button",Ae.append("Allow once",hp("\u2318\u23CE")),de.appendChild(Ae),S=Zh({anchor:ce,content:de,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,S),Ae.addEventListener("click",()=>{ma(e,t.id),n()})}else{let ce=w("button","persona-approval-primary persona-approval-primary--solo");ce.type="button",ce.setAttribute("data-action","allow"),v(ce),ce.append((he=o==null?void 0:o.approveLabel)!=null?he:"Allow"),y.append(ce,M)}return T.appendChild(y),i.appendChild(T),i.addEventListener("click",ce=>{let te=ce.target instanceof Element?ce.target.closest("[data-action]"):null;if(!te)return;let Te=te.getAttribute("data-action");if(Te==="toggle-params"){let We=i.querySelector('[data-role="params"]');if(We){let de=We.hidden;We.hidden=!de,b.setAttribute("aria-expanded",de?"true":"false"),b.setAttribute("aria-label",de?x:g),fa.set(t.id,de)}return}if(Te==="toggle-menu"){S==null||S.toggle();return}if(Te==="always"){ma(e,t.id),n({remember:!0});return}if(Te==="allow"){ma(e,t.id),n();return}if(Te==="deny"){ma(e,t.id),a();return}}),i},rx=()=>{let e=Iv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:n,deny:a,config:s})=>{let i=o==null?void 0:o.approval;if(!i)return null;let c=Wv(s);if(i.status!=="pending"){if(ma(e,o.id),i.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return Dv(i)}tx(e,o.id);let l=(c==null?void 0:c.enableAlwaysAllow)===!0,p=Fv(e,o,i,c,n,a,l);if(l){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let f=u=>{ex(u)||o.id===e.latestPendingApprovalId&&(u.key!=="Escape"&&u.key!=="Enter"||(u.preventDefault(),u.stopImmediatePropagation(),ma(e,o.id),u.key==="Escape"?a():u.metaKey||u.ctrlKey?n():n({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return p}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])ma(e,o);e.latestPendingApprovalId=null}}};var ox=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(r=null),!n||!n.length||!p&&(i!=null?i:a?a.getMessages():[]).some(L=>L.role==="user"))return;let f=document.createDocumentFragment(),u=a?a.isStreaming():!1,g=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(n.forEach(x=>{let b=w("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");b.type="button",b.textContent=x,b.disabled=u,c!=null&&c.fontFamily&&(b.style.fontFamily=g(c.fontFamily)),c!=null&&c.fontWeight&&(b.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(b.style.paddingLeft=c.paddingX,b.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(b.style.paddingTop=c.paddingY,b.style.paddingBottom=c.paddingY),b.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),a.sendMessage(x))}),f.appendChild(b),t.push(b)}),e.appendChild(f),p){let x=JSON.stringify(n);x!==r&&(r=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var Fs=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 Ns=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 Nv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ov=new Set(["step_start","execution_start"]),_v=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Uv=new Set(["step_complete","agent_turn_complete"]),qv=new Set(["flow_complete","agent_complete"]),nx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),sx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Kr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ga=(e,t)=>{let r=e[t];return sx(r)?r:void 0};function xp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function nl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Vv(e,t){return typeof t.type=="string"?t.type:e}function $v(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 zv(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 ax(e){var o,n,a,s,i;let t=ga(e,"result"),r=[ga(e,"tokens"),ga(e,"totalTokens"),t?ga(t,"tokens"):void 0,ga(e,"usage"),t?ga(t,"usage"):void 0];for(let c of r){if(!c)continue;let l=(n=(o=Kr(c.output))!=null?o:Kr(c.outputTokens))!=null?n:Kr(c.completionTokens);if(l!==void 0)return l}return(i=(a=Kr(e.outputTokens))!=null?a:Kr(e.completionTokens))!=null?i:t?(s=Kr(t.outputTokens))!=null?s:Kr(t.completionTokens):void 0}function jv(e){var r,o,n,a,s;let t=ga(e,"result");return(s=(n=(o=(r=Kr(e.executionTime))!=null?r:Kr(e.executionTimeMs))!=null?o:Kr(e.execution_time))!=null?n:Kr(e.duration))!=null?s:t?(a=Kr(t.executionTime))!=null?a:Kr(t.executionTimeMs):void 0}function Gv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Os=class{constructor(t=Gv){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:nl(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(!sx(r)){nx.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Vv(t,r),n=this.now();if(Nv.has(o)){this.startRun(n);return}if(Ov.has(o)){this.run||this.startRun(n);return}if(_v.has(o)){if(!zv(o,r))return;let s=$v(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+xp(i.visibleCharCount),l=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:nl(c,l),outputTokens:c,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Uv.has(o)){if(!this.run)return;let s=this.run,i=ax(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,l=s.exactOutputTokens+xp(s.visibleCharCount),p=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:nl(l,p),outputTokens:l,durationMs:p,source:c?"usage":"estimate"};return}if(qv.has(o)){if(!this.run)return;let s=this.run,i=ax(r),c=i!=null?i:s.exactOutputTokens+xp(s.visibleCharCount),l=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:nl(c,p),outputTokens:c,durationMs:p,source:l},this.run=null;return}if(nx.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=jv(r);return a!=null?a:o-t.startedAt}};function Ga(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var Kv={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)"}},Xv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Qv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Jv=100;function Yv(e,t){let r={...Kv,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return Xv}function Zv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function e0(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 t0(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 r0(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 o0(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 n0(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function a0(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 s0(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=w("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=w("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 yp(e,t,r,o,n,a,s,i){var u;let c=n.has(e.id),l=w("div","persona-border-b persona-border-persona-divider persona-text-xs");Ga(l,(u=o.classNames)==null?void 0:u.eventRow);let p=s.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>f(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(f()),l;function f(){var O,Q;let g=w("div",""),x=w("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let b=w("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),L=ge(c?"chevron-down":"chevron-right","14px","currentColor",2);L&&b.appendChild(L);let E=w("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(O=o.timestampFormat)!=null?O:"relative";E.textContent=A==="relative"?Zv(e.timestamp,r):e0(e.timestamp);let T=null;o.showSequenceNumbers!==!1&&(T=w("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(t+1));let y=Yv(e.type,o.badgeColors),S=w("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");S.style.backgroundColor=y.bg,S.style.color=y.text,S.style.borderColor=y.text+"50",S.textContent=e.type;let v=(Q=o.descriptionFields)!=null?Q:Qv,M=t0(e.payload,v),W=null;M&&(W=w("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=M);let H=w("div","persona-flex-1 persona-min-w-0"),I=w("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"),F=ge("clipboard","12px","currentColor",1.5);return F&&I.appendChild(F),I.addEventListener("click",async he=>{he.stopPropagation(),await r0(o0(e)),I.innerHTML="";let ce=ge("check","12px","currentColor",1.5);ce&&I.appendChild(ce),setTimeout(()=>{I.innerHTML="";let te=ge("clipboard","12px","currentColor",1.5);te&&I.appendChild(te)},1500)}),x.appendChild(b),x.appendChild(E),T&&x.appendChild(T),x.appendChild(S),W&&x.appendChild(W),x.appendChild(H),x.appendChild(I),g.appendChild(x),c&&g.appendChild(s0(e,s,i)),g}}function ix(e){var x,b,L,E,A;let{buffer:t,getFullHistory:r,onClose:o,config:n,plugins:a=[],getThroughput:s}=e,i=(x=n==null?void 0:n.features)==null?void 0:x.scrollToBottom,c=(i==null?void 0:i.enabled)!==!1,l=(b=i==null?void 0:i.iconName)!=null?b:"arrow-down",p=(L=i==null?void 0:i.label)!=null?L:"",f=(A=(E=n==null?void 0:n.features)==null?void 0:E.eventStream)!=null?A:{},u=a.find(T=>T.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&n){let T=u.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(T)return{element:T,update:()=>{},destroy:()=>{}}}return g();function g(){let T=f.classNames,y=w("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ga(y,T==null?void 0:T.panel);let S=[],v="",M="",W=null,H=[],I={},F=0,O=_i(),Q=0,he=0,ce=!1,te=null,Te=!1,We=0,de=new Set,Ae=new Map,ne="",le="",ue=null,ke,Fe,j,J,Ne=null,K=null,pe=null;function qe(){let se=w("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),N=w("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");if(Ga(N,T==null?void 0:T.headerBar),s){K=w("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),K.style.cursor="help",Ne=w("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",pe=w("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"),pe.style.display="none",pe.style.pointerEvents="none";let Ot=K,tr=pe,To=()=>{if(!tr.textContent)return;let lo=Ot.getBoundingClientRect(),co=se.getBoundingClientRect();tr.style.left=`${lo.left-co.left}px`,tr.style.top=`${lo.bottom-co.top+4}px`,tr.style.display="block"},zo=()=>{tr.style.display="none"};K.addEventListener("mouseenter",To),K.addEventListener("mouseleave",zo),K.appendChild(Ne)}let ye=w("div","persona-flex-1");ke=w("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 Oe=w("option","");Oe.value="",Oe.textContent="All events (0)",ke.appendChild(Oe),Fe=w("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"),Fe.type="button",Fe.title="Copy All";let Qe=ge("clipboard-copy","12px","currentColor",1.5);Qe&&Fe.appendChild(Qe);let Wt=w("span","persona-event-copy-all persona-text-xs");Wt.textContent="Copy All",Fe.appendChild(Wt),K&&N.appendChild(K),N.appendChild(ye),N.appendChild(ke),N.appendChild(Fe);let At=w("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ga(At,T==null?void 0:T.searchBar);let gt=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),kt=w("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");gt&&kt.appendChild(gt),j=w("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"),Ga(j,T==null?void 0:T.searchInput),j.type="text",j.placeholder="Search event payloads...",J=w("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"),J.type="button",J.style.display="none";let Xt=ge("x","12px","currentColor",2);return Xt&&J.appendChild(Xt),At.appendChild(kt),At.appendChild(j),At.appendChild(J),se.appendChild(N),se.appendChild(At),pe&&se.appendChild(pe),se}let ot,xt=a.find(se=>se.renderEventStreamToolbar);if(xt!=null&&xt.renderEventStreamToolbar&&n){let se=xt.renderEventStreamToolbar({config:n,defaultRenderer:()=>qe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:N=>{v=N,Z(),yt()},onSearchChange:N=>{M=N,Z(),yt()}});ot=se!=null?se:qe()}else ot=qe();let Ft=w("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");Ft.style.display="none";function Qt(){if(!s||!Ne||!K)return;let se=s(),N=n0(se);Ne.textContent=N;let ye=a0(se);pe&&(pe.textContent=ye,ye||(pe.style.display="none")),K.setAttribute("aria-label",ye?`Throughput: ${N}, ${ye}`:`Throughput: ${N}`)}let Ye=w("div","persona-flex-1 persona-min-h-0 persona-relative"),xe=w("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");xe.style.height="100%";let X=w("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");Ga(X,T==null?void 0:T.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let dt=ge(l,"14px","currentColor",2);dt&&X.appendChild(dt);let $e=w("span","");$e.textContent=p,X.appendChild($e);let Ce=w("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ce.style.display="none",Ye.appendChild(xe),Ye.appendChild(Ce),Ye.appendChild(X),y.setAttribute("tabindex","0"),y.appendChild(ot),y.appendChild(Ft),y.appendChild(Ye);function be(){let se=t.getAll(),N={};for(let At of se)N[At.type]=(N[At.type]||0)+1;let ye=Object.keys(N).sort(),Oe=ye.length!==H.length||!ye.every((At,gt)=>At===H[gt]),bt=!Oe&&ye.some(At=>N[At]!==I[At]),Qe=se.length!==Object.values(I).reduce((At,gt)=>At+gt,0);if(!Oe&&!bt&&!Qe||(H=ye,I=N,!ke))return;let Wt=ke.value;if(ke.options[0].textContent=`All events (${se.length})`,Oe){for(;ke.options.length>1;)ke.remove(1);for(let At of ye){let gt=w("option","");gt.value=At,gt.textContent=`${At} (${N[At]||0})`,ke.appendChild(gt)}Wt&&ye.includes(Wt)?ke.value=Wt:Wt&&(ke.value="",v="")}else for(let At=1;At<ke.options.length;At++){let gt=ke.options[At];gt.textContent=`${gt.value} (${N[gt.value]||0})`}}function et(){let se=t.getAll();if(v&&(se=se.filter(N=>N.type===v)),M){let N=M.toLowerCase();se=se.filter(ye=>ye.type.toLowerCase().includes(N)||ye.payload.toLowerCase().includes(N))}return se}function Lt(){return v!==""||M!==""}function Z(){F=0,Q=0,O.resume(),X.style.display="none"}function Ue(se){de.has(se)?de.delete(se):de.add(se),ue=se;let N=xe.scrollTop,ye=O.isFollowing();Te=!0,O.pause(),yt(),xe.scrollTop=N,ye&&O.resume(),Te=!1}function Sr(){return Bn(xe,50)}function yt(){he=Date.now(),ce=!1,Qt(),be();let se=t.getEvictedCount();se>0?(Ft.textContent=`${se.toLocaleString()} older events truncated`,Ft.style.display=""):Ft.style.display="none",S=et();let N=S.length,ye=t.getSize()>0;N===0&&ye&&Lt()?(Ce.textContent=M?`No events matching '${M}'`:"No events matching filter",Ce.style.display="",xe.style.display="none"):(Ce.style.display="none",xe.style.display=""),Fe&&(Fe.title=Lt()?`Copy Filtered (${N})`:"Copy All"),c&&!O.isFollowing()&&N>F&&(Q+=N-F,$e.textContent=p?`${p}${Q>0?` (${Q})`:""}`:"",X.style.display=""),F=N;let Oe=t.getAll(),bt=Oe.length>0?Oe[0].timestamp:0,Qe=new Set(S.map(gt=>gt.id));for(let gt of de)Qe.has(gt)||de.delete(gt);let Wt=v!==ne||M!==le,At=Ae.size===0&&S.length>0;if(Wt||At||S.length===0){xe.innerHTML="",Ae.clear();let gt=document.createDocumentFragment();for(let kt=0;kt<S.length;kt++){let Xt=yp(S[kt],kt,bt,f,de,Ue,a,n);Ae.set(S[kt].id,Xt),gt.appendChild(Xt)}xe.appendChild(gt),ne=v,le=M,ue=null}else{if(ue!==null){let kt=Ae.get(ue);if(kt&&kt.parentNode===xe){let Xt=S.findIndex(Ot=>Ot.id===ue);if(Xt>=0){let Ot=yp(S[Xt],Xt,bt,f,de,Ue,a,n);xe.insertBefore(Ot,kt),kt.remove(),Ae.set(ue,Ot)}}ue=null}let gt=new Set(S.map(kt=>kt.id));for(let[kt,Xt]of Ae)gt.has(kt)||(Xt.remove(),Ae.delete(kt));for(let kt=0;kt<S.length;kt++){let Xt=S[kt];if(!Ae.has(Xt.id)){let Ot=yp(Xt,kt,bt,f,de,Ue,a,n);Ae.set(Xt.id,Ot),xe.appendChild(Ot)}}}O.isFollowing()&&(xe.scrollTop=xe.scrollHeight)}function xr(){if(Date.now()-he>=Jv){te!==null&&(cancelAnimationFrame(te),te=null),yt();return}ce||(ce=!0,te=requestAnimationFrame(()=>{te=null,yt()}))}let Ao=(se,N)=>{if(!Fe)return;Fe.innerHTML="";let ye=ge(se,"12px","currentColor",1.5);ye&&Fe.appendChild(ye);let Oe=w("span","persona-text-xs");Oe.textContent="Copy All",Fe.appendChild(Oe),setTimeout(()=>{Fe.innerHTML="";let bt=ge("clipboard-copy","12px","currentColor",1.5);bt&&Fe.appendChild(bt);let Qe=w("span","persona-text-xs");Qe.textContent="Copy All",Fe.appendChild(Qe),Fe.disabled=!1},N)},Mo=async()=>{if(Fe){Fe.disabled=!0;try{let se;Lt()?se=S:r?(se=await r(),se.length===0&&(se=t.getAll())):se=t.getAll();let N=se.map(ye=>{try{return JSON.parse(ye.payload)}catch{return ye.payload}});await navigator.clipboard.writeText(JSON.stringify(N,null,2)),Ao("check",1500)}catch{Ao("x",1500)}}},P=()=>{ke&&(v=ke.value,Z(),yt())},ee=()=>{!j||!J||(J.style.display=j.value?"":"none",W&&clearTimeout(W),W=setTimeout(()=>{M=j.value,Z(),yt()},150))},Me=()=>{!j||!J||(j.value="",M="",J.style.display="none",W&&clearTimeout(W),Z(),yt())},He=()=>{if(Te)return;let se=xe.scrollTop,{action:N,nextLastScrollTop:ye}=Ui({following:O.isFollowing(),currentScrollTop:se,lastScrollTop:We,nearBottom:Sr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});We=ye,N==="resume"?(O.resume(),Q=0,X.style.display="none"):N==="pause"&&(O.pause(),c&&($e.textContent=p,X.style.display=""))},Le=se=>{let N=qi({following:O.isFollowing(),deltaY:se.deltaY,nearBottom:Sr(),resumeWhenNearBottom:!0});N==="pause"?(O.pause(),c&&($e.textContent=p,X.style.display="")):N==="resume"&&(O.resume(),Q=0,X.style.display="none")},Be=()=>{c&&(xe.scrollTop=xe.scrollHeight,O.resume(),Q=0,X.style.display="none")},Ge=se=>{let N=se.target;if(!N||N.closest("button"))return;let ye=N.closest("[data-event-id]");if(!ye)return;let Oe=ye.getAttribute("data-event-id");Oe&&Ue(Oe)},at=se=>{if((se.metaKey||se.ctrlKey)&&se.key==="f"){se.preventDefault(),j==null||j.focus(),j==null||j.select();return}se.key==="Escape"&&(j&&document.activeElement===j?(Me(),j.blur(),y.focus()):o&&o())};Fe&&Fe.addEventListener("click",Mo),ke&&ke.addEventListener("change",P),j&&j.addEventListener("input",ee),J&&J.addEventListener("click",Me),xe.addEventListener("scroll",He),xe.addEventListener("wheel",Le,{passive:!0}),xe.addEventListener("click",Ge),X.addEventListener("click",Be),y.addEventListener("keydown",at);function Pt(){W&&clearTimeout(W),te!==null&&(cancelAnimationFrame(te),te=null),ce=!1,Ae.clear(),Fe&&Fe.removeEventListener("click",Mo),ke&&ke.removeEventListener("change",P),j&&j.removeEventListener("input",ee),J&&J.removeEventListener("click",Me),xe.removeEventListener("scroll",He),xe.removeEventListener("wheel",Le),xe.removeEventListener("click",Ge),X.removeEventListener("click",Be),y.removeEventListener("keydown",at)}return{element:y,update:xr,destroy:Pt}}}function lx(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",n=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(u);let g=document.createElement("span");g.textContent=`Generating ${s.toLowerCase()}...`,f.appendChild(g)}else f.textContent=s;if(l.append(p,f),i.append(c,l),n==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${r}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",o),i.append(u)}return i}var dx=(e,t)=>{var o,n,a;let r=(a=(n=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(r){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",c=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=r({artifact:{artifactId:i,title:s,artifactType:l,status:c},config:t.config,defaultRenderer:()=>lx(e,t)});if(p)return p}return lx(e,t)};var bp=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)})}},ln=new bp;ln.register("PersonaArtifactCard",dx);function i0(e){var n;let t=w("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=w("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let o=w("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 cx(e,t){var Fe,j,J,Ne;let r=(j=(Fe=e.features)==null?void 0:Fe.artifacts)==null?void 0:j.layout,n=((J=r==null?void 0:r.toolbarPreset)!=null?J:"default")==="document",a=(Ne=r==null?void 0:r.panePadding)==null?void 0:Ne.trim(),s=e.markdown?ra(e.markdown):null,i=Ra(e.sanitize),c=K=>{let pe=s?s(K):Uo(K);return i?i(pe):pe},l=typeof document!="undefined"?w("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let f=w("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");f.setAttribute("data-persona-theme-zone","artifact-pane"),n&&f.classList.add("persona-artifact-pane-document");let u=w("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&u.classList.add("persona-artifact-toolbar-document");let g=w("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let x=w("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 K;p(),(K=t.onDismiss)==null||K.call(t)});let b="rendered",L=w("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=n?pr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):pr({icon:"eye",label:"Rendered view"}),A=n?pr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):pr({icon:"code-2",label:"Source"}),T=w("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),y=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,S=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,v=r==null?void 0:r.documentToolbarCopyMenuItems,M=!!(S&&v&&v.length>0),W=null,H,I=null,F=null;if(n&&(y||S)&&!M){if(H=y?Ds({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):pr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),S){let K=ge("chevron-down",14,"currentColor",2);K&&H.appendChild(K)}}else n&&M?(W=w("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),H=y?Ds({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):pr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I=pr({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(H,I)):n?H=pr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):H=pr({icon:"copy",label:"Copy"});let O=n?pr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):pr({icon:"refresh-cw",label:"Refresh"}),Q=n?pr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):pr({icon:"x",label:"Close"}),he=()=>{var xt,Ft,Qt;let K=(xt=Ae.find(Ye=>Ye.id===ne))!=null?xt:Ae[Ae.length-1],pe=(Ft=K==null?void 0:K.id)!=null?Ft:null,qe=(K==null?void 0:K.artifactType)==="markdown"&&(Qt=K.markdown)!=null?Qt:"",ot=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:qe,jsonPayload:ot,id:pe}},ce=async()=>{var xt;let{markdown:K,jsonPayload:pe}=he(),qe=(xt=Ae.find(Ft=>Ft.id===ne))!=null?xt:Ae[Ae.length-1],ot=(qe==null?void 0:qe.artifactType)==="markdown"?K:qe?pe:"";try{await navigator.clipboard.writeText(ot)}catch{}};if(H.addEventListener("click",async()=>{let K=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(K&&M){let{markdown:pe,jsonPayload:qe,id:ot}=he();try{await K({actionId:"primary",artifactId:ot,markdown:pe,jsonPayload:qe})}catch{}return}await ce()}),I&&(v!=null&&v.length)){let K=()=>{var qe;return(qe=f.closest("[data-persona-root]"))!=null?qe:document.body},pe=()=>{F=On({items:v.map(qe=>({id:qe.id,label:qe.label})),onSelect:async qe=>{let{markdown:ot,jsonPayload:xt,id:Ft}=he(),Qt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{Qt?await Qt({actionId:qe,artifactId:Ft,markdown:ot,jsonPayload:xt}):qe==="markdown"||qe==="md"?await navigator.clipboard.writeText(ot):qe==="json"||qe==="source"?await navigator.clipboard.writeText(xt):await navigator.clipboard.writeText(ot||xt)}catch{}},anchor:W!=null?W:I,position:"bottom-right",portal:K()})};f.isConnected?pe():requestAnimationFrame(pe),I.addEventListener("click",qe=>{qe.stopPropagation(),F==null||F.toggle()})}O.addEventListener("click",async()=>{var K;try{await((K=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:K.call(r))}catch{}ue()}),Q.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let te=()=>{n&&(E.setAttribute("aria-pressed",b==="rendered"?"true":"false"),A.setAttribute("aria-pressed",b==="source"?"true":"false"))};E.addEventListener("click",()=>{b="rendered",te(),ue()}),A.addEventListener("click",()=>{b="source",te(),ue()});let Te=w("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");n?(u.replaceChildren(),L.append(E,A),W?T.append(W,O,Q):T.append(H,O,Q),u.append(L,Te,T),te()):(u.appendChild(g),u.appendChild(x)),a&&(u.style.paddingLeft=a,u.style.paddingRight=a);let We=w("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"),de=w("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(We.style.paddingLeft=a,We.style.paddingRight=a,de.style.padding=a),f.appendChild(u),f.appendChild(We),f.appendChild(de);let Ae=[],ne=null,le=!1,ue=()=>{var ot,xt,Ft,Qt;let K=n&&Ae.length<=1;We.classList.toggle("persona-hidden",K),We.replaceChildren();for(let Ye of Ae){let xe=w("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");xe.type="button",xe.textContent=Ye.title||Ye.id.slice(0,8),Ye.id===ne&&xe.classList.add("persona-bg-persona-container","persona-border-persona-border"),xe.addEventListener("click",()=>t.onSelect(Ye.id)),We.appendChild(xe)}de.replaceChildren();let pe=ne&&Ae.find(Ye=>Ye.id===ne)||Ae[Ae.length-1];if(!pe)return;if(n){let Ye=pe.artifactType==="markdown"?"MD":(ot=pe.component)!=null?ot:"Component",X=(pe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Te.textContent=`${X} \xB7 ${Ye}`}else g.textContent="Artifacts";if(pe.artifactType==="markdown"){if(n&&b==="source"){let xe=w("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");xe.textContent=(xt=pe.markdown)!=null?xt:"",de.appendChild(xe);return}let Ye=w("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ye.innerHTML=c((Ft=pe.markdown)!=null?Ft:""),de.appendChild(Ye);return}let qe=pe.component?ln.get(pe.component):void 0;if(qe){let xe={message:{id:pe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=qe((Qt=pe.props)!=null?Qt:{},xe);if(X){de.appendChild(X);return}}catch{}}de.appendChild(i0(pe))},ke=()=>{var pe;let K=Ae.length>0;if(f.classList.toggle("persona-hidden",!K),l){let qe=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,xt=((pe=qe==null?void 0:qe.classList.contains("persona-artifact-narrow-host"))!=null?pe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&xt&&le?(l.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:l,update(K){var pe,qe,ot;Ae=K.artifacts,ne=(ot=(qe=K.selectedId)!=null?qe:(pe=K.artifacts[K.artifacts.length-1])==null?void 0:pe.id)!=null?ot:null,Ae.length>0&&(le=!0),ue(),ke()},setMobileOpen(K){le=K,!K&&l?(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):ke()}}}function io(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 px(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"),!io(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 l0(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,l,p,f,u,g,x,b,L,E;if(!io(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"),l0(e),px(e,t);return}let r=(l=(c=t.features)==null?void 0:c.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(f=r==null?void 0:r.paneWidth)!=null?f:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(u=r==null?void 0:r.paneMaxWidth)!=null?u:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(g=r==null?void 0:r.paneBackground)==null?void 0:g.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let n=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();n?e.style.setProperty("--persona-artifact-pane-padding",n):e.style.removeProperty("--persona-artifact-pane-padding");let a=(b=r==null?void 0:r.documentToolbarIconColor)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(L=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:L.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),px(e,t)}var ux=["panel","seamless"];function sl(e,t){var i,c,l,p,f,u;for(let g of ux)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!io(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(l=r==null?void 0:r.paneAppearance)!=null?l:"panel",n=ux.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${n}`);let a=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(f=r==null?void 0:r.paneShadow)==null?void 0:f.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((u=r.unifiedSplitOuterRadius)==null?void 0:u.trim())||a;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function fx(e,t){var r,o,n;return!t||!io(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function d0(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 c0(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 p0(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function u0(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function mx(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 gx(e,t,r,o,n,a){let s=d0(n,200),i=u0(t,r,o,200);i=Math.max(s,i);let c=c0(a);return c!==null&&(i=Math.min(i,c)),p0(e,s,i)}var hx={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"}},vp=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var x,b,L;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(b=hx[s])!=null?b:hx.init;a.classList.add("persona-form-card","persona-space-y-4");let c=w("div","persona-space-y-1"),l=w("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,c.appendChild(l),i.description){let E=w("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,c.appendChild(E)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var v,M;let A=w("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${E.name}`;let T=w("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=E.label,A.appendChild(T);let y=(v=E.type)!=null?v:"text",S;y==="textarea"?(S=document.createElement("textarea"),S.rows=3):(S=document.createElement("input"),S.type=y),S.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",S.id=`${t.id}-${s}-${E.name}`,S.name=E.name,S.placeholder=(M=E.placeholder)!=null?M:"",E.required&&(S.required=!0),A.appendChild(S),p.appendChild(A)});let f=w("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=w("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=w("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=(L=i.submitLabel)!=null?L:"Submit",f.appendChild(u),f.appendChild(g),p.appendChild(f),a.replaceChildren(c,p),p.addEventListener("submit",async E=>{var S,v;E.preventDefault();let A=(S=r.formEndpoint)!=null?S:"/form",T=new FormData(p),y={};T.forEach((M,W)=>{y[W]=M}),y.type=s,g.disabled=!0,u.textContent="Submitting\u2026";try{let M=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let W=await M.json();u.textContent=(v=W.message)!=null?v:"Thanks! We'll be in touch soon.",W.success&&W.nextPrompt&&await o.sendMessage(String(W.nextPrompt))}catch(M){u.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var wp=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 wp;var xx=()=>{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 f0=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},m0=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},Us=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=f0(e),r=m0(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}},Cp=e=>typeof e=="string"?e:e==null?"":String(e),ha={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Cp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=Cp(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:Cp(r.text)}}},yx=e=>Array.isArray(e)?e.map(t=>String(t)):[],qs=e=>{let t=new Set(yx(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(yx(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),o();let c={action:i,message:a.message};e.emit("action:detected",c);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",c)},f=l(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var g0=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}},h0=e=>e.map(t=>({...t,streaming:!1})),x0=e=>e.map(t=>({...t,status:"complete"})),il=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?g0(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?h0(r.messages):void 0,artifacts:r.artifacts?x0(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 Ka=La(oi(),1);function y0(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function b0(e,t){if(!y0(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 ll(){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,Ka.parse)(r,Ka.STR|Ka.OBJ),a=b0(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function bx(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function dl(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=ln.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 vx(){let e=ll();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function wx(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 cl(e){let t=wx(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=wx(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 v0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ul(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,ratingLabels:l=v0}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,g.appendChild(x);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=n,g.appendChild(b),u.appendChild(g);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-csat",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let v=1;v<=5;v++){let M=document.createElement("button");M.type="button",M.className="persona-feedback-rating-btn persona-feedback-star-btn",M.setAttribute("role","radio"),M.setAttribute("aria-checked","false"),M.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),M.title=l[v-1],M.dataset.rating=String(v),M.innerHTML=`
32
32
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
33
33
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
34
34
  </svg>
35
- `,M.addEventListener("click",()=>{f=v,E.forEach((W,H)=>{let I=H<v;W.classList.toggle("selected",I),W.setAttribute("aria-checked",H===v-1?"true":"false")})}),E.push(M),L.appendChild(M)}u.appendChild(L);let A=null;if(c){let v=document.createElement("div");v.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),v.appendChild(A),u.appendChild(v)}let T=document.createElement("div");T.className="persona-feedback-actions";let y=document.createElement("button");y.type="button",y.className="persona-feedback-btn persona-feedback-btn-skip",y.textContent=i,y.addEventListener("click",()=>{r==null||r(),p.remove()});let S=document.createElement("button");return S.type="button",S.className="persona-feedback-btn persona-feedback-btn-submit",S.textContent=s,S.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}S.disabled=!0,S.textContent="Submitting...";try{let v=(A==null?void 0:A.value.trim())||void 0;await t(f,v),p.remove()}catch(v){S.disabled=!1,S.textContent=s,console.error("[CSAT Feedback] Failed to submit:",v)}}),T.appendChild(y),T.appendChild(S),u.appendChild(T),p.appendChild(u),p}function ll(e){let{onSubmit:t,onDismiss:r,title:o="How likely are you to recommend us?",subtitle:n="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let u=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,x.appendChild(b);let L=document.createElement("p");L.className="persona-feedback-subtitle",L.textContent=n,x.appendChild(L),m.appendChild(x);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=l;let y=document.createElement("span");y.className="persona-feedback-label-high",y.textContent=p,A.appendChild(T),A.appendChild(y);let S=document.createElement("div");S.className="persona-feedback-numbers";let v=[];for(let D=0;D<=10;D++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${D} out of 10`),O.textContent=String(D),O.dataset.rating=String(D),D<=6?O.classList.add("persona-feedback-detractor"):D<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{u=D,v.forEach((J,me)=>{J.classList.toggle("selected",me===D),J.setAttribute("aria-checked",me===D?"true":"false")})}),v.push(O),S.appendChild(O)}E.appendChild(A),E.appendChild(S),m.appendChild(E);let M=null;if(c){let D=document.createElement("div");D.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),D.appendChild(M),m.appendChild(D)}let W=document.createElement("div");W.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{r==null||r(),f.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=s,I.addEventListener("click",async()=>{if(u===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let D=(M==null?void 0:M.value.trim())||void 0;await t(u,D),f.remove()}catch(D){I.disabled=!1,I.textContent=s,console.error("[NPS Feedback] Failed to submit:",D)}}),W.appendChild(H),W.appendChild(I),m.appendChild(W),f.appendChild(m),f}var Va="persona-chat-history",r0=30*1e3,o0={"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 n0(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=o0[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 dl(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 a0(e){var t,r,o,n,a,s,i,c,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(n=(o=e.persist)==null?void 0:o.openState)!=null?n:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(c=(i=e.persist)==null?void 0:i.focusInput)!=null?c:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function s0(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},ix=e=>e.map(t=>({...t,streaming:!1})),lx=(e,t,r)=>{let o=e!=null&&e.markdown?Gn(e.markdown):null,n=Ma(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&n&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),a=>{var p,f,u;let s=(p=a.text)!=null?p:"",i=(f=a.message.rawContent)!=null?f:null;if(t){let m=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});m!==null&&(s=m.text,m.persist||(a.message.__skipPersist=!0),m.resubmit&&!a.streaming&&r&&r())}let c=jn()!==null,l;if(e!=null&&e.postprocessMessage){let m=e.postprocessMessage({...a,text:s,raw:(u=i!=null?i:a.text)!=null?u:""});l=n?n(m):m}else if(o){let m=a.streaming?fg(s):s,x=o(m);l=n&&c?n(x):x}else l=Fo(s);return l}};function dx(e){var i,c,l,p;let t=w("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let r=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(c=e==null?void 0:e.iconSize)!=null?c:"48px",n=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",a=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,s=fe(r,o,n,a);if(s&&t.appendChild(s),e!=null&&e.label){let f=w("span","persona-drop-overlay-label");f.textContent=e.label,t.appendChild(f)}return t}var cl=(e,t,r)=>{var su,iu,lu,du,cu,pu,uu,fu,mu,gu,hu,xu,yu,bu,vu,wu,Cu,Su,Au,Mu,Tu,Eu,ku,Lu,Pu,Ru,Iu,Wu,Hu,Bu,Du,Fu,Nu,Ou,_u,Uu,qu,Vu,zu,$u,ju,Gu,Ku,Xu,Ju,Qu,Yu,Zu,ef,tf;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=Li(t),n=Is.getForInstance(o.plugins),{plugin:a,teardown:s}=Uh();o.components&&rn.registerAll(o.components);let i=rx(),l=o.persistState===!1?null:(su=o.storageAdapter)!=null?su:rl(),p={},f=null,u=!1,m=d=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(d);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:C}=g;return C&&(u=!0),h}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return d};if(l!=null&&l.load)try{let d=l.load();if(d&&typeof d.then=="function")f=d.then(g=>{let h=g!=null?g:{messages:[],metadata:{}};return m(h)});else{let g=d!=null?d:{messages:[],metadata:{}},h=m(g);h.metadata&&(p=hp(h.metadata)),(iu=h.messages)!=null&&iu.length&&(o={...o,initialMessages:h.messages}),(lu=h.artifacts)!=null&&lu.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(du=h.selectedArtifactId)!=null?du:null})}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",d)}else if(o.onStateLoaded)try{let d=m({messages:[],metadata:{}});(cu=d.messages)!=null&&cu.length&&(o={...o,initialMessages:d.messages})}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",d)}let x=()=>p,b=d=>{var h;p=(h=d({...p}))!=null?h:{},Ze()},L=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ws],E=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[la.message,la.messageAndClick],A=Hs({parsers:L,handlers:E,getSessionMetadata:x,updateSessionMetadata:b,emit:i.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let T=(uu=(pu=o.launcher)==null?void 0:pu.enabled)!=null?uu:!0,y=(mu=(fu=o.launcher)==null?void 0:fu.autoExpand)!=null?mu:!1,S=(gu=o.autoFocusInput)!=null?gu:!1,v=y,M=T,W=(xu=(hu=o.layout)==null?void 0:hu.header)==null?void 0:xu.layout,H=!1,I=()=>Ln(o),D=()=>T||I(),O=I()?!1:T?y:!0,J=!1,me=null,de=()=>{J=!0,me&&clearTimeout(me),me=setTimeout(()=>{J&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),J=!1)},1e4)},te=lx(o,A,de),Ae=(bu=(yu=o.features)==null?void 0:yu.showReasoning)!=null?bu:!0,Ie=(wu=(vu=o.features)==null?void 0:vu.showToolCalls)!=null?wu:!0,le=(Su=(Cu=o.features)==null?void 0:Cu.showEventStreamToggle)!=null?Su:!1,Ce=(Mu=(Au=o.features)==null?void 0:Au.scrollToBottom)!=null?Mu:{},se=(Eu=(Tu=o.features)==null?void 0:Tu.scrollBehavior)!=null?Eu:{},pe=`${(Lu=typeof o.persistState=="object"?(ku=o.persistState)==null?void 0:ku.keyPrefix:void 0)!=null?Lu:"persona-"}event-stream`,Ee=le?new Ps(pe):null,De=(Iu=(Ru=(Pu=o.features)==null?void 0:Pu.eventStream)==null?void 0:Ru.maxEvents)!=null?Iu:2e3,j=le?new Ls(De,Ee):null,Q=le?new Rs:null,Fe=null,K=!1,ce=null,qe=0;Ee==null||Ee.open().then(()=>j==null?void 0:j.restore()).catch(d=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",d)});let ot={onCopy:d=>{var g,h;i.emit("message:copy",d),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(d.id,"copy").catch(C=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",C)}),(h=(g=o.messageActions)==null?void 0:g.onCopy)==null||h.call(g,d)},onFeedback:d=>{var g,h;i.emit("message:feedback",d),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(d.messageId,d.type).catch(C=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",C)}),(h=(g=o.messageActions)==null?void 0:g.onFeedback)==null||h.call(g,d)}},yt=(Wu=o.statusIndicator)!=null?Wu:{},Ot=d=>{var g,h,C,R;return d==="idle"?(g=yt.idleText)!=null?g:Cr.idle:d==="connecting"?(h=yt.connectingText)!=null?h:Cr.connecting:d==="connected"?(C=yt.connectedText)!=null?C:Cr.connected:d==="error"?(R=yt.errorText)!=null?R:Cr.error:Cr[d]};function Qt(d,g,h,C){if(C==="idle"&&h.idleLink){d.textContent="";let R=document.createElement("a");R.href=h.idleLink,R.target="_blank",R.rel="noopener noreferrer",R.textContent=g,R.style.color="inherit",R.style.textDecoration="none",d.appendChild(R)}else d.textContent=g}let Ye=kh({config:o,showClose:D()}),{wrapper:ge,panel:X,pillRoot:dt}=Ye.shell,ze=Ye.panelElements,{container:ve,body:Me,messagesWrapper:et,suggestions:Pt,textarea:Z,sendButton:Ue,sendButtonWrapper:Ar,composerForm:bt,statusText:yr,introTitle:Co,introSubtitle:So,closeButton:P,iconHolder:ee,headerTitle:Se,headerSubtitle:We,header:ke,footer:He,actionsRow:Ge,leftActions:st,rightActions:Rt}=ze,ae=ze.setSendButtonMode,F=ze.micButton,he=ze.micButtonWrapper,Ne=ze.attachmentButton,vt=ze.attachmentButtonWrapper,Je=ze.attachmentInput,Bt=ze.attachmentPreviewsContainer;ve.classList.add("persona-relative"),Me.classList.add("persona-relative");let Mt=12,gt=()=>{var d;return(d=Ce.label)!=null?d:""},Lt=()=>{var d;return(d=Ce.iconName)!=null?d:"arrow-down"},Jt=()=>Ce.enabled!==!1,_t=()=>{var d;return(d=se.mode)!=null?d:"follow"},Fr=()=>{var d;return(d=se.anchorTopOffset)!=null?d:16},qt=w("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");qt.type="button",qt.style.display="none",qt.setAttribute("data-persona-scroll-to-bottom","true");let Nr=w("span","persona-flex persona-items-center"),Zr=w("span",""),br=w("span","");br.setAttribute("data-persona-scroll-to-bottom-count",""),br.style.display="none",qt.append(Nr,Zr,br),ve.appendChild(qt);let Rr=w("div","persona-stream-anchor-spacer");Rr.setAttribute("aria-hidden","true"),Rr.setAttribute("data-persona-anchor-spacer",""),Rr.style.flexShrink="0",Rr.style.pointerEvents="none",Rr.style.height="0px",Me.appendChild(Rr);let eo=()=>{let g=He.style.display==="none"?0:He.offsetHeight;qt.style.bottom=`${g+Mt}px`};eo();let on=()=>{let d=!!gt();qt.setAttribute("aria-label",gt()||"Jump to latest"),qt.title=gt(),qt.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false"),Nr.innerHTML="";let g=fe(Lt(),"14px","currentColor",2);g?(Nr.appendChild(g),Nr.style.display=""):Nr.style.display="none",Zr.textContent=gt(),Zr.style.display=d?"":"none"};on();let wt=null,Ao=null,Mo=n.find(d=>d.renderHeader);if(Mo!=null&&Mo.renderHeader){let d=Mo.renderHeader({config:o,defaultRenderer:()=>{let g=tn({config:o,showClose:D()});return oa(ve,g,o),g.header},onClose:()=>Vt(!1,"user")});if(d){let g=ve.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(d),ke=d,Ye.header.element=d)}}let _o=()=>{var g,h,C,R;if(!j)return;if(K=!0,!Fe&&j&&(Fe=jh({buffer:j,getFullHistory:()=>j.getAllFromStore(),onClose:()=>uo(),config:o,plugins:n,getThroughput:()=>{var N;return(N=Q==null?void 0:Q.getMetric())!=null?N:{status:"idle"}}})),Fe&&(Me.style.display="none",(g=He.parentNode)==null||g.insertBefore(Fe.element,He),Fe.update()),pt){pt.style.boxShadow=`inset 0 0 0 1.5px ${Pr.actionIconColor}`;let N=(R=(C=(h=o.features)==null?void 0:h.eventStream)==null?void 0:C.classNames)==null?void 0:R.toggleButtonActive;N&&N.split(/\s+/).forEach(z=>z&&pt.classList.add(z))}let d=()=>{if(!K)return;let N=Date.now();N-qe>=200&&(Fe==null||Fe.update(),qe=N),ce=requestAnimationFrame(d)};qe=0,ce=requestAnimationFrame(d),nt(),i.emit("eventStream:opened",{timestamp:Date.now()})},uo=()=>{var d,g,h;if(K){if(K=!1,Fe&&Fe.element.remove(),Me.style.display="",pt){pt.style.boxShadow="";let C=(h=(g=(d=o.features)==null?void 0:d.eventStream)==null?void 0:g.classNames)==null?void 0:h.toggleButtonActive;C&&C.split(/\s+/).forEach(R=>R&&pt.classList.remove(R))}ce!==null&&(cancelAnimationFrame(ce),ce=null),nt(),i.emit("eventStream:closed",{timestamp:Date.now()})}},pt=null;if(le){let d=(Bu=(Hu=o.features)==null?void 0:Hu.eventStream)==null?void 0:Bu.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(d!=null&&d.toggleButton?" "+d.toggleButton:"");pt=w("button",g),pt.style.width="28px",pt.style.height="28px",pt.style.color=Pr.actionIconColor,pt.type="button",pt.setAttribute("aria-label","Event Stream"),pt.title="Event Stream";let h=fe("activity","18px","currentColor",1.5);h&&pt.appendChild(h);let C=ze.clearChatButtonWrapper,R=ze.closeButtonWrapper,N=C||R;N&&N.parentNode===ke?ke.insertBefore(pt,N):ke.appendChild(pt),pt.addEventListener("click",()=>{K?uo():_o()})}let Rn=d=>{var R,N,z,U,_;let g=o.attachments;if(!(g!=null&&g.enabled))return;let h=(R=d.querySelector("[data-persona-composer-attachment-previews]"))!=null?R:d.querySelector(".persona-attachment-previews");if(!h){h=w("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=d.querySelector("[data-persona-composer-form]");oe!=null&&oe.parentNode?oe.parentNode.insertBefore(h,oe):d.insertBefore(h,d.firstChild)}if(!((N=d.querySelector("[data-persona-composer-attachment-input]"))!=null?N:d.querySelector('input[type="file"]'))){let oe=w("input");oe.type="file",oe.setAttribute("data-persona-composer-attachment-input",""),oe.accept=((z=g.allowedTypes)!=null?z:Zo).join(","),oe.multiple=((U=g.maxFiles)!=null?U:4)>1,oe.style.display="none",oe.setAttribute("aria-label",(_=g.buttonTooltipText)!=null?_:"Attach files"),d.appendChild(oe)}},To=n.find(d=>d.renderComposer);if(To!=null&&To.renderComposer){let d=o.composer,g=To.renderComposer({config:o,defaultRenderer:()=>Fa({config:o}).footer,onSubmit:h=>{var z;if(!q||q.isStreaming())return;let C=h.trim(),R=(z=wt==null?void 0:wt.hasAttachments())!=null?z:!1;if(!C&&!R)return;Fp();let N;R&&(N=[],N.push(...wt.getContentParts()),C&&N.push(gs(C))),q.sendMessage(C,{contentParts:N}),R&&wt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Je==null||Je.click()},models:d==null?void 0:d.models,selectedModelId:d==null?void 0:d.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Du=o.voiceRecognition)==null?void 0:Du.enabled)===!0?()=>{Ao==null||Ao()}:void 0});g&&(Ye.replaceComposer(g),He=Ye.composer.footer)}let In=d=>{let g=(...ne)=>{for(let Y of ne){let be=d.querySelector(Y);if(be)return be}return null},h=d.querySelector("[data-persona-composer-form]"),C=d.querySelector("[data-persona-composer-input]"),R=d.querySelector("[data-persona-composer-submit]"),N=d.querySelector("[data-persona-composer-mic]"),z=d.querySelector("[data-persona-composer-status]");h&&(bt=h),C&&(Z=C),R&&(Ue=R),N&&(F=N,he=N.parentElement),z&&(yr=z);let U=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Pt=U);let _=g("[data-persona-composer-attachment-button]",".persona-attachment-button");_&&(Ne=_,vt=_.parentElement),Je=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Bt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let oe=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");oe&&(Ge=oe)};Rn(He),In(He);let Ir=(Uu=(Fu=o.layout)==null?void 0:Fu.contentMaxWidth)!=null?Uu:I()?(_u=(Ou=(Nu=o.launcher)==null?void 0:Nu.composerBar)==null?void 0:Ou.contentMaxWidth)!=null?_u:"720px":void 0;if(Ir&&(et.style.maxWidth=Ir,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%"),Ir&&bt&&!I()&&(bt.style.maxWidth=Ir,bt.style.marginLeft="auto",bt.style.marginRight="auto"),Ir&&Pt&&!I()&&(Pt.style.maxWidth=Ir,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Ir&&Bt&&!I()&&(Bt.style.maxWidth=Ir,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),(qu=o.attachments)!=null&&qu.enabled&&Je&&Bt){wt=ea.fromConfig(o.attachments),wt.setPreviewsContainer(Bt),Je.addEventListener("change",h=>{let C=h.target;wt==null||wt.handleFileSelect(C.files),C.value=""});let d=o.attachments.dropOverlay,g=dx(d);ve.appendChild(g)}(()=>{var C,R;let d=(R=(C=o.layout)==null?void 0:C.slots)!=null?R:{},g=N=>{switch(N){case"body-top":return ve.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return et;case"footer-top":return Pt;case"composer":return bt;case"footer-bottom":return yr;default:return null}},h=(N,z)=>{var U;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")ke.insertBefore(z,ke.firstChild);else if(N==="header-right")ke.appendChild(z);else{let _=ke.querySelector(".persona-flex-col");_?(U=_.parentNode)==null||U.insertBefore(z,_.nextSibling):ke.appendChild(z)}break;case"body-top":{let _=Me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith(z):Me.insertBefore(z,Me.firstChild);break}case"body-bottom":Me.appendChild(z);break;case"footer-top":Pt.replaceWith(z);break;case"footer-bottom":yr.replaceWith(z);break;default:break}};for(let[N,z]of Object.entries(d))if(z)try{let U=z({config:o,defaultContent:()=>g(N)});U&&h(N,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,U)}})();let nn=d=>{var z,U;let h=d.target.closest('button[data-expand-header="true"]');if(!h)return;let C=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!C)return;let R=C.getAttribute("data-message-id");if(!R)return;let N=h.getAttribute("data-bubble-type");if(N==="reasoning")Oa.has(R)?Oa.delete(R):Oa.add(R),Ih(R,C);else if(N==="tool")_a.has(R)?_a.delete(R):_a.add(R),Wh(R,C,o);else if(N==="approval"){let _=o.approval!==!1?o.approval:void 0,oe=((z=_==null?void 0:_.detailsDisplay)!=null?z:"collapsed")==="expanded",ne=(U=aa.get(R))!=null?U:oe;aa.set(R,!ne),Fh(R,C,o)}Ro.delete(R)};et.addEventListener("pointerdown",d=>{d.target.closest('button[data-expand-header="true"]')&&(d.preventDefault(),nn(d))}),et.addEventListener("keydown",d=>{let g=d.target;(d.key==="Enter"||d.key===" ")&&g.closest('button[data-expand-header="true"]')&&(d.preventDefault(),nn(d))}),et.addEventListener("copy",d=>{let{clipboardData:g}=d;if(!g)return;let h=et.getRootNode(),C=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!C||C.isCollapsed)return;let R=C.toString(),N=ch(R);!N||N===R||(g.setData("text/plain",N),d.preventDefault())});let Uo=new Map,an=null,sn="idle",Wn={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Hn=(d,g)=>{let{icon:h,label:C}=Wn[g];d.setAttribute("aria-label",C),d.title=C,d.setAttribute("aria-pressed",g==="idle"?"false":"true"),d.classList.toggle("persona-message-action-active",g!=="idle"),d.classList.toggle("persona-message-action-loading",g==="loading");let R=fe(h,14,"currentColor",2);R&&(d.innerHTML="",d.appendChild(R))},ln=()=>{et.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{var N;let h=g.closest("[data-actions-for]"),C=(N=h==null?void 0:h.getAttribute("data-actions-for"))!=null?N:null;Hn(g,C&&C===an?sn:"idle")})};et.addEventListener("click",d=>{var z;let h=d.target.closest(".persona-message-action-btn[data-action]");if(!h)return;d.preventDefault(),d.stopPropagation();let C=h.closest("[data-actions-for]");if(!C)return;let R=C.getAttribute("data-actions-for");if(!R)return;let N=h.getAttribute("data-action");if(N==="copy"){let _=q.getMessages().find(oe=>oe.id===R);if(_&&ot.onCopy){let oe=_.content||"";navigator.clipboard.writeText(oe).then(()=>{h.classList.add("persona-message-action-success");let ne=fe("check",14,"currentColor",2);ne&&(h.innerHTML="",h.appendChild(ne)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=fe("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(ne=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ne)}),ot.onCopy(_)}}else if(N==="read-aloud")q.toggleReadAloud(R);else if(N==="upvote"||N==="downvote"){let _=((z=Uo.get(R))!=null?z:null)===N,oe=N==="upvote"?"thumbs-up":"thumbs-down";if(_){Uo.delete(R),h.classList.remove("persona-message-action-active");let ne=fe(oe,14,"currentColor",2);ne&&(h.innerHTML="",h.appendChild(ne))}else{let ne=N==="upvote"?"downvote":"upvote",Y=C.querySelector(`[data-action="${ne}"]`);if(Y){Y.classList.remove("persona-message-action-active");let Ve=fe(ne==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ve&&(Y.innerHTML="",Y.appendChild(Ve))}Uo.set(R,N),h.classList.add("persona-message-action-active");let be=fe(oe,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(be)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let we=q.getMessages().find(Qe=>Qe.id===R);we&&ot.onFeedback&&ot.onFeedback({type:N,messageId:we.id,message:we})}}}),et.addEventListener("click",d=>{let h=d.target.closest("button[data-approval-action]");if(!h)return;d.preventDefault(),d.stopPropagation();let C=h.closest(".persona-approval-bubble");if(!C)return;let R=C.getAttribute("data-message-id");if(!R)return;let N=h.getAttribute("data-approval-action");if(!N)return;let z=N==="approve"?"approved":"denied",_=q.getMessages().find(ne=>ne.id===R);if(!(_!=null&&_.approval))return;let oe=C.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),_.approval.toolType==="webmcp"?q.resolveWebMcpApproval(R,z):q.resolveApproval(_.approval,z)});let xt=null,Or=null,_r={artifacts:[],selectedId:null},Mr=!1,Ct={current:null};et.addEventListener("click",d=>{var Y,be,Be,we,Qe;let h=d.target.closest("[data-download-artifact]");if(!h)return;d.preventDefault(),d.stopPropagation();let C=h.getAttribute("data-download-artifact");if(!C||((Be=(be=(Y=o.features)==null?void 0:Y.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Be.call(be,{type:"download",artifactId:C}))===!0)return;let N=q.getArtifactById(C),z=N==null?void 0:N.markdown,U=(N==null?void 0:N.title)||"artifact";if(!z){let Ve=h.closest("[data-open-artifact]"),lt=Ve==null?void 0:Ve.closest("[data-message-id]"),tt=lt==null?void 0:lt.getAttribute("data-message-id");if(tt){let Te=q.getMessages().find($e=>$e.id===tt);if(Te!=null&&Te.rawContent)try{let $e=JSON.parse(Te.rawContent);z=(we=$e==null?void 0:$e.props)==null?void 0:we.markdown,U=((Qe=$e==null?void 0:$e.props)==null?void 0:Qe.title)||U}catch{}}}if(!z)return;let _=new Blob([z],{type:"text/markdown"}),oe=URL.createObjectURL(_),ne=document.createElement("a");ne.href=oe,ne.download=`${U}.md`,ne.click(),URL.revokeObjectURL(oe)}),et.addEventListener("click",d=>{var N,z,U;let h=d.target.closest("[data-open-artifact]");if(!h)return;let C=h.getAttribute("data-open-artifact");!C||((U=(z=(N=o.features)==null?void 0:N.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:U.call(z,{type:"open",artifactId:C}))===!0||(d.preventDefault(),d.stopPropagation(),Mr=!1,q.selectArtifact(C),Wr())}),et.addEventListener("keydown",d=>{if(d.key!=="Enter"&&d.key!==" ")return;let g=d.target;g.hasAttribute("data-open-artifact")&&(d.preventDefault(),g.click())});let to=ze.composerOverlay,ro=(d,g,h)=>{var U,_,oe,ne;let C=g.trim();if(!C||!Ct.current)return;let R=(U=d.getAttribute("data-tool-call-id"))!=null?U:"",N=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:R,answer:C,answers:h.structured,values:(_=h.values)!=null?_:h.source==="multi"?C.split(", "):[C],isFreeText:N,source:h.source},bubbles:!0,composed:!0})),wn(to,R);let z=Ct.current.getMessages().find(Y=>{var be;return((be=Y.toolCall)==null?void 0:be.id)===R});(oe=z==null?void 0:z.agentMetadata)!=null&&oe.awaitingLocalTool?Ct.current.resolveAskUserQuestion(z,(ne=h.structured)!=null?ne:C):Ct.current.sendMessage(C)},Ur=d=>{var R;let g=Ct.current;if(!g)return;let h=(R=d.getAttribute("data-tool-call-id"))!=null?R:"",C=g.getMessages().find(N=>{var z;return((z=N.toolCall)==null?void 0:z.id)===h});C&&g.persistAskUserQuestionProgress(C,{answers:ei(d,C),currentIndex:co(d)})},dn=d=>Object.entries(d).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),qo=d=>{var R,N,z;if(((N=(R=o.features)==null?void 0:R.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let g=co(d),h=ka(d);if(g>=h-1)return;let C=(z=Ct.current)==null?void 0:z.getMessages().find(U=>{var _;return((_=U.toolCall)==null?void 0:_.id)===d.getAttribute("data-tool-call-id")});C&&(ti(d,C,o,g+1),Ur(d))};to.addEventListener("click",d=>{var N,z,U,_,oe,ne,Y,be,Be,we,Qe,Ve,lt,tt;let h=d.target.closest("[data-ask-user-action]");if(!h)return;let C=h.closest("[data-persona-ask-sheet-for]");if(!C)return;let R=h.getAttribute("data-ask-user-action");if(d.preventDefault(),d.stopPropagation(),R==="dismiss"){let Le=(N=C.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),wn(to,Le);let Te=(z=Ct.current)==null?void 0:z.getMessages().find($e=>{var je;return((je=$e.toolCall)==null?void 0:je.id)===Le});(U=Te==null?void 0:Te.agentMetadata)!=null&&U.awaitingLocalTool&&((_=Ct.current)==null||_.markAskUserQuestionResolved(Te),(oe=Ct.current)==null||oe.resolveAskUserQuestion(Te,"(dismissed)"));return}if(R==="pick"){let Le=h.getAttribute("data-option-label");if(!Le)return;let Te=C.getAttribute("data-multi-select")==="true",$e=vn(C);if($e&&Te){let je=Kn(C)[co(C)],mt=new Set(Array.isArray(je)?je:[]);mt.has(Le)?mt.delete(Le):mt.add(Le),Cn(C,Array.from(mt)),Ur(C);return}if($e){Cn(C,Le),Ur(C),qo(C);return}if(Te){let je=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",je?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!je);let mt=C.querySelector('[data-ask-user-action="submit-multi"]');mt&&(mt.disabled=Wl(C).length===0);return}ro(C,Le,{source:"pick",values:[Le]});return}if(R==="submit-multi"){let Le=Wl(C);if(Le.length===0)return;ro(C,Le.join(", "),{source:"multi",values:Le});return}if(R==="open-free-text"){let Le=C.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let Te=Le.querySelector('[data-ask-free-text-input="true"]');Te==null||Te.focus()}return}if(R==="focus-free-text"){let Le=C.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(R==="submit-free-text"){let Le=C.querySelector('[data-ask-free-text-input="true"]'),Te=(ne=Le==null?void 0:Le.value)!=null?ne:"";if(!Te.trim())return;if(vn(C)){Cn(C,Te.trim()),Ur(C),qo(C);return}ro(C,Te,{source:"free-text"});return}if(R==="next"||R==="back"){if(!Ct.current)return;let Le=(Y=C.getAttribute("data-tool-call-id"))!=null?Y:"",Te=Ct.current.getMessages().find(Re=>{var Pe;return((Pe=Re.toolCall)==null?void 0:Pe.id)===Le});if(!Te)return;let $e=C.querySelector('[data-ask-free-text-input="true"]'),je=(Be=(be=$e==null?void 0:$e.value)==null?void 0:be.trim())!=null?Be:"";if(je){let Re=Kn(C)[co(C)];(typeof Re!="string"||Re!==je)&&Cn(C,je)}let mt=R==="next"?1:-1,B=co(C)+mt;ti(C,Te,o,B),Ur(C);return}if(R==="submit-all"){if(!Ct.current)return;let Le=(we=C.getAttribute("data-tool-call-id"))!=null?we:"",Te=Ct.current.getMessages().find(Re=>{var Pe;return((Pe=Re.toolCall)==null?void 0:Pe.id)===Le});if(!Te)return;let $e=C.querySelector('[data-ask-free-text-input="true"]'),je=(Ve=(Qe=$e==null?void 0:$e.value)==null?void 0:Qe.trim())!=null?Ve:"";je&&Cn(C,je);let mt=ei(C,Te);Ct.current.persistAskUserQuestionProgress(Te,{answers:mt,currentIndex:co(C)});let B=dn(mt);ro(C,B||"(submitted)",{source:"submit-all",structured:mt});return}if(R==="skip"){if(!Ct.current)return;let Le=(lt=C.getAttribute("data-tool-call-id"))!=null?lt:"",Te=Ct.current.getMessages().find(Pe=>{var ue;return((ue=Pe.toolCall)==null?void 0:ue.id)===Le});if(!Te)return;let $e=vn(C),je=co(C),mt=ka(C),B=je>=mt-1;if(!$e){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),wn(to,Le),(tt=Te.agentMetadata)!=null&&tt.awaitingLocalTool&&(Ct.current.markAskUserQuestionResolved(Te),Ct.current.resolveAskUserQuestion(Te,"(dismissed)"));return}Cn(C,"");let Re=C.querySelector('[data-ask-free-text-input="true"]');if(Re&&(Re.value=""),B){let Pe=ei(C,Te),ue=dn(Pe);ro(C,ue||"(skipped)",{source:"submit-all",structured:Pe});return}ti(C,Te,o,je+1),Ur(C);return}}),to.addEventListener("keydown",d=>{var N;if(d.key!=="Enter")return;let h=d.target;if(!((N=h.matches)!=null&&N.call(h,'[data-ask-free-text-input="true"]')))return;let C=h.closest("[data-persona-ask-sheet-for]");if(!C)return;d.preventDefault();let R=h.value;if(R.trim()){if(vn(C)){Cn(C,R.trim()),Ur(C),qo(C);return}ro(C,R,{source:"free-text"})}});let cn=d=>{if(!/^[1-9]$/.test(d.key)||d.metaKey||d.ctrlKey||d.altKey)return;let g=d.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let h=to.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let C=Number(d.key),N=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[C-1];N&&(d.preventDefault(),N.click())};document.addEventListener("keydown",cn);let qr=null,It=null,Tr=null,oo=null,pn=()=>{};function Vo(){oo==null||oo(),oo=null}let un=()=>{var z;if(!qr||!It)return;let d=e.classList.contains("persona-artifact-appearance-seamless"),h=((z=e.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!d||e.classList.contains("persona-artifact-narrow-host")||h){It.style.removeProperty("position"),It.style.removeProperty("left"),It.style.removeProperty("top"),It.style.removeProperty("bottom"),It.style.removeProperty("width"),It.style.removeProperty("z-index");return}let C=qr.firstElementChild;if(!C||C===It)return;let R=10;It.style.position="absolute",It.style.top="0",It.style.bottom="0",It.style.width=`${R}px`,It.style.zIndex="5";let N=C.offsetWidth-R/2;It.style.left=`${Math.max(0,N)}px`},ye=()=>{},Wr=()=>{var h,C,R,N,z;if(!xt||!po(o))return;el(e,o),tl(e,o),ye();let d=(N=(R=(C=(h=o.features)==null?void 0:h.artifacts)==null?void 0:C.layout)==null?void 0:R.narrowHostMaxWidth)!=null?N:520,g=X.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=d),xt.update(_r),Mr?(xt.setMobileOpen(!1),xt.element.classList.add("persona-hidden"),(z=xt.backdrop)==null||z.classList.add("persona-hidden")):_r.artifacts.length>0&&(xt.element.classList.remove("persona-hidden"),xt.setMobileOpen(!0)),pn()};if(po(o)){X.style.position="relative";let d=w("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=w("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");d.appendChild(ve),xt=Xh(o,{onSelect:h=>{var C;return(C=Ct.current)==null?void 0:C.selectArtifact(h)},onDismiss:()=>{Mr=!0,Wr()}}),xt.element.classList.add("persona-hidden"),qr=g,g.appendChild(d),g.appendChild(xt.element),xt.backdrop&&X.appendChild(xt.backdrop),X.appendChild(g),pn=()=>{var C,R,N,z;if(!qr||!xt)return;if(!(((N=(R=(C=o.features)==null?void 0:C.artifacts)==null?void 0:R.layout)==null?void 0:N.resizable)===!0)){Tr==null||Tr(),Tr=null,Vo(),It&&(It.remove(),It=null),xt.element.style.removeProperty("width"),xt.element.style.removeProperty("maxWidth");return}if(!It){let U=w("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let _=e.ownerDocument,oe=(z=_.defaultView)!=null?z:window,ne=Y=>{var lt,tt;if(!xt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||oe.innerWidth<=640)return;Y.preventDefault(),Vo();let be=Y.clientX,Be=xt.element.getBoundingClientRect().width,we=(tt=(lt=o.features)==null?void 0:lt.artifacts)==null?void 0:tt.layout,Qe=Le=>{let Te=qr.getBoundingClientRect().width,$e=e.classList.contains("persona-artifact-appearance-seamless"),je=$e?0:Zh(qr,oe),mt=$e?0:U.getBoundingClientRect().width||6,B=Be-(Le.clientX-be),Re=ex(B,Te,je,mt,we==null?void 0:we.resizableMinWidth,we==null?void 0:we.resizableMaxWidth);xt.element.style.width=`${Re}px`,xt.element.style.maxWidth="none",un()},Ve=()=>{_.removeEventListener("pointermove",Qe),_.removeEventListener("pointerup",Ve),_.removeEventListener("pointercancel",Ve),oo=null;try{U.releasePointerCapture(Y.pointerId)}catch{}};oo=Ve,_.addEventListener("pointermove",Qe),_.addEventListener("pointerup",Ve),_.addEventListener("pointercancel",Ve);try{U.setPointerCapture(Y.pointerId)}catch{}};U.addEventListener("pointerdown",ne),It=U,qr.insertBefore(U,xt.element),Tr=()=>{U.removeEventListener("pointerdown",ne)}}if(It){let U=_r.artifacts.length>0&&!Mr;It.classList.toggle("persona-hidden",!U),un()}},ye=()=>{var oe,ne,Y,be,Be,we,Qe,Ve,lt,tt,Le,Te,$e,je;if(!T||!xt||((ne=(oe=o.launcher)==null?void 0:oe.sidebarMode)!=null?ne:!1)||nr(o)&&Qr(o).reveal==="emerge")return;let C=(Y=e.ownerDocument.defaultView)!=null?Y:window,R=(Be=(be=o.launcher)==null?void 0:be.mobileFullscreen)!=null?Be:!0,N=(Qe=(we=o.launcher)==null?void 0:we.mobileBreakpoint)!=null?Qe:640;if(R&&C.innerWidth<=N||!Yh(o,T))return;let z=(tt=(lt=(Ve=o.launcher)==null?void 0:Ve.width)!=null?lt:o.launcherWidth)!=null?tt:Jr,U=(je=($e=(Te=(Le=o.features)==null?void 0:Le.artifacts)==null?void 0:Te.layout)==null?void 0:$e.expandedPanelWidth)!=null?je:"min(720px, calc(100vw - 24px))";_r.artifacts.length>0&&!Mr?(X.style.width=U,X.style.maxWidth=U):(X.style.width=z,X.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(Or=new ResizeObserver(()=>{Wr()}),Or.observe(X))}else X.appendChild(ve),I()&&dt&&(ze.peekBanner&&dt.appendChild(ze.peekBanner),dt.appendChild(He));e.appendChild(ge),dt&&e.appendChild(dt);let Eo=()=>{var Re,Pe,ue,Dt,Wt,Gt,ht,zt,jr,er,Ke,Tt,or,io,Gr,_n,Un,wa,Ca,Kt,qn,gn,hn,Xo,Vn,ho,Bo,Xe;if(I()){X.style.width="100%",X.style.maxWidth="100%";let Ft=(Pe=(Re=o.launcher)==null?void 0:Re.composerBar)!=null?Pe:{},jt=ge.dataset.state==="expanded",Nt=(ue=Ft.expandedSize)!=null?ue:"anchored";if(!(jt&&Nt!=="fullscreen")){ve.style.background="",ve.style.border="",ve.style.borderRadius="",ve.style.overflow="",ve.style.boxShadow="";return}let Et=(Wt=(Dt=o.theme)==null?void 0:Dt.components)==null?void 0:Wt.panel,Ut=Ba(o),fr=(gr,lo)=>{var xn;return gr==null||gr===""?lo:(xn=Wa(Ut,gr))!=null?xn:gr},Kr="1px solid var(--persona-border)",Do="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ve.style.background="var(--persona-surface, #ffffff)",ve.style.border=fr(Et==null?void 0:Et.border,Kr),ve.style.borderRadius=fr(Et==null?void 0:Et.borderRadius,mr),ve.style.boxShadow=fr(Et==null?void 0:Et.shadow,Do),ve.style.overflow="hidden";return}let d=nr(o),g=(ht=(Gt=o.launcher)==null?void 0:Gt.sidebarMode)!=null?ht:!1,h=d||g||((jr=(zt=o.launcher)==null?void 0:zt.fullHeight)!=null?jr:!1),C=((er=o.launcher)==null?void 0:er.enabled)===!1,R=(Tt=(Ke=o.theme)==null?void 0:Ke.components)==null?void 0:Tt.panel,N=Ba(o),z=(Ft,jt)=>{var Nt;return Ft==null||Ft===""?jt:(Nt=Wa(N,Ft))!=null?Nt:Ft},U=(or=e.ownerDocument.defaultView)!=null?or:window,_=(Gr=(io=o.launcher)==null?void 0:io.mobileFullscreen)!=null?Gr:!0,oe=(Un=(_n=o.launcher)==null?void 0:_n.mobileBreakpoint)!=null?Un:640,ne=U.innerWidth<=oe,Y=_&&ne&&T,be=(Ca=(wa=o.launcher)==null?void 0:wa.position)!=null?Ca:"bottom-left",Be=be==="bottom-left"||be==="top-left",we=(qn=(Kt=o.launcher)==null?void 0:Kt.zIndex)!=null?qn:Sr,Qe=g||Y?"none":"1px solid var(--persona-border)",Ve=Y?"none":g?Be?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";d&&!Y&&(Ve="none",Qe="none");let lt=g||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",tt=z(R==null?void 0:R.border,Qe),Le=z(R==null?void 0:R.shadow,Ve),Te=z(R==null?void 0:R.borderRadius,lt),$e=Me.scrollTop;e.style.cssText="",ge.style.cssText="",X.style.cssText="",ve.style.cssText="",Me.style.cssText="",He.style.cssText="",K&&(Me.style.display="none");let je=()=>{var jt;if($e<=0)return;((jt=Me.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(Me.scrollTop===$e)return;let Nt=Me.scrollHeight-Me.clientHeight;Nt<=0||(Me.scrollTop=Math.min($e,Nt))})};if(Y){ge.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"),ge.style.cssText=`
35
+ `,M.addEventListener("click",()=>{f=v,E.forEach((W,H)=>{let I=H<v;W.classList.toggle("selected",I),W.setAttribute("aria-checked",H===v-1?"true":"false")})}),E.push(M),L.appendChild(M)}u.appendChild(L);let A=null;if(c){let v=document.createElement("div");v.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),v.appendChild(A),u.appendChild(v)}let T=document.createElement("div");T.className="persona-feedback-actions";let y=document.createElement("button");y.type="button",y.className="persona-feedback-btn persona-feedback-btn-skip",y.textContent=i,y.addEventListener("click",()=>{r==null||r(),p.remove()});let S=document.createElement("button");return S.type="button",S.className="persona-feedback-btn persona-feedback-btn-submit",S.textContent=s,S.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}S.disabled=!0,S.textContent="Submitting...";try{let v=(A==null?void 0:A.value.trim())||void 0;await t(f,v),p.remove()}catch(v){S.disabled=!1,S.textContent=s,console.error("[CSAT Feedback] Failed to submit:",v)}}),T.appendChild(y),T.appendChild(S),u.appendChild(T),p.appendChild(u),p}function fl(e){let{onSubmit:t,onDismiss:r,title:o="How likely are you to recommend us?",subtitle:n="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,x.appendChild(b);let L=document.createElement("p");L.className="persona-feedback-subtitle",L.textContent=n,x.appendChild(L),g.appendChild(x);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=l;let y=document.createElement("span");y.className="persona-feedback-label-high",y.textContent=p,A.appendChild(T),A.appendChild(y);let S=document.createElement("div");S.className="persona-feedback-numbers";let v=[];for(let F=0;F<=10;F++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${F} out of 10`),O.textContent=String(F),O.dataset.rating=String(F),F<=6?O.classList.add("persona-feedback-detractor"):F<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{u=F,v.forEach((Q,he)=>{Q.classList.toggle("selected",he===F),Q.setAttribute("aria-checked",he===F?"true":"false")})}),v.push(O),S.appendChild(O)}E.appendChild(A),E.appendChild(S),g.appendChild(E);let M=null;if(c){let F=document.createElement("div");F.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"),F.appendChild(M),g.appendChild(F)}let W=document.createElement("div");W.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{r==null||r(),f.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=s,I.addEventListener("click",async()=>{if(u===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let F=(M==null?void 0:M.value.trim())||void 0;await t(u,F),f.remove()}catch(F){I.disabled=!1,I.textContent=s,console.error("[NPS Feedback] Failed to submit:",F)}}),W.appendChild(H),W.appendChild(I),g.appendChild(W),f.appendChild(g),f}var Xa="persona-chat-history",w0=30*1e3,C0={"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 S0(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=C0[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 ml(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 A0(e){var t,r,o,n,a,s,i,c,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(n=(o=e.persist)==null?void 0:o.openState)!=null?n:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(c=(i=e.persist)==null?void 0:i.focusInput)!=null?c:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function M0(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Sp=e=>!e||typeof e!="object"?{}:{...e},Cx=e=>e.map(t=>({...t,streaming:!1})),Sx=(e,t,r)=>{let o=e!=null&&e.markdown?ra(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 p,f,u;let s=(p=a.text)!=null?p:"",i=(f=a.message.rawContent)!=null?f:null;if(t){let g=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});g!==null&&(s=g.text,g.persist||(a.message.__skipPersist=!0),g.resubmit&&!a.streaming&&r&&r())}let c=ta()!==null,l;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...a,text:s,raw:(u=i!=null?i:a.text)!=null?u:""});l=n?n(g):g}else if(o){let g=a.streaming?kg(s):s,x=o(g);l=n&&c?n(x):x}else l=Uo(s);return l}};function Ax(e){var i,c,l,p;let t=w("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let r=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(c=e==null?void 0:e.iconSize)!=null?c:"48px",n=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",a=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,s=ge(r,o,n,a);if(s&&t.appendChild(s),e!=null&&e.label){let f=w("span","persona-drop-overlay-label");f.textContent=e.label,t.appendChild(f)}return t}var gl=(e,t,r)=>{var wu,Cu,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,cf,pf,uf,ff,mf,gf,hf,xf;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=Hi(t),n=_s.getForInstance(o.plugins),{plugin:a,teardown:s}=rx();o.components&&ln.registerAll(o.components);let i=xx(),l=o.persistState===!1?null:(wu=o.storageAdapter)!=null?wu:il(),p={},f=null,u=!1,g=d=>{if(o.onStateLoaded)try{let m=o.onStateLoaded(d);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:C}=m;return C&&(u=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return d};if(l!=null&&l.load)try{let d=l.load();if(d&&typeof d.then=="function")f=d.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return g(h)});else{let m=d!=null?d:{messages:[],metadata:{}},h=g(m);h.metadata&&(p=Sp(h.metadata)),(Cu=h.messages)!=null&&Cu.length&&(o={...o,initialMessages:h.messages}),(Su=h.artifacts)!=null&&Su.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Au=h.selectedArtifactId)!=null?Au:null})}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",d)}else if(o.onStateLoaded)try{let d=g({messages:[],metadata:{}});(Mu=d.messages)!=null&&Mu.length&&(o={...o,initialMessages:d.messages})}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",d)}let x=()=>p,b=d=>{var h;p=(h=d({...p}))!=null?h:{},ir()},L=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Us],E=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ha.message,ha.messageAndClick],A=qs({parsers:L,handlers:E,getSessionMetadata:x,updateSessionMetadata:b,emit:i.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let T=(Eu=(Tu=o.launcher)==null?void 0:Tu.enabled)!=null?Eu:!0,y=(Lu=(ku=o.launcher)==null?void 0:ku.autoExpand)!=null?Lu:!1,S=(Pu=o.autoFocusInput)!=null?Pu:!1,v=y,M=T,W=(Iu=(Ru=o.layout)==null?void 0:Ru.header)==null?void 0:Iu.layout,H=!1,I=()=>Nn(o),F=()=>T||I(),O=I()?!1:T?y:!0,Q=!1,he=null,ce=()=>{Q=!0,he&&clearTimeout(he),he=setTimeout(()=>{Q&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Q=!1)},1e4)},te=Sx(o,A,ce),Te=(Hu=(Wu=o.features)==null?void 0:Wu.showReasoning)!=null?Hu:!0,We=(Du=(Bu=o.features)==null?void 0:Bu.showToolCalls)!=null?Du:!0,de=(Nu=(Fu=o.features)==null?void 0:Fu.showEventStreamToggle)!=null?Nu:!1,Ae=(_u=(Ou=o.features)==null?void 0:Ou.scrollToBottom)!=null?_u:{},ne=(qu=(Uu=o.features)==null?void 0:Uu.scrollBehavior)!=null?qu:{},ue=`${($u=typeof o.persistState=="object"?(Vu=o.persistState)==null?void 0:Vu.keyPrefix:void 0)!=null?$u:"persona-"}event-stream`,ke=de?new Ns(ue):null,Fe=(Gu=(ju=(zu=o.features)==null?void 0:zu.eventStream)==null?void 0:ju.maxEvents)!=null?Gu:2e3,j=de?new Fs(Fe,ke):null,J=de?new Os:null,Ne=null,K=!1,pe=null,qe=0;ke==null||ke.open().then(()=>j==null?void 0:j.restore()).catch(d=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",d)});let ot={onCopy:d=>{var m,h;i.emit("message:copy",d),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(d.id,"copy").catch(C=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",C)}),(h=(m=o.messageActions)==null?void 0:m.onCopy)==null||h.call(m,d)},onFeedback:d=>{var m,h;i.emit("message:feedback",d),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(d.messageId,d.type).catch(C=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",C)}),(h=(m=o.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,d)}},xt=(Ku=o.statusIndicator)!=null?Ku:{},Ft=d=>{var m,h,C,R;return d==="idle"?(m=xt.idleText)!=null?m:wr.idle:d==="connecting"?(h=xt.connectingText)!=null?h:wr.connecting:d==="connected"?(C=xt.connectedText)!=null?C:wr.connected:d==="error"?(R=xt.errorText)!=null?R:wr.error:wr[d]};function Qt(d,m,h,C){if(C==="idle"&&h.idleLink){d.textContent="";let R=document.createElement("a");R.href=h.idleLink,R.target="_blank",R.rel="noopener noreferrer",R.textContent=m,R.style.color="inherit",R.style.textDecoration="none",d.appendChild(R)}else d.textContent=m}let Ye=Vh({config:o,showClose:F()}),{wrapper:xe,panel:X,pillRoot:dt}=Ye.shell,$e=Ye.panelElements,{container:Ce,body:be,messagesWrapper:et,suggestions:Lt,textarea:Z,sendButton:Ue,sendButtonWrapper:Sr,composerForm:yt,statusText:xr,introTitle:Ao,introSubtitle:Mo,closeButton:P,iconHolder:ee,headerTitle:Me,headerSubtitle:He,header:Le,footer:Be,actionsRow:Ge,leftActions:at,rightActions:Pt}=$e,se=$e.setSendButtonMode,N=$e.micButton,ye=$e.micButtonWrapper,Oe=$e.attachmentButton,bt=$e.attachmentButtonWrapper,Qe=$e.attachmentInput,Wt=$e.attachmentPreviewsContainer;Ce.classList.add("persona-relative"),be.classList.add("persona-relative");let At=12,gt=()=>{var d;return(d=Ae.label)!=null?d:""},kt=()=>{var d;return(d=Ae.iconName)!=null?d:"arrow-down"},Xt=()=>Ae.enabled!==!1,Ot=()=>{var d;return(d=ne.mode)!=null?d:"anchor-top"},tr=()=>Ot()==="follow"||Ot()==="anchor-top"&&Fo,To=()=>{var d;return(d=ne.anchorTopOffset)!=null?d:16},zo=()=>{var d;return(d=ne.restorePosition)!=null?d:"bottom"},lo=()=>ne.pauseOnInteraction===!0,co=()=>ne.showActivityWhilePinned!==!1,dn=()=>ne.announce===!0,$t=w("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");$t.type="button",$t.style.display="none",$t.setAttribute("data-persona-scroll-to-bottom","true");let po=w("span","persona-flex persona-items-center"),jo=w("span",""),Hr=w("span","");Hr.setAttribute("data-persona-scroll-to-bottom-count",""),Hr.style.display="none",$t.append(po,jo,Hr),Ce.appendChild($t);let Rr=w("div","persona-stream-anchor-spacer");Rr.setAttribute("aria-hidden","true"),Rr.setAttribute("data-persona-anchor-spacer",""),Rr.style.flexShrink="0",Rr.style.pointerEvents="none",Rr.style.height="0px",be.appendChild(Rr);let Br=w("div","persona-sr-only");Br.setAttribute("aria-live","polite"),Br.setAttribute("aria-atomic","true"),Br.setAttribute("role","status"),Br.setAttribute("data-persona-live-region",""),Object.assign(Br.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Ce.appendChild(Br);let uo=null,Eo=null,cn=d=>{!dn()||!d||(Eo=d,uo===null&&(uo=setTimeout(()=>{uo=null,Eo&&dn()&&(Br.textContent=Eo),Eo=null},400)))},Xr=()=>{let m=Be.style.display==="none"?0:Be.offsetHeight;$t.style.bottom=`${m+At}px`};Xr();let pn=()=>{let d=!!gt();$t.setAttribute("aria-label",gt()||"Jump to latest"),$t.title=gt(),$t.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false"),po.innerHTML="";let m=ge(kt(),"14px","currentColor",2);m?(po.appendChild(m),po.style.display=""):po.style.display="none",jo.textContent=gt(),jo.style.display=d?"":"none"};pn();let vt=null,ko=null,Lo=n.find(d=>d.renderHeader);if(Lo!=null&&Lo.renderHeader){let d=Lo.renderHeader({config:o,defaultRenderer:()=>{let m=sn({config:o,showClose:F()});return pa(Ce,m,o),m.header},onClose:()=>Ut(!1,"user")});if(d){let m=Ce.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(d),Le=d,Ye.header.element=d)}}let Go=()=>{var m,h,C,R;if(!j)return;if(K=!0,!Ne&&j&&(Ne=ix({buffer:j,getFullHistory:()=>j.getAllFromStore(),onClose:()=>fo(),config:o,plugins:n,getThroughput:()=>{var D;return(D=J==null?void 0:J.getMetric())!=null?D:{status:"idle"}}})),Ne&&(be.style.display="none",(m=Be.parentNode)==null||m.insertBefore(Ne.element,Be),Ne.update()),pt){pt.style.boxShadow=`inset 0 0 0 1.5px ${Pr.actionIconColor}`;let D=(R=(C=(h=o.features)==null?void 0:h.eventStream)==null?void 0:C.classNames)==null?void 0:R.toggleButtonActive;D&&D.split(/\s+/).forEach($=>$&&pt.classList.add($))}let d=()=>{if(!K)return;let D=Date.now();D-qe>=200&&(Ne==null||Ne.update(),qe=D),pe=requestAnimationFrame(d)};qe=0,pe=requestAnimationFrame(d),Ur(),i.emit("eventStream:opened",{timestamp:Date.now()})},fo=()=>{var d,m,h;if(K){if(K=!1,Ne&&Ne.element.remove(),be.style.display="",pt){pt.style.boxShadow="";let C=(h=(m=(d=o.features)==null?void 0:d.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;C&&C.split(/\s+/).forEach(R=>R&&pt.classList.remove(R))}pe!==null&&(cancelAnimationFrame(pe),pe=null),Ur(),i.emit("eventStream:closed",{timestamp:Date.now()})}},pt=null;if(de){let d=(Qu=(Xu=o.features)==null?void 0:Xu.eventStream)==null?void 0:Qu.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(d!=null&&d.toggleButton?" "+d.toggleButton:"");pt=w("button",m),pt.style.width="28px",pt.style.height="28px",pt.style.color=Pr.actionIconColor,pt.type="button",pt.setAttribute("aria-label","Event Stream"),pt.title="Event Stream";let h=ge("activity","18px","currentColor",1.5);h&&pt.appendChild(h);let C=$e.clearChatButtonWrapper,R=$e.closeButtonWrapper,D=C||R;D&&D.parentNode===Le?Le.insertBefore(pt,D):Le.appendChild(pt),pt.addEventListener("click",()=>{K?fo():Go()})}let _n=d=>{var R,D,$,U,_;let m=o.attachments;if(!(m!=null&&m.enabled))return;let h=(R=d.querySelector("[data-persona-composer-attachment-previews]"))!=null?R:d.querySelector(".persona-attachment-previews");if(!h){h=w("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 ie=d.querySelector("[data-persona-composer-form]");ie!=null&&ie.parentNode?ie.parentNode.insertBefore(h,ie):d.insertBefore(h,d.firstChild)}if(!((D=d.querySelector("[data-persona-composer-attachment-input]"))!=null?D:d.querySelector('input[type="file"]'))){let ie=w("input");ie.type="file",ie.setAttribute("data-persona-composer-attachment-input",""),ie.accept=(($=m.allowedTypes)!=null?$:an).join(","),ie.multiple=((U=m.maxFiles)!=null?U:4)>1,ie.style.display="none",ie.setAttribute("aria-label",(_=m.buttonTooltipText)!=null?_:"Attach files"),d.appendChild(ie)}},Po=n.find(d=>d.renderComposer);if(Po!=null&&Po.renderComposer){let d=o.composer,m=Po.renderComposer({config:o,defaultRenderer:()=>Va({config:o}).footer,onSubmit:h=>{var $;if(!q||q.isStreaming())return;let C=h.trim(),R=($=vt==null?void 0:vt.hasAttachments())!=null?$:!1;if(!C&&!R)return;Qp();let D;R&&(D=[],D.push(...vt.getContentParts()),C&&D.push(Ss(C))),q.sendMessage(C,{contentParts:D}),R&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Qe==null||Qe.click()},models:d==null?void 0:d.models,selectedModelId:d==null?void 0:d.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Ju=o.voiceRecognition)==null?void 0:Ju.enabled)===!0?()=>{ko==null||ko()}:void 0});m&&(Ye.replaceComposer(m),Be=Ye.composer.footer)}let Un=d=>{let m=(...ae)=>{for(let Y of ae){let ve=d.querySelector(Y);if(ve)return ve}return null},h=d.querySelector("[data-persona-composer-form]"),C=d.querySelector("[data-persona-composer-input]"),R=d.querySelector("[data-persona-composer-submit]"),D=d.querySelector("[data-persona-composer-mic]"),$=d.querySelector("[data-persona-composer-status]");h&&(yt=h),C&&(Z=C),R&&(Ue=R),D&&(N=D,ye=D.parentElement),$&&(xr=$);let U=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Lt=U);let _=m("[data-persona-composer-attachment-button]",".persona-attachment-button");_&&(Oe=_,bt=_.parentElement),Qe=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Wt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ie=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ie&&(Ge=ie)};_n(Be),Un(Be);let Ir=(rf=(Yu=o.layout)==null?void 0:Yu.contentMaxWidth)!=null?rf:I()?(tf=(ef=(Zu=o.launcher)==null?void 0:Zu.composerBar)==null?void 0:ef.contentMaxWidth)!=null?tf:"720px":void 0;if(Ir&&(et.style.maxWidth=Ir,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%"),Ir&&yt&&!I()&&(yt.style.maxWidth=Ir,yt.style.marginLeft="auto",yt.style.marginRight="auto"),Ir&&Lt&&!I()&&(Lt.style.maxWidth=Ir,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),Ir&&Wt&&!I()&&(Wt.style.maxWidth=Ir,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),(of=o.attachments)!=null&&of.enabled&&Qe&&Wt){vt=da.fromConfig(o.attachments),vt.setPreviewsContainer(Wt),Qe.addEventListener("change",h=>{let C=h.target;vt==null||vt.handleFileSelect(C.files),C.value=""});let d=o.attachments.dropOverlay,m=Ax(d);Ce.appendChild(m)}(()=>{var C,R;let d=(R=(C=o.layout)==null?void 0:C.slots)!=null?R:{},m=D=>{switch(D){case"body-top":return Ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return et;case"footer-top":return Lt;case"composer":return yt;case"footer-bottom":return xr;default:return null}},h=(D,$)=>{var U;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")Le.insertBefore($,Le.firstChild);else if(D==="header-right")Le.appendChild($);else{let _=Le.querySelector(".persona-flex-col");_?(U=_.parentNode)==null||U.insertBefore($,_.nextSibling):Le.appendChild($)}break;case"body-top":{let _=be.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith($):be.insertBefore($,be.firstChild);break}case"body-bottom":be.appendChild($);break;case"footer-top":Lt.replaceWith($);break;case"footer-bottom":xr.replaceWith($);break;default:break}};for(let[D,$]of Object.entries(d))if($)try{let U=$({config:o,defaultContent:()=>m(D)});U&&h(D,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,U)}})();let un=d=>{var $,U;let h=d.target.closest('button[data-expand-header="true"]');if(!h)return;let C=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!C)return;let R=C.getAttribute("data-message-id");if(!R)return;let D=h.getAttribute("data-bubble-type");if(D==="reasoning")za.has(R)?za.delete(R):za.add(R),Gh(R,C);else if(D==="tool")ja.has(R)?ja.delete(R):ja.add(R),Kh(R,C,o);else if(D==="approval"){let _=o.approval!==!1?o.approval:void 0,ie=(($=_==null?void 0:_.detailsDisplay)!=null?$:"collapsed")==="expanded",ae=(U=fa.get(R))!=null?U:ie;fa.set(R,!ae),Yh(R,C,o)}Ho.delete(R)};et.addEventListener("pointerdown",d=>{d.target.closest('button[data-expand-header="true"]')&&(d.preventDefault(),un(d))}),et.addEventListener("keydown",d=>{let m=d.target;(d.key==="Enter"||d.key===" ")&&m.closest('button[data-expand-header="true"]')&&(d.preventDefault(),un(d))}),et.addEventListener("copy",d=>{let{clipboardData:m}=d;if(!m)return;let h=et.getRootNode(),C=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!C||C.isCollapsed)return;let R=C.toString(),D=Mh(R);!D||D===R||(m.setData("text/plain",D),d.preventDefault())});let Ko=new Map,fn=null,mn="idle",qn={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Vn=(d,m)=>{let{icon:h,label:C}=qn[m];d.setAttribute("aria-label",C),d.title=C,d.setAttribute("aria-pressed",m==="idle"?"false":"true"),d.classList.toggle("persona-message-action-active",m!=="idle"),d.classList.toggle("persona-message-action-loading",m==="loading");let R=ge(h,14,"currentColor",2);R&&(d.innerHTML="",d.appendChild(R))},gn=()=>{et.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var D;let h=m.closest("[data-actions-for]"),C=(D=h==null?void 0:h.getAttribute("data-actions-for"))!=null?D:null;Vn(m,C&&C===fn?mn:"idle")})};et.addEventListener("click",d=>{var $;let h=d.target.closest(".persona-message-action-btn[data-action]");if(!h)return;d.preventDefault(),d.stopPropagation();let C=h.closest("[data-actions-for]");if(!C)return;let R=C.getAttribute("data-actions-for");if(!R)return;let D=h.getAttribute("data-action");if(D==="copy"){let _=q.getMessages().find(ie=>ie.id===R);if(_&&ot.onCopy){let ie=_.content||"";navigator.clipboard.writeText(ie).then(()=>{h.classList.add("persona-message-action-success");let ae=ge("check",14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=ge("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ae)}),ot.onCopy(_)}}else if(D==="read-aloud")q.toggleReadAloud(R);else if(D==="upvote"||D==="downvote"){let _=(($=Ko.get(R))!=null?$:null)===D,ie=D==="upvote"?"thumbs-up":"thumbs-down";if(_){Ko.delete(R),h.classList.remove("persona-message-action-active");let ae=ge(ie,14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae))}else{let ae=D==="upvote"?"downvote":"upvote",Y=C.querySelector(`[data-action="${ae}"]`);if(Y){Y.classList.remove("persona-message-action-active");let Ve=ge(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ve&&(Y.innerHTML="",Y.appendChild(Ve))}Ko.set(R,D),h.classList.add("persona-message-action-active");let ve=ge(ie,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ve)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Se=q.getMessages().find(Je=>Je.id===R);Se&&ot.onFeedback&&ot.onFeedback({type:D,messageId:Se.id,message:Se})}}}),et.addEventListener("click",d=>{let h=d.target.closest("button[data-approval-action]");if(!h)return;d.preventDefault(),d.stopPropagation();let C=h.closest(".persona-approval-bubble");if(!C)return;let R=C.getAttribute("data-message-id");if(!R)return;let D=h.getAttribute("data-approval-action");if(!D)return;let $=D==="approve"?"approved":"denied",_=q.getMessages().find(ae=>ae.id===R);if(!(_!=null&&_.approval))return;let ie=C.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),_.approval.toolType==="webmcp"?q.resolveWebMcpApproval(R,$):q.resolveApproval(_.approval,$)});let ht=null,Dr=null,Fr={artifacts:[],selectedId:null},Ar=!1,wt={current:null};et.addEventListener("click",d=>{var Y,ve,De,Se,Je;let h=d.target.closest("[data-download-artifact]");if(!h)return;d.preventDefault(),d.stopPropagation();let C=h.getAttribute("data-download-artifact");if(!C||((De=(ve=(Y=o.features)==null?void 0:Y.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:De.call(ve,{type:"download",artifactId:C}))===!0)return;let D=q.getArtifactById(C),$=D==null?void 0:D.markdown,U=(D==null?void 0:D.title)||"artifact";if(!$){let Ve=h.closest("[data-open-artifact]"),lt=Ve==null?void 0:Ve.closest("[data-message-id]"),tt=lt==null?void 0:lt.getAttribute("data-message-id");if(tt){let Ee=q.getMessages().find(ze=>ze.id===tt);if(Ee!=null&&Ee.rawContent)try{let ze=JSON.parse(Ee.rawContent);$=(Se=ze==null?void 0:ze.props)==null?void 0:Se.markdown,U=((Je=ze==null?void 0:ze.props)==null?void 0:Je.title)||U}catch{}}}if(!$)return;let _=new Blob([$],{type:"text/markdown"}),ie=URL.createObjectURL(_),ae=document.createElement("a");ae.href=ie,ae.download=`${U}.md`,ae.click(),URL.revokeObjectURL(ie)}),et.addEventListener("click",d=>{var D,$,U;let h=d.target.closest("[data-open-artifact]");if(!h)return;let C=h.getAttribute("data-open-artifact");!C||((U=($=(D=o.features)==null?void 0:D.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:U.call($,{type:"open",artifactId:C}))===!0||(d.preventDefault(),d.stopPropagation(),Ar=!1,q.selectArtifact(C),Ro())}),et.addEventListener("keydown",d=>{if(d.key!=="Enter"&&d.key!==" ")return;let m=d.target;m.hasAttribute("data-open-artifact")&&(d.preventDefault(),m.click())});let Qr=$e.composerOverlay,Jr=(d,m,h)=>{var U,_,ie,ae;let C=m.trim();if(!C||!wt.current)return;let R=(U=d.getAttribute("data-tool-call-id"))!=null?U:"",D=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:R,answer:C,answers:h.structured,values:(_=h.values)!=null?_:h.source==="multi"?C.split(", "):[C],isFreeText:D,source:h.source},bubbles:!0,composed:!0})),Ln(Qr,R);let $=wt.current.getMessages().find(Y=>{var ve;return((ve=Y.toolCall)==null?void 0:ve.id)===R});(ie=$==null?void 0:$.agentMetadata)!=null&&ie.awaitingLocalTool?wt.current.resolveAskUserQuestion($,(ae=h.structured)!=null?ae:C):wt.current.sendMessage(C)},Nr=d=>{var R;let m=wt.current;if(!m)return;let h=(R=d.getAttribute("data-tool-call-id"))!=null?R:"",C=m.getMessages().find(D=>{var $;return(($=D.toolCall)==null?void 0:$.id)===h});C&&m.persistAskUserQuestionProgress(C,{answers:ai(d,C),currentIndex:so(d)})},hn=d=>Object.entries(d).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),we=d=>{var R,D,$;if(((D=(R=o.features)==null?void 0:R.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let m=so(d),h=Ha(d);if(m>=h-1)return;let C=($=wt.current)==null?void 0:$.getMessages().find(U=>{var _;return((_=U.toolCall)==null?void 0:_.id)===d.getAttribute("data-tool-call-id")});C&&(si(d,C,o,m+1),Nr(d))};Qr.addEventListener("click",d=>{var D,$,U,_,ie,ae,Y,ve,De,Se,Je,Ve,lt,tt;let h=d.target.closest("[data-ask-user-action]");if(!h)return;let C=h.closest("[data-persona-ask-sheet-for]");if(!C)return;let R=h.getAttribute("data-ask-user-action");if(d.preventDefault(),d.stopPropagation(),R==="dismiss"){let Pe=(D=C.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Ln(Qr,Pe);let Ee=($=wt.current)==null?void 0:$.getMessages().find(ze=>{var je;return((je=ze.toolCall)==null?void 0:je.id)===Pe});(U=Ee==null?void 0:Ee.agentMetadata)!=null&&U.awaitingLocalTool&&((_=wt.current)==null||_.markAskUserQuestionResolved(Ee),(ie=wt.current)==null||ie.resolveAskUserQuestion(Ee,"(dismissed)"));return}if(R==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Ee=C.getAttribute("data-multi-select")==="true",ze=kn(C);if(ze&&Ee){let je=oa(C)[so(C)],ft=new Set(Array.isArray(je)?je:[]);ft.has(Pe)?ft.delete(Pe):ft.add(Pe),Pn(C,Array.from(ft)),Nr(C);return}if(ze){Pn(C,Pe),Nr(C),we(C);return}if(Ee){let je=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",je?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!je);let ft=C.querySelector('[data-ask-user-action="submit-multi"]');ft&&(ft.disabled=_l(C).length===0);return}Jr(C,Pe,{source:"pick",values:[Pe]});return}if(R==="submit-multi"){let Pe=_l(C);if(Pe.length===0)return;Jr(C,Pe.join(", "),{source:"multi",values:Pe});return}if(R==="open-free-text"){let Pe=C.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Ee=Pe.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus()}return}if(R==="focus-free-text"){let Pe=C.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(R==="submit-free-text"){let Pe=C.querySelector('[data-ask-free-text-input="true"]'),Ee=(ae=Pe==null?void 0:Pe.value)!=null?ae:"";if(!Ee.trim())return;if(kn(C)){Pn(C,Ee.trim()),Nr(C),we(C);return}Jr(C,Ee,{source:"free-text"});return}if(R==="next"||R==="back"){if(!wt.current)return;let Pe=(Y=C.getAttribute("data-tool-call-id"))!=null?Y:"",Ee=wt.current.getMessages().find(Ie=>{var Re;return((Re=Ie.toolCall)==null?void 0:Re.id)===Pe});if(!Ee)return;let ze=C.querySelector('[data-ask-free-text-input="true"]'),je=(De=(ve=ze==null?void 0:ze.value)==null?void 0:ve.trim())!=null?De:"";if(je){let Ie=oa(C)[so(C)];(typeof Ie!="string"||Ie!==je)&&Pn(C,je)}let ft=R==="next"?1:-1,B=so(C)+ft;si(C,Ee,o,B),Nr(C);return}if(R==="submit-all"){if(!wt.current)return;let Pe=(Se=C.getAttribute("data-tool-call-id"))!=null?Se:"",Ee=wt.current.getMessages().find(Ie=>{var Re;return((Re=Ie.toolCall)==null?void 0:Re.id)===Pe});if(!Ee)return;let ze=C.querySelector('[data-ask-free-text-input="true"]'),je=(Ve=(Je=ze==null?void 0:ze.value)==null?void 0:Je.trim())!=null?Ve:"";je&&Pn(C,je);let ft=ai(C,Ee);wt.current.persistAskUserQuestionProgress(Ee,{answers:ft,currentIndex:so(C)});let B=hn(ft);Jr(C,B||"(submitted)",{source:"submit-all",structured:ft});return}if(R==="skip"){if(!wt.current)return;let Pe=(lt=C.getAttribute("data-tool-call-id"))!=null?lt:"",Ee=wt.current.getMessages().find(Re=>{var fe;return((fe=Re.toolCall)==null?void 0:fe.id)===Pe});if(!Ee)return;let ze=kn(C),je=so(C),ft=Ha(C),B=je>=ft-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Ln(Qr,Pe),(tt=Ee.agentMetadata)!=null&&tt.awaitingLocalTool&&(wt.current.markAskUserQuestionResolved(Ee),wt.current.resolveAskUserQuestion(Ee,"(dismissed)"));return}Pn(C,"");let Ie=C.querySelector('[data-ask-free-text-input="true"]');if(Ie&&(Ie.value=""),B){let Re=ai(C,Ee),fe=hn(Re);Jr(C,fe||"(skipped)",{source:"submit-all",structured:Re});return}si(C,Ee,o,je+1),Nr(C);return}}),Qr.addEventListener("keydown",d=>{var D;if(d.key!=="Enter")return;let h=d.target;if(!((D=h.matches)!=null&&D.call(h,'[data-ask-free-text-input="true"]')))return;let C=h.closest("[data-persona-ask-sheet-for]");if(!C)return;d.preventDefault();let R=h.value;if(R.trim()){if(kn(C)){Pn(C,R.trim()),Nr(C),we(C);return}Jr(C,R,{source:"free-text"})}});let Xo=d=>{if(!/^[1-9]$/.test(d.key)||d.metaKey||d.ctrlKey||d.altKey)return;let m=d.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=Qr.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let C=Number(d.key),D=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[C-1];D&&(d.preventDefault(),D.click())};document.addEventListener("keydown",Xo);let Yr=null,_t=null,Zr=null,Qo=null,Ja=()=>{};function ya(){Qo==null||Qo(),Qo=null}let Ya=()=>{var $;if(!Yr||!_t)return;let d=e.classList.contains("persona-artifact-appearance-seamless"),h=(($=e.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!d||e.classList.contains("persona-artifact-narrow-host")||h){_t.style.removeProperty("position"),_t.style.removeProperty("left"),_t.style.removeProperty("top"),_t.style.removeProperty("bottom"),_t.style.removeProperty("width"),_t.style.removeProperty("z-index");return}let C=Yr.firstElementChild;if(!C||C===_t)return;let R=10;_t.style.position="absolute",_t.style.top="0",_t.style.bottom="0",_t.style.width=`${R}px`,_t.style.zIndex="5";let D=C.offsetWidth-R/2;_t.style.left=`${Math.max(0,D)}px`},$n=()=>{},Ro=()=>{var h,C,R,D,$;if(!ht||!io(o))return;al(e,o),sl(e,o),$n();let d=(D=(R=(C=(h=o.features)==null?void 0:h.artifacts)==null?void 0:C.layout)==null?void 0:R.narrowHostMaxWidth)!=null?D:520,m=X.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=d),ht.update(Fr),Ar?(ht.setMobileOpen(!1),ht.element.classList.add("persona-hidden"),($=ht.backdrop)==null||$.classList.add("persona-hidden")):Fr.artifacts.length>0&&(ht.element.classList.remove("persona-hidden"),ht.setMobileOpen(!0)),Ja()};if(io(o)){X.style.position="relative";let d=w("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=w("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");d.appendChild(Ce),ht=cx(o,{onSelect:h=>{var C;return(C=wt.current)==null?void 0:C.selectArtifact(h)},onDismiss:()=>{Ar=!0,Ro()}}),ht.element.classList.add("persona-hidden"),Yr=m,m.appendChild(d),m.appendChild(ht.element),ht.backdrop&&X.appendChild(ht.backdrop),X.appendChild(m),Ja=()=>{var C,R,D,$;if(!Yr||!ht)return;if(!(((D=(R=(C=o.features)==null?void 0:C.artifacts)==null?void 0:R.layout)==null?void 0:D.resizable)===!0)){Zr==null||Zr(),Zr=null,ya(),_t&&(_t.remove(),_t=null),ht.element.style.removeProperty("width"),ht.element.style.removeProperty("maxWidth");return}if(!_t){let U=w("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let _=e.ownerDocument,ie=($=_.defaultView)!=null?$:window,ae=Y=>{var lt,tt;if(!ht||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||ie.innerWidth<=640)return;Y.preventDefault(),ya();let ve=Y.clientX,De=ht.element.getBoundingClientRect().width,Se=(tt=(lt=o.features)==null?void 0:lt.artifacts)==null?void 0:tt.layout,Je=Pe=>{let Ee=Yr.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),je=ze?0:mx(Yr,ie),ft=ze?0:U.getBoundingClientRect().width||6,B=De-(Pe.clientX-ve),Ie=gx(B,Ee,je,ft,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);ht.element.style.width=`${Ie}px`,ht.element.style.maxWidth="none",Ya()},Ve=()=>{_.removeEventListener("pointermove",Je),_.removeEventListener("pointerup",Ve),_.removeEventListener("pointercancel",Ve),Qo=null;try{U.releasePointerCapture(Y.pointerId)}catch{}};Qo=Ve,_.addEventListener("pointermove",Je),_.addEventListener("pointerup",Ve),_.addEventListener("pointercancel",Ve);try{U.setPointerCapture(Y.pointerId)}catch{}};U.addEventListener("pointerdown",ae),_t=U,Yr.insertBefore(U,ht.element),Zr=()=>{U.removeEventListener("pointerdown",ae)}}if(_t){let U=Fr.artifacts.length>0&&!Ar;_t.classList.toggle("persona-hidden",!U),Ya()}},$n=()=>{var ie,ae,Y,ve,De,Se,Je,Ve,lt,tt,Pe,Ee,ze,je;if(!T||!ht||((ae=(ie=o.launcher)==null?void 0:ie.sidebarMode)!=null?ae:!1)||nr(o)&&Gr(o).reveal==="emerge")return;let C=(Y=e.ownerDocument.defaultView)!=null?Y:window,R=(De=(ve=o.launcher)==null?void 0:ve.mobileFullscreen)!=null?De:!0,D=(Je=(Se=o.launcher)==null?void 0:Se.mobileBreakpoint)!=null?Je:640;if(R&&C.innerWidth<=D||!fx(o,T))return;let $=(tt=(lt=(Ve=o.launcher)==null?void 0:Ve.width)!=null?lt:o.launcherWidth)!=null?tt:jr,U=(je=(ze=(Ee=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Ee.layout)==null?void 0:ze.expandedPanelWidth)!=null?je:"min(720px, calc(100vw - 24px))";Fr.artifacts.length>0&&!Ar?(X.style.width=U,X.style.maxWidth=U):(X.style.width=$,X.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Dr=new ResizeObserver(()=>{Ro()}),Dr.observe(X))}else X.appendChild(Ce),I()&&dt&&($e.peekBanner&&dt.appendChild($e.peekBanner),dt.appendChild(Be));e.appendChild(xe),dt&&e.appendChild(dt);let xn=()=>{var Ie,Re,fe,Ht,Rt,jt,mt,qt,qr,Zt,Ke,Mt,or,no,Vr,Xn,Qn,Ea,ka,Gt,Jn,Sn,An,tn,Yn,yo,Oo,Xe;if(I()){X.style.width="100%",X.style.maxWidth="100%";let Bt=(Re=(Ie=o.launcher)==null?void 0:Ie.composerBar)!=null?Re:{},zt=xe.dataset.state==="expanded",Dt=(fe=Bt.expandedSize)!=null?fe:"anchored";if(!(zt&&Dt!=="fullscreen")){Ce.style.background="",Ce.style.border="",Ce.style.borderRadius="",Ce.style.overflow="",Ce.style.boxShadow="";return}let Tt=(Rt=(Ht=o.theme)==null?void 0:Ht.components)==null?void 0:Rt.panel,Nt=Ua(o),fr=(gr,ao)=>{var Mn;return gr==null||gr===""?ao:(Mn=Oa(Nt,gr))!=null?Mn:gr},$r="1px solid var(--persona-border)",_o="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Ce.style.background="var(--persona-surface, #ffffff)",Ce.style.border=fr(Tt==null?void 0:Tt.border,$r),Ce.style.borderRadius=fr(Tt==null?void 0:Tt.borderRadius,mr),Ce.style.boxShadow=fr(Tt==null?void 0:Tt.shadow,_o),Ce.style.overflow="hidden";return}let d=nr(o),m=(mt=(jt=o.launcher)==null?void 0:jt.sidebarMode)!=null?mt:!1,h=d||m||((qr=(qt=o.launcher)==null?void 0:qt.fullHeight)!=null?qr:!1),C=((Zt=o.launcher)==null?void 0:Zt.enabled)===!1,R=(Mt=(Ke=o.theme)==null?void 0:Ke.components)==null?void 0:Mt.panel,D=Ua(o),$=(Bt,zt)=>{var Dt;return Bt==null||Bt===""?zt:(Dt=Oa(D,Bt))!=null?Dt:Bt},U=(or=e.ownerDocument.defaultView)!=null?or:window,_=(Vr=(no=o.launcher)==null?void 0:no.mobileFullscreen)!=null?Vr:!0,ie=(Qn=(Xn=o.launcher)==null?void 0:Xn.mobileBreakpoint)!=null?Qn:640,ae=U.innerWidth<=ie,Y=_&&ae&&T,ve=(ka=(Ea=o.launcher)==null?void 0:Ea.position)!=null?ka:"bottom-left",De=ve==="bottom-left"||ve==="top-left",Se=(Jn=(Gt=o.launcher)==null?void 0:Gt.zIndex)!=null?Jn:Cr,Je=m||Y?"none":"1px solid var(--persona-border)",Ve=Y?"none":m?De?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";d&&!Y&&(Ve="none",Je="none");let lt=m||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",tt=$(R==null?void 0:R.border,Je),Pe=$(R==null?void 0:R.shadow,Ve),Ee=$(R==null?void 0:R.borderRadius,lt),ze=be.scrollTop;e.style.cssText="",xe.style.cssText="",X.style.cssText="",Ce.style.cssText="",be.style.cssText="",Be.style.cssText="",K&&(be.style.display="none");let je=()=>{var zt;if(ze<=0)return;((zt=be.ownerDocument.defaultView)!=null?zt:window).requestAnimationFrame(()=>{if(be.scrollTop===ze)return;let Dt=be.scrollHeight-be.clientHeight;Dt<=0||(be.scrollTop=Math.min(ze,Dt))})};if(Y){xe.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"),xe.style.cssText=`
36
36
  position: fixed !important;
37
37
  inset: 0 !important;
38
38
  width: 100% !important;
@@ -42,7 +42,7 @@ _Details: ${r.message}_`:o}var ys=e=>({isError:!0,content:[{type:"text",text:e}]
42
42
  padding: 0 !important;
43
43
  display: flex !important;
44
44
  flex-direction: column !important;
45
- z-index: ${we} !important;
45
+ z-index: ${Se} !important;
46
46
  background-color: var(--persona-surface, #ffffff) !important;
47
47
  `,X.style.cssText=`
48
48
  position: relative !important;
@@ -57,7 +57,7 @@ _Details: ${r.message}_`:o}var ys=e=>({isError:!0,content:[{type:"text",text:e}]
57
57
  padding: 0 !important;
58
58
  box-shadow: none !important;
59
59
  border-radius: 0 !important;
60
- `,ve.style.cssText=`
60
+ `,Ce.style.cssText=`
61
61
  display: flex !important;
62
62
  flex-direction: column !important;
63
63
  flex: 1 1 0% !important;
@@ -68,19 +68,19 @@ _Details: ${r.message}_`:o}var ys=e=>({isError:!0,content:[{type:"text",text:e}]
68
68
  overflow: hidden !important;
69
69
  border-radius: 0 !important;
70
70
  border: none !important;
71
- `,Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",He.style.flexShrink="0",H=!0,je();return}let mt=(hn=(gn=o==null?void 0:o.launcher)==null?void 0:gn.width)!=null?hn:o==null?void 0:o.launcherWidth,B=mt!=null?mt:Jr;if(!g&&!d)C&&h?(X.style.width="100%",X.style.maxWidth="100%"):(X.style.width=B,X.style.maxWidth=B);else if(d)if(Qr(o).reveal==="emerge"){let jt=Qr(o).width;X.style.width=jt,X.style.maxWidth=jt}else X.style.width="100%",X.style.maxWidth="100%";if(ye(),X.style.boxShadow=Le,X.style.borderRadius=Te,ve.style.border=tt,ve.style.borderRadius=Te,d&&!Y&&(R==null?void 0:R.border)===void 0&&(ve.style.border="none",Qr(o).side==="right"?ve.style.borderLeft="1px solid var(--persona-border)":ve.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",C&&(e.style.width="100%"),ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.height="100%",C&&(ge.style.overflow="hidden"),X.style.display="flex",X.style.flexDirection="column",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.maxHeight="100%",X.style.height="100%",X.style.overflow="hidden",ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.overflow="hidden",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",He.style.flexShrink="0"),ge.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!C&&!d&&((Xo=wo[be])!=null?Xo:wo["bottom-right"]).split(" ").forEach(jt=>ge.classList.add(jt)),g){let Ft=(ho=(Vn=o.launcher)==null?void 0:Vn.sidebarWidth)!=null?ho:"420px";ge.style.cssText=`
71
+ `,be.style.flex="1 1 0%",be.style.minHeight="0",be.style.overflowY="auto",Be.style.flexShrink="0",H=!0,je();return}let ft=(An=(Sn=o==null?void 0:o.launcher)==null?void 0:Sn.width)!=null?An:o==null?void 0:o.launcherWidth,B=ft!=null?ft:jr;if(!m&&!d)C&&h?(X.style.width="100%",X.style.maxWidth="100%"):(X.style.width=B,X.style.maxWidth=B);else if(d)if(Gr(o).reveal==="emerge"){let zt=Gr(o).width;X.style.width=zt,X.style.maxWidth=zt}else X.style.width="100%",X.style.maxWidth="100%";if($n(),X.style.boxShadow=Pe,X.style.borderRadius=Ee,Ce.style.border=tt,Ce.style.borderRadius=Ee,d&&!Y&&(R==null?void 0:R.border)===void 0&&(Ce.style.border="none",Gr(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",C&&(e.style.width="100%"),xe.style.display="flex",xe.style.flexDirection="column",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.maxHeight="100%",xe.style.height="100%",C&&(xe.style.overflow="hidden"),X.style.display="flex",X.style.flexDirection="column",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.maxHeight="100%",X.style.height="100%",X.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",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.overflowY="auto",Be.style.flexShrink="0"),xe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!C&&!d&&((tn=So[ve])!=null?tn:So["bottom-right"]).split(" ").forEach(zt=>xe.classList.add(zt)),m){let Bt=(yo=(Yn=o.launcher)==null?void 0:Yn.sidebarWidth)!=null?yo:"420px";xe.style.cssText=`
72
72
  position: fixed !important;
73
73
  top: 0 !important;
74
74
  bottom: 0 !important;
75
- width: ${Ft} !important;
75
+ width: ${Bt} !important;
76
76
  height: 100vh !important;
77
77
  max-height: 100vh !important;
78
78
  margin: 0 !important;
79
79
  padding: 0 !important;
80
80
  display: flex !important;
81
81
  flex-direction: column !important;
82
- z-index: ${we} !important;
83
- ${Be?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
82
+ z-index: ${Se} !important;
83
+ ${De?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
84
84
  `,X.style.cssText=`
85
85
  position: relative !important;
86
86
  display: flex !important;
@@ -92,9 +92,9 @@ _Details: ${r.message}_`:o}var ys=e=>({isError:!0,content:[{type:"text",text:e}]
92
92
  min-height: 0 !important;
93
93
  margin: 0 !important;
94
94
  padding: 0 !important;
95
- box-shadow: ${Le} !important;
96
- border-radius: ${Te} !important;
97
- `,X.style.setProperty("width","100%","important"),X.style.setProperty("max-width","100%","important"),ve.style.cssText=`
95
+ box-shadow: ${Pe} !important;
96
+ border-radius: ${Ee} !important;
97
+ `,X.style.setProperty("width","100%","important"),X.style.setProperty("max-width","100%","important"),Ce.style.cssText=`
98
98
  display: flex !important;
99
99
  flex-direction: column !important;
100
100
  flex: 1 1 0% !important;
@@ -103,29 +103,29 @@ _Details: ${r.message}_`:o}var ys=e=>({isError:!0,content:[{type:"text",text:e}]
103
103
  min-height: 0 !important;
104
104
  max-height: 100% !important;
105
105
  overflow: hidden !important;
106
- border-radius: ${Te} !important;
106
+ border-radius: ${Ee} !important;
107
107
  border: ${tt} !important;
108
- `,He.style.cssText=`
108
+ `,Be.style.cssText=`
109
109
  flex-shrink: 0 !important;
110
110
  border-top: none !important;
111
111
  padding: 8px 16px 12px 16px !important;
112
- `}if(!C&&!d){let Ft="max-height: -moz-available !important; max-height: stretch !important;",jt=g?"":"padding-top: 1.25em !important;",Nt=g?"":`z-index: ${(Xe=(Bo=o.launcher)==null?void 0:Bo.zIndex)!=null?Xe:Sr} !important;`;ge.style.cssText+=Ft+jt+Nt}je()};Eo(),Tn(e,o),el(e,o),tl(e,o);let ut=[];ut.push(()=>{document.removeEventListener("keydown",cn)});let ar=null,sr=null;ut.push(()=>{ar==null||ar(),ar=null,sr==null||sr(),sr=null}),Or&&ut.push(()=>{Or==null||Or.disconnect(),Or=null}),ut.push(()=>{Tr==null||Tr(),Tr=null,Vo(),It&&(It.remove(),It=null),xt==null||xt.element.style.removeProperty("width"),xt==null||xt.element.style.removeProperty("maxWidth")}),le&&ut.push(()=>{ce!==null&&(cancelAnimationFrame(ce),ce=null),Fe==null||Fe.destroy(),Fe=null,j==null||j.destroy(),j=null,Ee=null});let ko=null,$a=()=>{ko&&(ko(),ko=null),o.colorScheme==="auto"&&(ko=Ii(()=>{Tn(e,o)}))};$a(),ut.push(()=>{ko&&(ko(),ko=null)}),ut.push(s);let zo=(Vu=o.features)==null?void 0:Vu.streamAnimation;if(zo!=null&&zo.type&&zo.type!=="none"){let d=Ss(zo.type,zo.plugins);d&&(Kc(d,e),ut.push(()=>Ch(e)))}let Bn=qh(Pt),Lo=null,q,ca=d=>{var C,R;if(!q)return;let g=d!=null?d:q.getMessages(),h=((R=(C=o.features)==null?void 0:C.suggestReplies)==null?void 0:R.enabled)!==!1?oi(g):null;h?Bn.render(h,q,Z,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(N=>N.role==="user")?Bn.render([],q,Z,g):Bn.render(o.suggestionChips,q,Z,g,o.suggestionChipsConfig)},Po=!1,Ro=fh(),$o=new Map,Io=new Map,fo=new Map,pa=0,Fs=jn()!==null,Vr=Bi(),zr=0,mo=null,go=!1,Dn=!1,jo=0,vr=null,Wo=null,ua=!1,Fn=!1,fa=null,Ns=4,ma=24,Os=80,ga=new Map,ct={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ja=($u=(zu=o.voiceRecognition)==null?void 0:zu.autoResume)!=null?$u:!1,no=d=>{i.emit("voice:state",{active:ct.active,source:d,timestamp:Date.now()})},Hr=()=>{b(d=>({...d,voiceState:{active:ct.active,timestamp:Date.now(),manuallyDeactivated:ct.manuallyDeactivated}}))},_s=()=>{var C,R;if(((C=o.voiceRecognition)==null?void 0:C.enabled)===!1)return;let d=hp(p.voiceState),g=!!d.active,h=Number((R=d.timestamp)!=null?R:0);ct.manuallyDeactivated=!!d.manuallyDeactivated,g&&Date.now()-h<r0&&setTimeout(()=>{var N,z;ct.active||(ct.manuallyDeactivated=!1,((z=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:z.type)==="runtype"?q.toggleVoice().then(()=>{ct.active=q.isVoiceActive(),no("restore"),q.isVoiceActive()&&ba()}):qs("restore"))},1e3)},ha=()=>q?ix(q.getMessages()).filter(d=>!d.__skipPersist):[];function Ze(d){if(!(l!=null&&l.save))return;let h={messages:d?ix(d):q?ha():[],metadata:p,artifacts:_r.artifacts,selectedArtifactId:_r.selectedId};try{let C=l.save(h);C instanceof Promise&&C.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(C){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)}}let k=null,$=()=>ge.querySelector("#persona-scroll-container")||Me,V=()=>{k!==null&&(cancelAnimationFrame(k),k=null),go=!1},G=()=>{mo!==null&&(cancelAnimationFrame(mo),mo=null),Dn=!1,V()},xe=()=>{jo>0?(br.textContent=String(jo),br.style.display="",qt.setAttribute("aria-label",`${gt()||"Jump to latest"} (${jo} new)`)):(br.textContent="",br.style.display="none",qt.setAttribute("aria-label",gt()||"Jump to latest"))},Oe=()=>{jo!==0&&(jo=0,xe())},ft=()=>_t()==="follow"?!Vr.isFollowing():!ta(Me,ma),nt=()=>{if(!Jt()||K){qt.parentNode&&qt.remove(),qt.style.display="none";return}qt.parentNode!==ve&&ve.appendChild(qt),eo();let g=en(Me)>0&&ft();g||Oe(),qt.style.display=g?"":"none"},Ga=()=>{Vr.pause()&&(G(),nt())},Br=()=>{Vr.resume(),Oe(),nt()},pr=(d=!1)=>{_t()==="follow"&&Vr.isFollowing()&&(!d&&!Po||(mo!==null&&(cancelAnimationFrame(mo),mo=null),Dn=!0,mo=requestAnimationFrame(()=>{mo=null,Dn=!1,Vr.isFollowing()&&Nn($(),d?220:140)})))},ur=(d,g,h,C=()=>!0)=>{let R=d.scrollTop,N=g(),z=N-R;V();let U=performance.now();go=!0;let _=ne=>1-Math.pow(1-ne,3),oe=ne=>{if(!C()){V();return}let Y=g();Y!==N&&(N=Y,z=N-R);let be=ne-U,Be=Math.min(be/h,1),we=_(Be),Qe=R+z*we;d.scrollTop=Qe,zr=d.scrollTop,Be<1?k=requestAnimationFrame(oe):(d.scrollTop=N,zr=d.scrollTop,k=null,go=!1)};k=requestAnimationFrame(oe)},Nn=(d,g=500)=>{let h=en(d)-d.scrollTop;if(Math.abs(h)<1){zr=d.scrollTop;return}if(Math.abs(h)>=Os){V(),go=!0,d.scrollTop=en(d),zr=d.scrollTop,go=!1;return}ur(d,()=>en(d),g,()=>Vr.isFollowing())},Go=()=>{let d=$();go=!0,d.scrollTop=en(d),zr=d.scrollTop,go=!1,nt()},Er=d=>{Rr.style.height=`${Math.max(0,Math.round(d))}px`,vr&&(vr.spacerHeight=Math.max(0,d))},hr=()=>{Wo!==null&&(cancelAnimationFrame(Wo),Wo=null),V(),vr=null,Rr.style.height="0px"},$r=d=>{Wo!==null&&cancelAnimationFrame(Wo),Wo=requestAnimationFrame(()=>{var oe;Wo=null;let g=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(d):d.replace(/"/g,'\\"'),h=Me.querySelector(`[data-message-id="${g}"]`);if(!h)return;let C=0,R=h;for(;R&&R!==Me;)C+=R.offsetTop,R=R.offsetParent;let N=(oe=vr==null?void 0:vr.spacerHeight)!=null?oe:0,z=Me.scrollHeight-N,{targetScrollTop:U,spacerHeight:_}=yh({anchorOffsetTop:C,topOffset:Fr(),viewportHeight:Me.clientHeight,contentHeight:z});vr={initialSpacerHeight:_,contentHeightAtAnchor:z,spacerHeight:_},Er(_),ur(Me,()=>U,220)})},jx=()=>{if(_t()==="follow"){if(!Vr.isFollowing()||ta(Me,1))return;pr(!Po);return}if(vr&&vr.initialSpacerHeight>0){let d=Me.scrollHeight-vr.spacerHeight,g=bh({initialSpacerHeight:vr.initialSpacerHeight,contentHeightAtAnchor:vr.contentHeightAtAnchor,currentContentHeight:d});g!==vr.spacerHeight&&Er(g)}nt()},Gx=d=>{let g=_t();g==="follow"?(Br(),pr(!0)):g==="anchor-top"&&$r(d)},Kx=d=>{let g=new Map;d.forEach(h=>{let C=ga.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!C&&h.role==="assistant"&&(i.emit("assistant:message",h),!Fn&&_t()!=="anchor-top"&&ft()&&(jo+=1,xe(),nt())),h.role==="assistant"&&(C!=null&&C.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(C?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),ga.clear(),g.forEach((h,C)=>{ga.set(C,h)})},Xx=(d,g,h)=>{var tt,Le,Te,$e,je,mt;let C=document.createElement("div"),N=(()=>{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})(),z=(B,Re)=>Re==null?!1:typeof Re=="string"?(B.textContent=Re,!0):(B.appendChild(Re),!0),U=new Set,_=new Set,oe=n.some(B=>B.renderAskUserQuestion),ne=[],Y=[],be=o.enableComponentStreaming!==!1,Be=o.approval!==!1,we=[];if(g.forEach(B=>{var Ke,Tt,or,io,Gr,_n,Un,wa,Ca,Kt,qn,gn,hn,Xo,Vn,ho,Bo;U.add(B.id);let Re=oe&&Jo(B),Pe=Be&&B.variant==="approval"&&!!B.approval,ue=!Re&&B.role==="assistant"&&!B.variant&&be&&al(B);if(!Pe&&fo.has(B.id)){let Xe=d.querySelector(`#wrapper-${B.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime"),fo.delete(B.id)}if(!ue&&Io.has(B.id)){let Xe=d.querySelector(`#wrapper-${B.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime"),Io.delete(B.id)}let Dt=Jo(B)?`:${(Ke=B.agentMetadata)!=null&&Ke.askUserQuestionAnswered?"a":"u"}:${(Tt=B.agentMetadata)!=null&&Tt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Wt=uh(B,pa)+Dt,Gt=Re||Pe||ue?null:mh(Ro,B.id,Wt);if(Gt){C.appendChild(Gt.cloneNode(!0)),Jo(B)&&((or=B.toolCall)!=null&&or.id)&&((io=B.agentMetadata)==null?void 0:io.awaitingLocalTool)===!0&&!((Gr=B.agentMetadata)!=null&&Gr.askUserQuestionAnswered)&&(_.add(B.toolCall.id),La(B,o,ze.composerOverlay));return}let ht=null,zt=n.find(Xe=>!!(B.variant==="reasoning"&&Xe.renderReasoning||B.variant==="tool"&&Xe.renderToolCall||!B.variant&&Xe.renderMessage)),jr=(_n=o.layout)==null?void 0:_n.messages;if(Jo(B)&&((Un=B.agentMetadata)==null?void 0:Un.askUserQuestionAnswered)===!0){$o.delete(B.id);let Xe=d.querySelector(`#wrapper-${B.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime");return}if(cs(B)&&((Ca=(wa=o.features)==null?void 0:wa.suggestReplies)==null?void 0:Ca.enabled)!==!1)return;if(Jo(B)&&((qn=(Kt=o.features)==null?void 0:Kt.askUserQuestion)==null?void 0:qn.enabled)!==!1){let Xe=n.find(Ft=>typeof Ft.renderAskUserQuestion=="function");if(Xe&&Ct.current){let Ft=$o.get(B.id),jt=Ft!==Wt,Nt=null;if(jt){let{payload:Ut,complete:fr}=Qo(B),Kr=B.id,Do=()=>{var mr;return(mr=Ct.current)==null?void 0:mr.getMessages().find(gr=>gr.id===Kr)};Nt=Xe.renderAskUserQuestion({message:B,payload:Ut,complete:fr,resolve:mr=>{var lo;let gr=Do();gr&&((lo=Ct.current)==null||lo.resolveAskUserQuestion(gr,mr))},dismiss:()=>{var gr,lo,xn;let mr=Do();(gr=mr==null?void 0:mr.agentMetadata)!=null&&gr.awaitingLocalTool&&((lo=Ct.current)==null||lo.markAskUserQuestionResolved(mr),(xn=Ct.current)==null||xn.resolveAskUserQuestion(mr,"(dismissed)"))},config:o})}let Xt=Ft!=null;if(jt&&Nt===null&&!Xt){((gn=B.agentMetadata)==null?void 0:gn.awaitingLocalTool)===!0&&!((hn=B.agentMetadata)!=null&&hn.askUserQuestionAnswered)&&(_.add(B.toolCall.id),La(B,o,ze.composerOverlay));return}let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${B.id}`,Et.setAttribute("data-wrapper-id",B.id),Et.setAttribute("data-ask-plugin-stub","true"),Et.setAttribute("data-preserve-runtime","true"),C.appendChild(Et),ne.push({messageId:B.id,fingerprint:Wt,bubble:Nt});return}else{((Xo=B.agentMetadata)==null?void 0:Xo.awaitingLocalTool)===!0&&!((Vn=B.agentMetadata)!=null&&Vn.askUserQuestionAnswered)&&(_.add(B.toolCall.id),La(B,o,ze.composerOverlay));return}}else if(Pe){let Xe=(ho=n.find(Xt=>typeof Xt.renderApproval=="function"))!=null?ho:a,jt=fo.get(B.id)!==Wt,Nt=null;if(jt&&(Xe!=null&&Xe.renderApproval)){let Xt=B.id,Et=(Ut,fr)=>{var Do,mr,gr;let Kr=(Do=Ct.current)==null?void 0:Do.getMessages().find(lo=>lo.id===Xt);Kr!=null&&Kr.approval&&(Kr.approval.toolType==="webmcp"?(mr=Ct.current)==null||mr.resolveWebMcpApproval(Kr.id,Ut):(gr=Ct.current)==null||gr.resolveApproval(Kr.approval,Ut,fr))};Nt=Xe.renderApproval({message:B,defaultRenderer:()=>Yi(B,o),config:o,approve:Ut=>Et("approved",Ut),deny:Ut=>Et("denied",Ut)})}if(jt&&Nt===null){let Xt=d.querySelector(`#wrapper-${B.id}`);Xt==null||Xt.removeAttribute("data-preserve-runtime"),fo.delete(B.id),ht=Yi(B,o)}else{let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${B.id}`,Xt.setAttribute("data-wrapper-id",B.id),Xt.setAttribute("data-approval-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),C.appendChild(Xt),we.push({messageId:B.id,fingerprint:Wt,bubble:Nt});return}}else if(zt)if(B.variant==="reasoning"&&B.reasoning&&zt.renderReasoning){if(!Ae)return;ht=zt.renderReasoning({message:B,defaultRenderer:()=>sp(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&zt.renderToolCall){if(!Ie)return;ht=zt.renderToolCall({message:B,defaultRenderer:()=>lp(B,o),config:o})}else zt.renderMessage&&(ht=zt.renderMessage({message:B,defaultRenderer:()=>{let Xe=Na(B,h,jr,o.messageActions,ot,{loadingIndicatorRenderer:N,widgetConfig:o});return B.role!=="user"&&fp(Xe,B,o,q),Xe},config:o}));if(!ht&&ue){let Xe=sl(B);if(Xe){let Ft=Io.get(B.id),jt=Ft!==Wt,Nt=o.wrapComponentDirectiveInBubble!==!1,Xt=null;if(jt){let Et=nl(Xe,{config:o,message:B,transform:h});if(Et)if(Nt){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${B.id}`,Ut.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let fr=document.createElement("div");fr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",fr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Ut.appendChild(fr)}Ut.appendChild(Et),Xt=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${B.id}`,Ut.setAttribute("data-message-id",B.id),Ut.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let fr=document.createElement("div");fr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",fr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Ut.appendChild(fr)}Ut.appendChild(Et),Xt=Ut}}if(Xt||Ft!=null){let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${B.id}`,Et.setAttribute("data-wrapper-id",B.id),Et.setAttribute("data-component-directive-stub","true"),Et.setAttribute("data-preserve-runtime","true"),Nt||Et.classList.add("persona-w-full"),C.appendChild(Et),Y.push({messageId:B.id,fingerprint:Wt,bubble:Xt});return}}}if(!ht)if(B.variant==="reasoning"&&B.reasoning){if(!Ae)return;ht=sp(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!Ie)return;ht=lp(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;ht=Yi(B,o)}else{let Xe=(Bo=o.layout)==null?void 0:Bo.messages;Xe!=null&&Xe.renderUserMessage&&B.role==="user"?ht=Xe.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):Xe!=null&&Xe.renderAssistantMessage&&B.role==="assistant"?ht=Xe.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):ht=Na(B,h,Xe,o.messageActions,ot,{loadingIndicatorRenderer:N,widgetConfig:o}),B.role!=="user"&&ht&&fp(ht,B,o,q)}let er=document.createElement("div");er.className="persona-flex",er.id=`wrapper-${B.id}`,er.setAttribute("data-wrapper-id",B.id),B.role==="user"&&er.classList.add("persona-justify-end"),(ht==null?void 0:ht.getAttribute("data-persona-component-directive"))==="true"&&er.classList.add("persona-w-full"),er.appendChild(ht),gh(Ro,B.id,Wt,er),C.appendChild(er)}),ze.composerOverlay&&ze.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Pe=Re.getAttribute("data-persona-ask-sheet-for");Pe&&!_.has(Pe)&&wn(ze.composerOverlay,Pe)}),(Le=(tt=o.features)==null?void 0:tt.toolCallDisplay)!=null&&Le.grouped){let B=[],Re=[];g.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ie){Re.push(Pe);return}Re.length>1&&B.push(Re),Re=[]}),Re.length>1&&B.push(Re),B.forEach((Pe,ue)=>{var Ke,Tt;let Dt=Pe.map(or=>Array.from(C.children).find(io=>io instanceof HTMLElement&&io.getAttribute("data-wrapper-id")===or.id)).filter(or=>!!or);if(Dt.length<2)return;let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-tool-group-${ue}-${Pe[0].id}`,Wt.setAttribute("data-wrapper-id",`tool-group-${ue}-${Pe[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let ht=document.createElement("div");ht.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Pe.length} tools`,jr=(Tt=(Ke=o.toolCall)==null?void 0:Ke.renderGroupedSummary)==null?void 0:Tt.call(Ke,{messages:Pe,toolCalls:Pe.map(or=>or.toolCall).filter(or=>!!or),defaultSummary:zt,config:o});z(ht,jr)||(ht.textContent=zt);let er=document.createElement("div");er.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(ht,er),Wt.appendChild(Gt),Dt[0].before(Wt),Dt.forEach((or,io)=>{let Gr=document.createElement("div");Gr.className="persona-tool-group-item persona-relative",Gr.setAttribute("data-persona-tool-group-item","true"),io<Dt.length-1&&Gr.setAttribute("data-persona-tool-group-connector","true"),Gr.appendChild(or),er.appendChild(Gr)})})}hh(Ro,U);let Qe=g.some(B=>B.role==="assistant"&&B.streaming),Ve=g[g.length-1],lt=(Ve==null?void 0:Ve.role)==="assistant"&&!Ve.streaming&&Ve.variant!=="approval";if(Po&&g.some(B=>B.role==="user")&&!Qe&&!lt){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:na},Re=n.find(ue=>ue.renderLoadingIndicator),Pe=null;if(Re!=null&&Re.renderLoadingIndicator&&(Pe=Re.renderLoadingIndicator(B)),Pe===null&&((Te=o.loadingIndicator)!=null&&Te.render)&&(Pe=o.loadingIndicator.render(B)),Pe===null&&(Pe=na()),Pe){let ue=document.createElement("div"),Dt=(($e=o.loadingIndicator)==null?void 0:$e.showBubble)!==!1;ue.className=Dt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ue.setAttribute("data-typing-indicator","true"),ue.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ue.appendChild(Pe);let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id="wrapper-typing-indicator",Wt.setAttribute("data-wrapper-id","typing-indicator"),Wt.appendChild(ue),C.appendChild(Wt)}}if(!Po&&g.length>0){let B=g[g.length-1],Re={config:o,lastMessage:B,messageCount:g.length},Pe=n.find(Dt=>Dt.renderIdleIndicator),ue=null;if(Pe!=null&&Pe.renderIdleIndicator&&(ue=Pe.renderIdleIndicator(Re)),ue===null&&((je=o.loadingIndicator)!=null&&je.renderIdle)&&(ue=o.loadingIndicator.renderIdle(Re)),ue){let Dt=document.createElement("div"),Wt=((mt=o.loadingIndicator)==null?void 0:mt.showBubble)!==!1;Dt.className=Wt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Dt.setAttribute("data-idle-indicator","true"),Dt.appendChild(ue);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild(Dt),C.appendChild(Gt)}}if(Wi(d,C),ne.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of ne){let ue=d.querySelector(`#wrapper-${B}`);ue&&Pe!==null&&(ue.replaceChildren(Pe),ue.setAttribute("data-bubble-fp",Re),$o.set(B,Re))}if($o.size>0)for(let B of $o.keys())U.has(B)||$o.delete(B);if(Y.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of Y){let ue=d.querySelector(`#wrapper-${B}`);ue&&Pe!==null&&(ue.replaceChildren(Pe),ue.setAttribute("data-bubble-fp",Re),Io.set(B,Re))}if(Io.size>0)for(let B of Io.keys())U.has(B)||Io.delete(B);if(we.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of we){let ue=d.querySelector(`#wrapper-${B}`);ue&&Pe!==null&&(ue.replaceChildren(Pe),ue.setAttribute("data-bubble-fp",Re),fo.set(B,Re))}if(fo.size>0)for(let B of fo.keys())U.has(B)||fo.delete(B)},Ka=(d,g,h)=>{Xx(d,g,h),ln()},Xa=null,Jx=()=>{var h;if(Xa)return;let d=C=>{let R=C.composedPath();R.includes(ge)||dt&&R.includes(dt)||Vt(!1,"user")};Xa=d,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",d,!0)},Wp=()=>{var g;if(!Xa)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Xa,!0),Xa=null};ut.push(()=>Wp());let Ja=null,Qx=()=>{var h;if(Ja)return;let d=C=>{C.key==="Escape"&&(C.isComposing||Vt(!1,"user"))};Ja=d,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",d,!0)},Hp=()=>{var g;if(!Ja)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",Ja,!0),Ja=null};ut.push(()=>Hp());let Qa=!1,Bp=new Set,Yx=()=>{var g,h,C,R;let d=(C=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.peek)==null?void 0:C.streamAnimation;return d||((R=o.features)==null?void 0:R.streamAnimation)},xa=()=>{var lt,tt,Le,Te;if(!I())return;let d=ze.peekBanner,g=ze.peekTextNode;if(!d||!g)return;if(O){d.classList.remove("persona-pill-peek--visible");return}let h=(lt=q==null?void 0:q.getMessages())!=null?lt:[],C;for(let $e=h.length-1;$e>=0;$e--){let je=h[$e];if(je.role==="assistant"&&je.content){C=je;break}}if(!C){d.classList.remove("persona-pill-peek--visible");return}let R=C.content,N=!!C.streaming,z=Yx(),U=Ni(z),_=U.type!=="none"?Ss(U.type,z==null?void 0:z.plugins):null,oe=((tt=_==null?void 0:_.isAnimating)==null?void 0:tt.call(_,C))===!0,ne=_!==null&&(N||oe);ne&&_&&!Bp.has(_.name)&&(Kc(_,e),Bp.add(_.name));let Y=ne&&(_!=null&&_.containerClass)?_.containerClass:null,be=(Le=g.dataset.personaPeekStreamClass)!=null?Le:null;be&&be!==Y&&(g.classList.remove(be),delete g.dataset.personaPeekStreamClass),Y&&be!==Y&&(g.classList.add(Y),g.dataset.personaPeekStreamClass=Y),ne?(g.style.setProperty("--persona-stream-step",`${U.speed}ms`),g.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Be=ne?Oi(R,U.buffer,_,C,N):R;if(ne&&U.placeholder==="skeleton"&&N&&(!Be||!Be.trim())){let $e=document.createElement("div"),je=Ms();je.classList.add("persona-pill-peek__skeleton"),$e.appendChild(je),Wi(g,$e)}else{let $e=Math.max(0,Be.length-100),je=Be.length>100?Be.slice(-100):Be,mt=Fo(je);if(!ne||!_){let B=Be.length>100?`\u2026${je}`:je;g.textContent!==B&&(g.textContent=B)}else{let B=mt;(_.wrap==="char"||_.wrap==="word")&&(B=As(mt,_.wrap,`peek-${C.id}`,{skipTags:_.skipTags,startIndex:$e}));let Re=document.createElement("div");if(Re.innerHTML=B,_.useCaret&&je.length>0){let Pe=_i(),ue=Re.querySelectorAll(".persona-stream-char, .persona-stream-word"),Dt=ue[ue.length-1];Dt!=null&&Dt.parentNode?Dt.parentNode.insertBefore(Pe,Dt.nextSibling):Re.appendChild(Pe)}Wi(g,Re),(Te=_.onAfterRender)==null||Te.call(_,{container:g,bubble:d,messageId:C.id,message:C,speed:U.speed,duration:U.duration})}}let Ve=Po||Qa;d.classList.toggle("persona-pill-peek--visible",Ve)};if(I()){let d=ze.peekBanner;if(d){let C=R=>{R.preventDefault(),R.stopPropagation(),Vt(!0,"user")};d.addEventListener("pointerdown",C),ut.push(()=>{d.removeEventListener("pointerdown",C)})}let g=()=>{Qa||(Qa=!0,xa())},h=()=>{Qa&&(Qa=!1,xa())};X.addEventListener("pointerenter",g),X.addEventListener("pointerleave",h),ut.push(()=>{X.removeEventListener("pointerenter",g),X.removeEventListener("pointerleave",h)}),dt&&(dt.addEventListener("pointerenter",g),dt.addEventListener("pointerleave",h),ut.push(()=>{dt.removeEventListener("pointerenter",g),dt.removeEventListener("pointerleave",h)}))}let Zx=d=>{var be,Be,we,Qe,Ve,lt,tt,Le;let g=(Be=(be=o.launcher)==null?void 0:be.composerBar)!=null?Be:{},h=(we=g.expandedSize)!=null?we:"anchored",C=(Qe=g.bottomOffset)!=null?Qe:"16px",R=g.collapsedMaxWidth,N=(Ve=g.expandedMaxWidth)!=null?Ve:"880px",z=(lt=g.expandedTopOffset)!=null?lt:"5vh",U=(tt=g.modalMaxWidth)!=null?tt:"880px",_=(Le=g.modalMaxHeight)!=null?Le:"min(90vh, 800px)",oe="calc(100vw - 32px)",ne="var(--persona-pill-area-height, 80px)",Y=ge.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",dt){let Te=dt.style;Te.bottom=C,Te.width=R!=null?R:""}if(d&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=U,Y.maxWidth=oe,Y.maxHeight=_,Y.height=_;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${C} + ${ne})`,Y.top=z,Y.width=N,Y.maxWidth=oe}},Ya=()=>{var _,oe,ne,Y,be,Be,we,Qe;if(!D())return;if(I()){let lt=(ne=((oe=(_=o.launcher)==null?void 0:_.composerBar)!=null?oe:{}).expandedSize)!=null?ne:"anchored",tt=O?"expanded":"collapsed";ge.dataset.state=tt,ge.dataset.expandedSize=lt,dt&&(dt.dataset.state=tt,dt.dataset.expandedSize=lt),ge.style.removeProperty("display"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Zx(O),ve.style.display=O?"flex":"none",Eo(),O?(Jx(),Qx()):(Wp(),Hp()),xa();return}let d=nr(o),g=(Y=e.ownerDocument.defaultView)!=null?Y:window,h=(Be=(be=o.launcher)==null?void 0:be.mobileBreakpoint)!=null?Be:640,C=(Qe=(we=o.launcher)==null?void 0:we.mobileFullscreen)!=null?Qe:!0,R=g.innerWidth<=h,N=C&&R&&T,z=Qr(o).reveal;O?(ge.style.removeProperty("display"),ge.style.display=d?"flex":"",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0"),X.classList.add("persona-scale-100","persona-opacity-100"),Zt?Zt.element.style.display="none":ir&&(ir.style.display="none")):(d?d&&(z==="overlay"||z==="push")&&!N?(ge.style.removeProperty("display"),ge.style.display="flex",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.setProperty("display","none","important"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.display="",ge.classList.add("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100"),X.classList.add("persona-scale-95","persona-opacity-0")),Zt?Zt.element.style.display=d?"none":"":ir&&(ir.style.display=d?"none":""))},Vt=(d,g="user")=>{var N,z;if(!D()||O===d)return;let h=O;O=d,Ya();let C=(()=>{var we,Qe,Ve,lt,tt,Le,Te,$e,je,mt;let U=(Qe=(we=o.launcher)==null?void 0:we.sidebarMode)!=null?Qe:!1,_=(Ve=e.ownerDocument.defaultView)!=null?Ve:window,oe=(tt=(lt=o.launcher)==null?void 0:lt.mobileFullscreen)!=null?tt:!0,ne=(Te=(Le=o.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Te:640,Y=_.innerWidth<=ne,be=nr(o)&&oe&&Y,Be=I()&&((mt=(je=($e=o.launcher)==null?void 0:$e.composerBar)==null?void 0:je.expandedSize)!=null?mt:"fullscreen")==="fullscreen";return U||oe&&Y&&T||be||Be})();if(O&&C){if(!ar){let U=e.getRootNode(),_=U instanceof ShadowRoot?U.host:e.closest(".persona-host");_&&(ar=Xc(_,(z=(N=o.launcher)==null?void 0:N.zIndex)!=null?z:Sr))}sr||(sr=Jc(e.ownerDocument))}else O||(ar==null||ar(),ar=null,sr==null||sr(),sr=null);O&&(Za(),_t()==="follow"?pr(!0):Go());let R={open:O,source:g,timestamp:Date.now()};O&&!h?i.emit("widget:opened",R):!O&&h&&i.emit("widget:closed",R),i.emit("widget:state",{open:O,launcherEnabled:T,voiceActive:ct.active,streaming:q.isStreaming()})},fl=d=>{ae(d?"stop":"send"),F&&(F.disabled=d),Bn.buttons.forEach(g=>{g.disabled=d}),He.dataset.personaComposerStreaming=d?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=d)})},ml=()=>{ct.active||Z&&Z.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ml(),200)});let Dp=()=>{var h,C,R,N,z,U,_,oe,ne,Y,be;Co.textContent=(C=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?C:"Hello \u{1F44B}",So.textContent=(N=(R=o.copy)==null?void 0:R.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",Z.placeholder=(U=(z=o.copy)==null?void 0:z.inputPlaceholder)!=null?U:"How can I help...";let d=Me.querySelector("[data-persona-intro-card]");if(d){let Be=((_=o.copy)==null?void 0:_.showWelcomeCard)!==!1;d.style.display=Be?"":"none",Be?(Me.classList.remove("persona-gap-3"),Me.classList.add("persona-gap-6")):(Me.classList.remove("persona-gap-6"),Me.classList.add("persona-gap-3"))}!((ne=(oe=o.sendButton)==null?void 0:oe.useIcon)!=null&&ne)&&!(q!=null&&q.isStreaming())&&(Ue.textContent=(be=(Y=o.copy)==null?void 0:Y.sendButtonLabel)!=null?be:"Send"),Z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Z.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let d=p.sessionId;return typeof d=="string"?d:null},setStoredSessionId:d=>{b(g=>({...g,sessionId:d}))}});let On=null,ey=()=>{On==null&&(On=setInterval(()=>{let d=et.querySelectorAll("[data-tool-elapsed]");if(d.length===0){clearInterval(On),On=null;return}let g=Date.now();d.forEach(h=>{let C=Number(h.getAttribute("data-tool-elapsed"));C&&(h.textContent=ai(g-C))})},100))};q=new Ia(o,{onMessagesChanged(d){var C;Ka(et,d,te),ey(),ca(d),pr(!Po),Kx(d);let g=[...d].reverse().find(R=>R.role==="user");d.length===0&&hr(),!ua||Fn?(ua=!0,fa=(C=g==null?void 0:g.id)!=null?C:null):g&&g.id!==fa&&(fa=g.id,Gx(g.id));let h=ct.lastUserMessageId;g&&g.id!==h&&(ct.lastUserMessageId=g.id,i.emit("user:message",g)),ct.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Ze(d),xa()},onStatusChanged(d){var C;let g=(C=o.statusIndicator)!=null?C:{};Qt(yr,(R=>{var N,z,U,_;return R==="idle"?(N=g.idleText)!=null?N:Cr.idle:R==="connecting"?(z=g.connectingText)!=null?z:Cr.connecting:R==="connected"?(U=g.connectedText)!=null?U:Cr.connected:R==="error"?(_=g.errorText)!=null?_:Cr.error:Cr[R]})(d),g,d)},onStreamingChanged(d){Po=d,fl(d),q&&Ka(et,q.getMessages(),te),d||pr(!0),xa()},onVoiceStatusChanged(d){var g,h;if(i.emit("voice:status",{status:d,timestamp:Date.now()}),((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype")switch(d){case"listening":Ko(),ba();break;case"processing":Ko(),ay();break;case"speaking":Ko(),sy();break;default:d==="idle"&&q.isBargeInActive()?(Ko(),ba(),F==null||F.setAttribute("aria-label","End voice session")):(ct.active=!1,Ko(),no("system"),Hr());break}},onArtifactsState(d){_r=d,Wr(),Ze()}}),Ct.current=q;let gl=null;if(q.onReadAloudChange((d,g)=>{var R;an=d,sn=g,ln();let h=d!=null?d:gl;d&&(gl=d);let C=h&&(R=q.getMessages().find(N=>N.id===h))!=null?R:null;i.emit("message:read-aloud",{messageId:h,message:C,state:g,timestamp:Date.now()}),g==="idle"&&(gl=null)}),ua=!0,((Gu=(ju=o.voiceRecognition)==null?void 0:ju.provider)==null?void 0:Gu.type)==="runtype")try{q.setupVoice()}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",d)}o.clientToken&&q.initClientSession().catch(d=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",d)}),(j||o.onSSEEvent)&&q.setSSEEventCallback((d,g)=>{var h;(h=o.onSSEEvent)==null||h.call(o,d,g),Q==null||Q.processEvent(d,g),j==null||j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:d,timestamp:Date.now(),payload:JSON.stringify(g)})}),f&&f.then(d=>{var g,h,C;if(d){if(d.metadata&&(p=hp(d.metadata),A.syncFromMetadata()),(g=d.messages)!=null&&g.length){Fn=!0;try{q.hydrateMessages(d.messages)}finally{Fn=!1}}(h=d.artifacts)!=null&&h.length&&q.hydrateArtifacts(d.artifacts,(C=d.selectedArtifactId)!=null?C:null)}}).catch(d=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",d)});let Fp=()=>{var g,h,C;!I()||O||!((C=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.expandOnSubmit)==null||C)||Vt(!0,"auto")},Np=d=>{var R;if(d.preventDefault(),q.isStreaming()){q.cancel(),Q==null||Q.reset(),Fe==null||Fe.update();return}let g=Z.value.trim(),h=(R=wt==null?void 0:wt.hasAttachments())!=null?R:!1;if(!g&&!h)return;Fp();let C;h&&(C=[],C.push(...wt.getContentParts()),g&&C.push(gs(g))),Z.value="",Z.style.height="auto",Us(),q.sendMessage(g,{contentParts:C}),h&&wt.clearAttachments()},ty=()=>{var d;return((d=o.features)==null?void 0:d.composerHistory)!==!1},hl={...Hi},xl=!1,Us=()=>{hl={...Hi}},ry=()=>q.getMessages().filter(d=>d.role==="user").map(d=>{var g;return(g=d.content)!=null?g:""}).filter(d=>d.length>0),oy=d=>{if(!Z)return;xl=!0,Z.value=d,Z.dispatchEvent(new Event("input",{bubbles:!0})),xl=!1;let g=Z.value.length;Z.setSelectionRange(g,g)},Op=()=>{xl||Us()},_p=d=>{if(Z){if(ty()&&(d.key==="ArrowUp"||d.key==="ArrowDown")&&!d.shiftKey&&!d.metaKey&&!d.ctrlKey&&!d.altKey&&!d.isComposing){let g=Z.selectionStart===0&&Z.selectionEnd===0,h=ph({direction:d.key==="ArrowUp"?"up":"down",history:ry(),currentValue:Z.value,atStart:g,state:hl});if(hl=h.state,h.handled){d.preventDefault(),h.value!==void 0&&oy(h.value);return}}if(d.key==="Enter"&&!d.shiftKey){if(q.isStreaming()){d.preventDefault();return}Us(),d.preventDefault(),Ue.click()}}},Up=d=>{d.key!=="Escape"||d.isComposing||q.isStreaming()&&d.composedPath().includes(ve)&&(q.cancel(),Q==null||Q.reset(),Fe==null||Fe.update(),Us(),d.preventDefault(),d.stopImmediatePropagation())},qp=async d=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!wt)return;let g=n0(d.clipboardData);g.length!==0&&(d.preventDefault(),await wt.handleFiles(g))},ao=null,Ho=!1,ya=null,it=null,Vp=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,qs=(d="user")=>{var N,z,U,_,oe,ne,Y;if(Ho||q.isStreaming())return;let g=Vp();if(!g)return;ao=new g;let C=(z=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?z:2e3;ao.continuous=!0,ao.interimResults=!0,ao.lang="en-US";let R=Z.value;ao.onresult=be=>{let Be="",we="";for(let Ve=0;Ve<be.results.length;Ve++){let lt=be.results[Ve],tt=lt[0].transcript;lt.isFinal?Be+=tt+" ":we=tt}let Qe=R+Be+we;Z.value=Qe,ya&&clearTimeout(ya),(Be||we)&&(ya=window.setTimeout(()=>{let Ve=Z.value.trim();Ve&&ao&&Ho&&(fn(),Z.value="",Z.style.height="auto",q.sendMessage(Ve,{viaVoice:!0}))},C))},ao.onerror=be=>{be.error!=="no-speech"&&fn()},ao.onend=()=>{if(Ho){let be=Z.value.trim();be&&be!==R.trim()&&(Z.value="",Z.style.height="auto",q.sendMessage(be,{viaVoice:!0})),fn()}};try{if(ao.start(),Ho=!0,ct.active=!0,d!=="system"&&(ct.manuallyDeactivated=!1),no(d),Hr(),F){let be=(U=o.voiceRecognition)!=null?U:{};it={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor,iconName:(_=be.iconName)!=null?_:"mic",iconSize:parseFloat((Y=(ne=be.iconSize)!=null?ne:(oe=o.sendButton)==null?void 0:oe.size)!=null?Y:"40")||24};let Be=be.recordingBackgroundColor,we=be.recordingIconColor,Qe=be.recordingBorderColor;if(F.classList.add("persona-voice-recording"),F.style.backgroundColor=Be!=null?Be:"var(--persona-voice-recording-bg, #ef4444)",F.style.color=we!=null?we:"var(--persona-voice-recording-indicator, #ffffff)",we){let Ve=F.querySelector("svg");Ve&&Ve.setAttribute("stroke",we)}Qe&&(F.style.borderColor=Qe),F.setAttribute("aria-label","Stop voice recognition")}}catch{fn("system")}},fn=(d="user")=>{if(Ho){if(Ho=!1,ya&&(clearTimeout(ya),ya=null),ao){try{ao.stop()}catch{}ao=null}if(ct.active=!1,no(d),Hr(),F){if(F.classList.remove("persona-voice-recording"),it){F.style.backgroundColor=it.backgroundColor,F.style.color=it.color,F.style.borderColor=it.borderColor;let g=F.querySelector("svg");g&&g.setAttribute("stroke",it.color||"currentColor"),it=null}F.setAttribute("aria-label","Start voice recognition")}}},ny=(d,g)=>{var tt,Le,Te,$e,je,mt,B,Re,Pe;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),C=((tt=d==null?void 0:d.provider)==null?void 0:tt.type)==="runtype",R=((Le=d==null?void 0:d.provider)==null?void 0:Le.type)==="custom";if(!(h||C||R))return null;let z=w("div","persona-send-button-wrapper"),U=w("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let _=(Te=d==null?void 0:d.iconName)!=null?Te:"mic",oe=($e=g==null?void 0:g.size)!=null?$e:"40px",ne=(je=d==null?void 0:d.iconSize)!=null?je:oe,Y=parseFloat(ne)||24,be=(mt=d==null?void 0:d.backgroundColor)!=null?mt:g==null?void 0:g.backgroundColor,Be=(B=d==null?void 0:d.iconColor)!=null?B:g==null?void 0:g.textColor;U.style.width=ne,U.style.height=ne,U.style.minWidth=ne,U.style.minHeight=ne,U.style.fontSize="18px",U.style.lineHeight="1",Be?U.style.color=Be:U.style.color="var(--persona-text, #111827)";let Qe=fe(_,Y,Be||"currentColor",1.5);Qe?U.appendChild(Qe):U.textContent="\u{1F3A4}",be?U.style.backgroundColor=be:U.style.backgroundColor="",d!=null&&d.borderWidth&&(U.style.borderWidth=d.borderWidth,U.style.borderStyle="solid"),d!=null&&d.borderColor&&(U.style.borderColor=d.borderColor),d!=null&&d.paddingX&&(U.style.paddingLeft=d.paddingX,U.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(U.style.paddingTop=d.paddingY,U.style.paddingBottom=d.paddingY),z.appendChild(U);let Ve=(Re=d==null?void 0:d.tooltipText)!=null?Re:"Start voice recognition";if(((Pe=d==null?void 0:d.showTooltip)!=null?Pe:!1)&&Ve){let ue=w("div","persona-send-button-tooltip");ue.textContent=Ve,z.appendChild(ue)}return{micButton:U,micButtonWrapper:z}},yl=()=>{var g,h,C,R,N;if(!F||it)return;let d=(g=o.voiceRecognition)!=null?g:{};it={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor,iconName:(h=d.iconName)!=null?h:"mic",iconSize:parseFloat((N=(R=d.iconSize)!=null?R:(C=o.sendButton)==null?void 0:C.size)!=null?N:"40")||24}},bl=(d,g)=>{var N,z,U,_,oe;if(!F)return;let h=F.querySelector("svg");h&&h.remove();let C=(oe=it==null?void 0:it.iconSize)!=null?oe:parseFloat((_=(U=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?U:(z=o.sendButton)==null?void 0:z.size)!=null?_:"40")||24,R=fe(d,C,g,1.5);R&&F.appendChild(R)},Vs=()=>{F&&F.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ba=()=>{var R;if(!F)return;yl();let d=(R=o.voiceRecognition)!=null?R:{},g=d.recordingBackgroundColor,h=d.recordingIconColor,C=d.recordingBorderColor;if(Vs(),F.classList.add("persona-voice-recording"),F.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",F.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=F.querySelector("svg");N&&N.setAttribute("stroke",h)}C&&(F.style.borderColor=C),F.setAttribute("aria-label","Stop voice recognition")},ay=()=>{var U,_,oe,ne,Y,be,Be,we;if(!F)return;yl();let d=(U=o.voiceRecognition)!=null?U:{},g=q.getVoiceInterruptionMode(),h=(_=d.processingIconName)!=null?_:"loader",C=(ne=(oe=d.processingIconColor)!=null?oe:it==null?void 0:it.color)!=null?ne:"",R=(be=(Y=d.processingBackgroundColor)!=null?Y:it==null?void 0:it.backgroundColor)!=null?be:"",N=(we=(Be=d.processingBorderColor)!=null?Be:it==null?void 0:it.borderColor)!=null?we:"";Vs(),F.classList.add("persona-voice-processing"),F.style.backgroundColor=R,F.style.borderColor=N;let z=C||"currentColor";F.style.color=z,bl(h,z),F.setAttribute("aria-label","Processing voice input"),g==="none"&&(F.style.cursor="default")},sy=()=>{var oe,ne,Y,be,Be,we,Qe,Ve,lt,tt,Le,Te;if(!F)return;yl();let d=(oe=o.voiceRecognition)!=null?oe:{},g=q.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",C=(ne=d.speakingIconName)!=null?ne:h,R=(we=d.speakingIconColor)!=null?we:g==="barge-in"?(be=(Y=d.recordingIconColor)!=null?Y:it==null?void 0:it.color)!=null?be:"":(Be=it==null?void 0:it.color)!=null?Be:"",N=(lt=d.speakingBackgroundColor)!=null?lt:g==="barge-in"?(Qe=d.recordingBackgroundColor)!=null?Qe:"var(--persona-voice-recording-bg, #ef4444)":(Ve=it==null?void 0:it.backgroundColor)!=null?Ve:"",z=(Te=d.speakingBorderColor)!=null?Te:g==="barge-in"?(tt=d.recordingBorderColor)!=null?tt:"":(Le=it==null?void 0:it.borderColor)!=null?Le:"";Vs(),F.classList.add("persona-voice-speaking"),F.style.backgroundColor=N,F.style.borderColor=z;let U=R||"currentColor";F.style.color=U,bl(C,U);let _=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";F.setAttribute("aria-label",_),g==="none"&&(F.style.cursor="default"),g==="barge-in"&&F.classList.add("persona-voice-recording")},Ko=()=>{var d,g,h;F&&(Vs(),it&&(F.style.backgroundColor=(d=it.backgroundColor)!=null?d:"",F.style.color=(g=it.color)!=null?g:"",F.style.borderColor=(h=it.borderColor)!=null?h:"",bl(it.iconName,it.color||"currentColor"),it=null),F.style.cursor="",F.setAttribute("aria-label","Start voice recognition"))},zs=()=>{var d,g;if(((g=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:g.type)==="runtype"){let h=q.getVoiceStatus(),C=q.getVoiceInterruptionMode();if(C==="none"&&(h==="processing"||h==="speaking"))return;if(C==="cancel"&&(h==="processing"||h==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{ct.active=!1,ct.manuallyDeactivated=!0,Hr(),no("user"),Ko()});return}q.toggleVoice().then(()=>{ct.active=q.isVoiceActive(),ct.manuallyDeactivated=!q.isVoiceActive(),Hr(),no("user"),q.isVoiceActive()?ba():Ko()});return}if(Ho){let h=Z.value.trim();ct.manuallyDeactivated=!0,Hr(),fn("user"),h&&(Z.value="",Z.style.height="auto",q.sendMessage(h))}else ct.manuallyDeactivated=!1,Hr(),qs("user")};Ao=zs,F&&(F.addEventListener("click",zs),ut.push(()=>{var d,g;((g=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:g.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Ko()):fn("system"),F&&F.removeEventListener("click",zs)}));let iy=i.on("assistant:complete",()=>{ja&&(ct.active||ct.manuallyDeactivated||ja==="assistant"&&!ct.lastUserMessageWasVoice||setTimeout(()=>{var d,g;!ct.active&&!ct.manuallyDeactivated&&(((g=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{ct.active=q.isVoiceActive(),no("auto"),q.isVoiceActive()&&ba()}):qs("auto"))},600))});ut.push(iy);let ly=i.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});ut.push(ly);let zp=()=>{Vt(!O,"user")},Zt=null,ir=null;if(T&&!I()){let{instance:d,element:g}=tp({config:o,plugins:n,onToggle:zp});Zt=d,d||(ir=g)}Zt?e.appendChild(Zt.element):ir&&e.appendChild(ir),Ya(),ca(),Dp(),fl(q.isStreaming()),_t()==="follow"?pr(!0):Go(),_s(),S&&(!T||I()?setTimeout(()=>ml(),0):O&&setTimeout(()=>ml(),200));let Za=()=>{var _,oe,ne,Y,be,Be,we,Qe,Ve,lt,tt,Le,Te,$e,je,mt,B,Re,Pe,ue,Dt,Wt;if(I()){eo(),Ya();return}let d=nr(o),g=(oe=(_=o.launcher)==null?void 0:_.sidebarMode)!=null?oe:!1,h=d||g||((Y=(ne=o.launcher)==null?void 0:ne.fullHeight)!=null?Y:!1),C=(be=e.ownerDocument.defaultView)!=null?be:window,R=(we=(Be=o.launcher)==null?void 0:Be.mobileFullscreen)!=null?we:!0,N=(Ve=(Qe=o.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?Ve:640,z=C.innerWidth<=N,U=R&&z&&T;try{if(U){Eo(),Tn(e,o);return}if(H&&(H=!1,Eo(),Tn(e,o)),!T&&!d){X.style.height="",X.style.width="";return}if(!g&&!d){let Gt=(tt=(lt=o==null?void 0:o.launcher)==null?void 0:lt.width)!=null?tt:o==null?void 0:o.launcherWidth,ht=Gt!=null?Gt:Jr;X.style.width=ht,X.style.maxWidth=ht}if(ye(),!h){let Gt=C.innerHeight,ht=64,zt=(Te=(Le=o.launcher)==null?void 0:Le.heightOffset)!=null?Te:0,jr=Math.max(200,Gt-ht),er=Math.min(640,jr),Ke=Math.max(200,er-zt);X.style.height=`${Ke}px`}}finally{if(eo(),Ya(),O&&T){let ht=(($e=e.ownerDocument.defaultView)!=null?$e:window).innerWidth<=((mt=(je=o.launcher)==null?void 0:je.mobileBreakpoint)!=null?mt:640),zt=(Re=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Re:!1,jr=(ue=(Pe=o.launcher)==null?void 0:Pe.mobileFullscreen)!=null?ue:!0,er=nr(o)&&jr&&ht,Ke=zt||jr&&ht&&T||er;if(Ke&&!sr){let Tt=e.getRootNode(),or=Tt instanceof ShadowRoot?Tt.host:e.closest(".persona-host");or&&!ar&&(ar=Xc(or,(Wt=(Dt=o.launcher)==null?void 0:Dt.zIndex)!=null?Wt:Sr)),sr=Jc(e.ownerDocument)}else Ke||(ar==null||ar(),ar=null,sr==null||sr(),sr=null)}}};Za();let $p=(Ku=e.ownerDocument.defaultView)!=null?Ku:window;if($p.addEventListener("resize",Za),ut.push(()=>$p.removeEventListener("resize",Za)),typeof ResizeObserver!="undefined"){let d=new ResizeObserver(()=>{eo()});d.observe(He),ut.push(()=>d.disconnect())}zr=Me.scrollTop;let jp=en(Me),dy=()=>{let d=Me.getRootNode(),g=typeof d.getSelection=="function"?d.getSelection():null;return g!=null?g:Me.ownerDocument.getSelection()},vl=()=>xh(dy(),Me),Gp=()=>{let d=Me.scrollTop,g=en(Me),h=g<jp;if(jp=g,_t()!=="follow"){zr=d,nt();return}let{action:C,nextLastScrollTop:R}=Di({following:Vr.isFollowing(),currentScrollTop:d,lastScrollTop:zr,nearBottom:ta(Me,ma),userScrollThreshold:Ns,isAutoScrolling:go||Dn||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(zr=R,C==="resume"){vl()||Br();return}C==="pause"&&Ga()};if(Me.addEventListener("scroll",Gp,{passive:!0}),ut.push(()=>Me.removeEventListener("scroll",Gp)),typeof ResizeObserver!="undefined"){let d=new ResizeObserver(()=>{jx()});d.observe(et),d.observe(Me),ut.push(()=>d.disconnect())}let Kp=()=>{_t()==="follow"&&Vr.isFollowing()&&vl()&&Ga()},Xp=Me.ownerDocument;Xp.addEventListener("selectionchange",Kp),ut.push(()=>{Xp.removeEventListener("selectionchange",Kp)});let Jp=d=>{if(_t()!=="follow")return;let g=Fi({following:Vr.isFollowing(),deltaY:d.deltaY,nearBottom:ta(Me,ma),resumeWhenNearBottom:!0});g==="pause"?Ga():g==="resume"&&!vl()&&Br()};Me.addEventListener("wheel",Jp,{passive:!0}),ut.push(()=>Me.removeEventListener("wheel",Jp)),qt.addEventListener("click",()=>{hr(),Me.scrollTop=Me.scrollHeight,zr=Me.scrollTop,Br(),pr(!0),nt()}),ut.push(()=>qt.remove()),ut.push(()=>{G(),hr()});let Qp=()=>{P&&(Lo&&(P.removeEventListener("click",Lo),Lo=null),D()?(P.style.display="",Lo=()=>{Vt(!1,"user")},P.addEventListener("click",Lo)):P.style.display="none")};Qp(),(()=>{let{clearChatButton:d}=ze;d&&d.addEventListener("click",()=>{q.clearMessages(),Ro.clear(),Br(),wn(ze.composerOverlay);try{localStorage.removeItem(Va),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Va}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Va)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),l!=null&&l.clear)try{let h=l.clear();h instanceof Promise&&h.catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},A.syncFromMetadata(),j==null||j.clear(),Q==null||Q.reset(),Fe==null||Fe.update()})})(),bt&&bt.addEventListener("submit",Np),Z==null||Z.addEventListener("keydown",_p),Z==null||Z.addEventListener("input",Op),Z==null||Z.addEventListener("paste",qp);let Yp=(Xu=e.ownerDocument)!=null?Xu:document;Yp.addEventListener("keydown",Up,!0);let Zp="persona-attachment-drop-active",es=0,wl=()=>{es=0,ve.classList.remove(Zp)},va=()=>{var d;return((d=o.attachments)==null?void 0:d.enabled)===!0&&wt!==null},eu=d=>{!dl(d.dataTransfer)||!va()||(es++,es===1&&ve.classList.add(Zp))},tu=d=>{!dl(d.dataTransfer)||!va()||(es--,es<=0&&wl())},ru=d=>{!dl(d.dataTransfer)||!va()||(d.preventDefault(),d.dataTransfer.dropEffect="copy")},ou=d=>{var h;if(!dl(d.dataTransfer)||!va())return;d.preventDefault(),d.stopPropagation(),wl();let g=Array.from((h=d.dataTransfer.files)!=null?h:[]);g.length!==0&&wt.handleFiles(g)},mn=!0;ve.addEventListener("dragenter",eu,mn),ve.addEventListener("dragleave",tu,mn),e.addEventListener("dragover",ru,mn),e.addEventListener("drop",ou,mn);let $s=e.ownerDocument,nu=d=>{va()&&d.preventDefault()},au=d=>{va()&&d.preventDefault()};$s.addEventListener("dragover",nu),$s.addEventListener("drop",au),ut.push(()=>{bt&&bt.removeEventListener("submit",Np),Z==null||Z.removeEventListener("keydown",_p),Z==null||Z.removeEventListener("input",Op),Z==null||Z.removeEventListener("paste",qp),Yp.removeEventListener("keydown",Up,!0)}),ut.push(()=>{ve.removeEventListener("dragenter",eu,mn),ve.removeEventListener("dragleave",tu,mn),e.removeEventListener("dragover",ru,mn),e.removeEventListener("drop",ou,mn),$s.removeEventListener("dragover",nu),$s.removeEventListener("drop",au),wl()}),ut.push(()=>{q.cancel()}),Zt?ut.push(()=>{Zt==null||Zt.destroy()}):ir&&ut.push(()=>{ir==null||ir.remove()});let rr={update(d){var Ut,fr,Kr,Do,mr,gr,lo,xn,rf,of,nf,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,vf,wf,Cf,Sf,Af,Mf,Tf,Ef,kf,Lf,Pf,Rf,If,Wf,Hf,Bf,Df,Ff,Nf,Of,_f,Uf,qf,Vf,zf,$f,jf,Gf,Kf,Xf,Jf,Qf,Yf,Zf,em,tm,rm,om,nm,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,vm,wm,Cm,Sm,Am,Mm,Tm,Em,km,Lm,Pm,Rm,Im,Wm,Hm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,Vm,zm,$m,jm,Gm,Km,Xm,Jm,Qm,Ym,Zm,eg,tg;let g=o.toolCall,h=o.messageActions,C=(Ut=o.layout)==null?void 0:Ut.messages,R=o.colorScheme,N=o.loadingIndicator,z=o.iterationDisplay,U=(fr=o.features)==null?void 0:fr.showReasoning,_=(Kr=o.features)==null?void 0:Kr.showToolCalls,oe=(Do=o.features)==null?void 0:Do.toolCallDisplay,ne=(mr=o.features)==null?void 0:mr.reasoningDisplay;o={...o,...d},Eo(),Tn(e,o),el(e,o),tl(e,o),Wr(),o.colorScheme!==R&&$a();let Y=Is.getForInstance(o.plugins);n.length=0,n.push(...Y),T=(lo=(gr=o.launcher)==null?void 0:gr.enabled)!=null?lo:!0,y=(rf=(xn=o.launcher)==null?void 0:xn.autoExpand)!=null?rf:!1,Ae=(nf=(of=o.features)==null?void 0:of.showReasoning)!=null?nf:!0,Ie=(sf=(af=o.features)==null?void 0:af.showToolCalls)!=null?sf:!0,Ce=(df=(lf=o.features)==null?void 0:lf.scrollToBottom)!=null?df:{};let be=_t();se=(pf=(cf=o.features)==null?void 0:cf.scrollBehavior)!=null?pf:{},be!==_t()&&(hr(),Br()),on(),nt();let Be=le;if(le=(ff=(uf=o.features)==null?void 0:uf.showEventStreamToggle)!=null?ff:!1,le&&!Be){if(j||(Ee=new Ps(pe),j=new Ls(De,Ee),Q=Q!=null?Q:new Rs,Ee.open().then(()=>j==null?void 0:j.restore()).catch(()=>{}),q.setSSEEventCallback((re,St)=>{var $t;($t=o.onSSEEvent)==null||$t.call(o,re,St),Q==null||Q.processEvent(re,St),j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(St)})})),!pt&&ke){let re=(gf=(mf=o.features)==null?void 0:mf.eventStream)==null?void 0:gf.classNames,St="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(re!=null&&re.toggleButton?" "+re.toggleButton:"");pt=w("button",St),pt.style.width="28px",pt.style.height="28px",pt.style.color=Pr.actionIconColor,pt.type="button",pt.setAttribute("aria-label","Event Stream"),pt.title="Event Stream";let $t=fe("activity","18px","currentColor",1.5);$t&&pt.appendChild($t);let rt=ze.clearChatButtonWrapper,kt=ze.closeButtonWrapper,lr=rt||kt;lr&&lr.parentNode===ke?ke.insertBefore(pt,lr):ke.appendChild(pt),pt.addEventListener("click",()=>{K?uo():_o()})}}else!le&&Be&&(uo(),pt&&(pt.remove(),pt=null),j==null||j.clear(),Ee==null||Ee.destroy(),j=null,Ee=null,Q==null||Q.reset(),Q=null);if(((hf=o.launcher)==null?void 0:hf.enabled)===!1&&Zt&&(Zt.destroy(),Zt=null),((xf=o.launcher)==null?void 0:xf.enabled)===!1&&ir&&(ir.remove(),ir=null),((yf=o.launcher)==null?void 0:yf.enabled)!==!1&&!Zt&&!ir){let{instance:re,element:St}=tp({config:o,plugins:n,onToggle:zp});Zt=re,re||(ir=St),e.appendChild(St)}Zt&&Zt.update(o),Se&&((bf=o.launcher)==null?void 0:bf.title)!==void 0&&(Se.textContent=o.launcher.title),We&&((vf=o.launcher)==null?void 0:vf.subtitle)!==void 0&&(We.textContent=o.launcher.subtitle);let we=(wf=o.layout)==null?void 0:wf.header;if((we==null?void 0:we.layout)!==W&&ke){let re=we?Da(o,we,{showClose:D(),onClose:()=>Vt(!1,"user")}):tn({config:o,showClose:D(),onClose:()=>Vt(!1,"user")});Ye.replaceHeader(re),ke=Ye.header.element,ee=Ye.header.iconHolder,Se=Ye.header.headerTitle,We=Ye.header.headerSubtitle,P=Ye.header.closeButton,W=we==null?void 0:we.layout}else if(we&&(ee&&(ee.style.display=we.showIcon===!1?"none":""),Se&&(Se.style.display=we.showTitle===!1?"none":""),We&&(We.style.display=we.showSubtitle===!1?"none":""),P&&(P.style.display=we.showCloseButton===!1?"none":""),ze.clearChatButtonWrapper)){let re=we.showClearChat;if(re!==void 0){ze.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:St}=ze;St&&!St.classList.contains("persona-absolute")&&(re?St.classList.remove("persona-ml-auto"):St.classList.add("persona-ml-auto"))}}let Ve=((Cf=o.layout)==null?void 0:Cf.showHeader)!==!1;ke&&(ke.style.display=Ve?"":"none");let lt=((Sf=o.layout)==null?void 0:Sf.showFooter)!==!1;He&&(He.style.display=lt?"":"none"),eo(),nt(),T!==M?T?Vt(y,"auto"):(O=!0,Ya()):y!==v&&Vt(y,"auto"),v=y,M=T,Za(),Qp();let Te=JSON.stringify(d.toolCall)!==JSON.stringify(g),$e=JSON.stringify(o.messageActions)!==JSON.stringify(h),je=JSON.stringify((Af=o.layout)==null?void 0:Af.messages)!==JSON.stringify(C),mt=((Mf=o.loadingIndicator)==null?void 0:Mf.render)!==(N==null?void 0:N.render)||((Tf=o.loadingIndicator)==null?void 0:Tf.renderIdle)!==(N==null?void 0:N.renderIdle)||((Ef=o.loadingIndicator)==null?void 0:Ef.showBubble)!==(N==null?void 0:N.showBubble),B=o.iterationDisplay!==z,Re=((Lf=(kf=o.features)==null?void 0:kf.showReasoning)!=null?Lf:!0)!==(U!=null?U:!0)||((Rf=(Pf=o.features)==null?void 0:Pf.showToolCalls)!=null?Rf:!0)!==(_!=null?_:!0)||JSON.stringify((If=o.features)==null?void 0:If.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify((Wf=o.features)==null?void 0:Wf.reasoningDisplay)!==JSON.stringify(ne);(Te||$e||je||mt||B||Re)&&q&&(pa++,Ka(et,q.getMessages(),te));let ue=(Hf=o.launcher)!=null?Hf:{},Dt=(Bf=ue.headerIconHidden)!=null?Bf:!1,Wt=(Ff=(Df=o.layout)==null?void 0:Df.header)==null?void 0:Ff.showIcon,Gt=Dt||Wt===!1,ht=ue.headerIconName,zt=(Nf=ue.headerIconSize)!=null?Nf:"48px";if(ee){let re=ve.querySelector(".persona-border-b-persona-divider"),St=re==null?void 0:re.querySelector(".persona-flex-col");if(Gt)ee.style.display="none",re&&St&&!re.contains(St)&&re.insertBefore(St,re.firstChild);else{if(ee.style.display="",ee.style.height=zt,ee.style.width=zt,re&&St&&(re.contains(ee)?ee.nextSibling!==St&&(ee.remove(),re.insertBefore(ee,St)):re.insertBefore(ee,St)),ht){let rt=parseFloat(zt)||24,kt=fe(ht,rt*.6,"currentColor",1);kt?ee.replaceChildren(kt):ee.textContent=(Of=ue.agentIconText)!=null?Of:"\u{1F4AC}"}else if(ue.iconUrl){let rt=ee.querySelector("img");if(rt)rt.src=ue.iconUrl,rt.style.height=zt,rt.style.width=zt;else{let kt=document.createElement("img");kt.src=ue.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=zt,kt.style.width=zt,ee.replaceChildren(kt)}}else{let rt=ee.querySelector("svg"),kt=ee.querySelector("img");(rt||kt)&&ee.replaceChildren(),ee.textContent=(_f=ue.agentIconText)!=null?_f:"\u{1F4AC}"}let $t=ee.querySelector("img");$t&&($t.style.height=zt,$t.style.width=zt)}}let jr=(qf=(Uf=o.layout)==null?void 0:Uf.header)==null?void 0:qf.showTitle,er=(zf=(Vf=o.layout)==null?void 0:Vf.header)==null?void 0:zf.showSubtitle;if(Se&&(Se.style.display=jr===!1?"none":""),We&&(We.style.display=er===!1?"none":""),P){((jf=($f=o.layout)==null?void 0:$f.header)==null?void 0:jf.showCloseButton)===!1?P.style.display="none":P.style.display="";let St=(Gf=ue.closeButtonSize)!=null?Gf:"32px",$t=(Kf=ue.closeButtonPlacement)!=null?Kf:"inline";P.style.height=St,P.style.width=St;let{closeButtonWrapper:rt}=ze,kt=$t==="top-right",lr=rt==null?void 0:rt.classList.contains("persona-absolute");if(rt&&kt!==lr)if(rt.remove(),kt)rt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ve.style.position="relative",ve.appendChild(rt);else{let at=(Jf=(Xf=ue.clearChat)==null?void 0:Xf.placement)!=null?Jf:"inline",dr=(Yf=(Qf=ue.clearChat)==null?void 0:Qf.enabled)!=null?Yf:!0;rt.className=dr&&at==="inline"?"":"persona-ml-auto";let Dr=ve.querySelector(".persona-border-b-persona-divider");Dr&&Dr.appendChild(rt)}if(P.style.color=ue.closeButtonColor||Pr.actionIconColor,ue.closeButtonBackgroundColor?(P.style.backgroundColor=ue.closeButtonBackgroundColor,P.classList.remove("hover:persona-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:persona-bg-gray-100")),ue.closeButtonBorderWidth||ue.closeButtonBorderColor){let at=ue.closeButtonBorderWidth||"0px",dr=ue.closeButtonBorderColor||"transparent";P.style.border=`${at} solid ${dr}`,P.classList.remove("persona-border-none")}else P.style.border="",P.classList.add("persona-border-none");ue.closeButtonBorderRadius?(P.style.borderRadius=ue.closeButtonBorderRadius,P.classList.remove("persona-rounded-full")):(P.style.borderRadius="",P.classList.add("persona-rounded-full")),ue.closeButtonPaddingX?(P.style.paddingLeft=ue.closeButtonPaddingX,P.style.paddingRight=ue.closeButtonPaddingX):(P.style.paddingLeft="",P.style.paddingRight=""),ue.closeButtonPaddingY?(P.style.paddingTop=ue.closeButtonPaddingY,P.style.paddingBottom=ue.closeButtonPaddingY):(P.style.paddingTop="",P.style.paddingBottom="");let wr=(Zf=ue.closeButtonIconName)!=null?Zf:"x",xo=(em=ue.closeButtonIconText)!=null?em:"\xD7";P.innerHTML="";let kr=fe(wr,"28px","currentColor",1);kr?P.appendChild(kr):P.textContent=xo;let Yt=(tm=ue.closeButtonTooltipText)!=null?tm:"Close chat",Xr=(rm=ue.closeButtonShowTooltip)!=null?rm:!0;if(P.setAttribute("aria-label",Yt),rt&&(rt._cleanupTooltip&&(rt._cleanupTooltip(),delete rt._cleanupTooltip),Xr&&Yt)){let at=null,dr=()=>{if(at||!P)return;let zn=P.ownerDocument,ts=zn.body;if(!ts)return;at=No(zn,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let rs=No(zn,"div");rs.className="persona-clear-chat-tooltip-arrow",at.appendChild(rs);let $n=P.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(En),at.style.left=`${$n.left+$n.width/2}px`,at.style.top=`${$n.top-8}px`,at.style.transform="translate(-50%, -100%)",ts.appendChild(at)},Dr=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};rt.addEventListener("mouseenter",dr),rt.addEventListener("mouseleave",Dr),P.addEventListener("focus",dr),P.addEventListener("blur",Dr),rt._cleanupTooltip=()=>{Dr(),rt&&(rt.removeEventListener("mouseenter",dr),rt.removeEventListener("mouseleave",Dr)),P&&(P.removeEventListener("focus",dr),P.removeEventListener("blur",Dr))}}}let{clearChatButton:Ke,clearChatButtonWrapper:Tt}=ze;if(Ke){let re=(om=ue.clearChat)!=null?om:{},St=(nm=re.enabled)!=null?nm:!0,$t=(sm=(am=o.layout)==null?void 0:am.header)==null?void 0:sm.showClearChat,rt=$t!==void 0?$t:St,kt=(im=re.placement)!=null?im:"inline";if(Tt){Tt.style.display=rt?"":"none";let{closeButtonWrapper:lr}=ze;!I()&&lr&&!lr.classList.contains("persona-absolute")&&(rt?lr.classList.remove("persona-ml-auto"):lr.classList.add("persona-ml-auto"));let wr=kt==="top-right",xo=Tt.classList.contains("persona-absolute");if(!I()&&wr!==xo&&rt){if(Tt.remove(),wr)Tt.className="persona-absolute persona-top-4 persona-z-50",Tt.style.right="48px",ve.style.position="relative",ve.appendChild(Tt);else{Tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Tt.style.right="";let Yt=ve.querySelector(".persona-border-b-persona-divider"),Xr=ze.closeButtonWrapper;Yt&&Xr&&Xr.parentElement===Yt?Yt.insertBefore(Tt,Xr):Yt&&Yt.appendChild(Tt)}let kr=ze.closeButtonWrapper;kr&&!kr.classList.contains("persona-absolute")&&(wr?kr.classList.add("persona-ml-auto"):kr.classList.remove("persona-ml-auto"))}}if(rt){if(!I()){let at=(lm=re.size)!=null?lm:"32px";Ke.style.height=at,Ke.style.width=at}let lr=(dm=re.iconName)!=null?dm:"refresh-cw",wr=(cm=re.iconColor)!=null?cm:"";Ke.style.color=wr||Pr.actionIconColor,Ke.innerHTML="";let xo=I()?"14px":"20px",kr=fe(lr,xo,"currentColor",2);if(kr&&Ke.appendChild(kr),re.backgroundColor?(Ke.style.backgroundColor=re.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let at=re.borderWidth||"0px",dr=re.borderColor||"transparent";Ke.style.border=`${at} solid ${dr}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");re.borderRadius?(Ke.style.borderRadius=re.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),re.paddingX?(Ke.style.paddingLeft=re.paddingX,Ke.style.paddingRight=re.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),re.paddingY?(Ke.style.paddingTop=re.paddingY,Ke.style.paddingBottom=re.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let Yt=(pm=re.tooltipText)!=null?pm:"Clear chat",Xr=(um=re.showTooltip)!=null?um:!0;if(Ke.setAttribute("aria-label",Yt),Tt&&(Tt._cleanupTooltip&&(Tt._cleanupTooltip(),delete Tt._cleanupTooltip),Xr&&Yt)){let at=null,dr=()=>{if(at||!Ke)return;let zn=Ke.ownerDocument,ts=zn.body;if(!ts)return;at=No(zn,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let rs=No(zn,"div");rs.className="persona-clear-chat-tooltip-arrow",at.appendChild(rs);let $n=Ke.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(En),at.style.left=`${$n.left+$n.width/2}px`,at.style.top=`${$n.top-8}px`,at.style.transform="translate(-50%, -100%)",ts.appendChild(at)},Dr=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};Tt.addEventListener("mouseenter",dr),Tt.addEventListener("mouseleave",Dr),Ke.addEventListener("focus",dr),Ke.addEventListener("blur",Dr),Tt._cleanupTooltip=()=>{Dr(),Tt&&(Tt.removeEventListener("mouseenter",dr),Tt.removeEventListener("mouseleave",Dr)),Ke&&(Ke.removeEventListener("focus",dr),Ke.removeEventListener("blur",Dr))}}}}let or=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ws],io=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[la.message,la.messageAndClick];A=Hs({parsers:or,handlers:io,getSessionMetadata:x,updateSessionMetadata:b,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),te=lx(o,A,de),q.updateConfig(o),Ka(et,q.getMessages(),te),ca(),Dp(),fl(q.isStreaming());let Gr=((fm=o.voiceRecognition)==null?void 0:fm.enabled)===!0,_n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Un=((gm=(mm=o.voiceRecognition)==null?void 0:mm.provider)==null?void 0:gm.type)==="runtype";if(Gr&&(_n||Un))if(!F||!he){let re=ny(o.voiceRecognition,o.sendButton);re&&(F=re.micButton,he=re.micButtonWrapper,Rt.insertBefore(he,Ar),F.addEventListener("click",zs),F.disabled=q.isStreaming())}else{let re=(hm=o.voiceRecognition)!=null?hm:{},St=(xm=o.sendButton)!=null?xm:{},$t=(ym=re.iconName)!=null?ym:"mic",rt=(bm=St.size)!=null?bm:"40px",kt=(vm=re.iconSize)!=null?vm:rt,lr=parseFloat(kt)||24;F.style.width=kt,F.style.height=kt,F.style.minWidth=kt,F.style.minHeight=kt;let wr=(Cm=(wm=re.iconColor)!=null?wm:St.textColor)!=null?Cm:"currentColor";F.innerHTML="";let xo=fe($t,lr,wr,2);xo?F.appendChild(xo):F.textContent="\u{1F3A4}";let kr=(Sm=re.backgroundColor)!=null?Sm:St.backgroundColor;kr?F.style.backgroundColor=kr:F.style.backgroundColor="",wr?F.style.color=wr:F.style.color="var(--persona-text, #111827)",re.borderWidth?(F.style.borderWidth=re.borderWidth,F.style.borderStyle="solid"):(F.style.borderWidth="",F.style.borderStyle=""),re.borderColor?F.style.borderColor=re.borderColor:F.style.borderColor="",re.paddingX?(F.style.paddingLeft=re.paddingX,F.style.paddingRight=re.paddingX):(F.style.paddingLeft="",F.style.paddingRight=""),re.paddingY?(F.style.paddingTop=re.paddingY,F.style.paddingBottom=re.paddingY):(F.style.paddingTop="",F.style.paddingBottom="");let Yt=he==null?void 0:he.querySelector(".persona-send-button-tooltip"),Xr=(Am=re.tooltipText)!=null?Am:"Start voice recognition";if(((Mm=re.showTooltip)!=null?Mm:!1)&&Xr)if(Yt)Yt.textContent=Xr,Yt.style.display="";else{let dr=document.createElement("div");dr.className="persona-send-button-tooltip",dr.textContent=Xr,he==null||he.insertBefore(dr,F)}else Yt&&(Yt.style.display="none");he.style.display="",F.disabled=q.isStreaming()}else F&&he&&(he.style.display="none",((Em=(Tm=o.voiceRecognition)==null?void 0:Tm.provider)==null?void 0:Em.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():Ho&&fn());if(((km=o.attachments)==null?void 0:km.enabled)===!0)if(!vt||!Ne){let re=(Lm=o.attachments)!=null?Lm:{},$t=(Rm=((Pm=o.sendButton)!=null?Pm:{}).size)!=null?Rm:"40px";Bt||(Bt=w("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Bt.style.display="none",bt.insertBefore(Bt,Z)),Je||(Je=document.createElement("input"),Je.type="file",Je.accept=((Im=re.allowedTypes)!=null?Im:Zo).join(","),Je.multiple=((Wm=re.maxFiles)!=null?Wm:4)>1,Je.style.display="none",Je.setAttribute("aria-label","Attach files"),bt.insertBefore(Je,Z)),vt=w("div","persona-send-button-wrapper"),Ne=w("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ne.type="button",Ne.setAttribute("aria-label",(Hm=re.buttonTooltipText)!=null?Hm:"Attach file");let rt=(Bm=re.buttonIconName)!=null?Bm:"paperclip",kt=$t,lr=parseFloat(kt)||40,wr=Math.round(lr*.6);Ne.style.width=kt,Ne.style.height=kt,Ne.style.minWidth=kt,Ne.style.minHeight=kt,Ne.style.fontSize="18px",Ne.style.lineHeight="1",Ne.style.backgroundColor="transparent",Ne.style.color="var(--persona-primary, #111827)",Ne.style.border="none",Ne.style.borderRadius="6px",Ne.style.transition="background-color 0.15s ease",Ne.addEventListener("mouseenter",()=>{Ne.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ne.addEventListener("mouseleave",()=>{Ne.style.backgroundColor="transparent"});let xo=fe(rt,wr,"currentColor",1.5);xo?Ne.appendChild(xo):Ne.textContent="\u{1F4CE}",Ne.addEventListener("click",Xr=>{Xr.preventDefault(),Je==null||Je.click()}),vt.appendChild(Ne);let kr=(Dm=re.buttonTooltipText)!=null?Dm:"Attach file",Yt=w("div","persona-send-button-tooltip");Yt.textContent=kr,vt.appendChild(Yt),st.append(vt),!wt&&Je&&Bt&&(wt=ea.fromConfig(re),wt.setPreviewsContainer(Bt),Je.addEventListener("change",async()=>{wt&&(Je!=null&&Je.files)&&(await wt.handleFileSelect(Je.files),Je.value="")})),ve.querySelector(".persona-attachment-drop-overlay")||ve.appendChild(dx(re.dropOverlay))}else{vt.style.display="";let re=(Fm=o.attachments)!=null?Fm:{};Je&&(Je.accept=((Nm=re.allowedTypes)!=null?Nm:Zo).join(","),Je.multiple=((Om=re.maxFiles)!=null?Om:4)>1),wt&&wt.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}else vt&&(vt.style.display="none"),wt&&wt.clearAttachments(),(_m=ve.querySelector(".persona-attachment-drop-overlay"))==null||_m.remove();let Kt=(Um=o.sendButton)!=null?Um:{},qn=(qm=Kt.useIcon)!=null?qm:!1,gn=(Vm=Kt.iconText)!=null?Vm:"\u2191",hn=Kt.iconName,Xo=(zm=Kt.tooltipText)!=null?zm:"Send message",Vn=($m=Kt.showTooltip)!=null?$m:!1,ho=(jm=Kt.size)!=null?jm:"40px",Bo=Kt.backgroundColor,Xe=Kt.textColor;if(qn){if(Ue.style.width=ho,Ue.style.height=ho,Ue.style.minWidth=ho,Ue.style.minHeight=ho,Ue.style.fontSize="18px",Ue.style.lineHeight="1",Ue.innerHTML="",Xe?Ue.style.color=Xe:Ue.style.color="var(--persona-button-primary-fg, #ffffff)",hn){let re=parseFloat(ho)||24,St=(Xe==null?void 0:Xe.trim())||"currentColor",$t=fe(hn,re,St,2);$t?Ue.appendChild($t):Ue.textContent=gn}else Ue.textContent=gn;Ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Bo?(Ue.style.backgroundColor=Bo,Ue.classList.remove("persona-bg-persona-primary")):(Ue.style.backgroundColor="",Ue.classList.add("persona-bg-persona-primary"))}else Ue.textContent=(Km=(Gm=o.copy)==null?void 0:Gm.sendButtonLabel)!=null?Km:"Send",Ue.style.width="",Ue.style.height="",Ue.style.minWidth="",Ue.style.minHeight="",Ue.style.fontSize="",Ue.style.lineHeight="",Ue.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",Bo?(Ue.style.backgroundColor=Bo,Ue.classList.remove("persona-bg-persona-accent")):Ue.classList.add("persona-bg-persona-accent"),Xe?Ue.style.color=Xe:Ue.classList.add("persona-text-white");Kt.borderWidth?(Ue.style.borderWidth=Kt.borderWidth,Ue.style.borderStyle="solid"):(Ue.style.borderWidth="",Ue.style.borderStyle=""),Kt.borderColor?Ue.style.borderColor=Kt.borderColor:Ue.style.borderColor="",Kt.paddingX?(Ue.style.paddingLeft=Kt.paddingX,Ue.style.paddingRight=Kt.paddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Kt.paddingY?(Ue.style.paddingTop=Kt.paddingY,Ue.style.paddingBottom=Kt.paddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let Ft=Ar==null?void 0:Ar.querySelector(".persona-send-button-tooltip");if(Vn&&Xo)if(Ft)Ft.textContent=Xo,Ft.style.display="";else{let re=document.createElement("div");re.className="persona-send-button-tooltip",re.textContent=Xo,Ar==null||Ar.insertBefore(re,Ue)}else Ft&&(Ft.style.display="none");let jt=(Zm=(Xm=o.layout)==null?void 0:Xm.contentMaxWidth)!=null?Zm:I()?(Ym=(Qm=(Jm=o.launcher)==null?void 0:Jm.composerBar)==null?void 0:Qm.contentMaxWidth)!=null?Ym:"720px":void 0;jt?(et.style.maxWidth=jt,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%",bt&&(bt.style.maxWidth=jt,bt.style.marginLeft="auto",bt.style.marginRight="auto"),Pt&&(Pt.style.maxWidth=jt,Pt.style.marginLeft="auto",Pt.style.marginRight="auto")):(et.style.maxWidth="",et.style.marginLeft="",et.style.marginRight="",et.style.width="",bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""),Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""));let Nt=(eg=o.statusIndicator)!=null?eg:{},Xt=(tg=Nt.visible)!=null?tg:!0;if(yr.style.display=Xt?"":"none",q){let re=q.getStatus();Qt(yr,($t=>{var rt,kt,lr,wr;return $t==="idle"?(rt=Nt.idleText)!=null?rt:Cr.idle:$t==="connecting"?(kt=Nt.connectingText)!=null?kt:Cr.connecting:$t==="connected"?(lr=Nt.connectedText)!=null?lr:Cr.connected:$t==="error"?(wr=Nt.errorText)!=null?wr:Cr.error:Cr[$t]})(re),Nt,re)}yr.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Et=Nt.align==="left"?"persona-text-left":Nt.align==="center"?"persona-text-center":"persona-text-right";yr.classList.add(Et)},open(){D()&&Vt(!0,"api")},close(){D()&&Vt(!1,"api")},toggle(){D()&&Vt(!O,"api")},clearChat(){Mr=!1,q.clearMessages(),Ro.clear(),Br();try{localStorage.removeItem(Va),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Va}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Va)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let d=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(d),l!=null&&l.clear)try{let g=l.clear();g instanceof Promise&&g.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}p={},A.syncFromMetadata(),j==null||j.clear(),Q==null||Q.reset(),Fe==null||Fe.update()},setMessage(d){return!Z||q.isStreaming()?!1:(!O&&D()&&Vt(!0,"system"),Z.value=d,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(d){if(q.isStreaming())return!1;let g=(d==null?void 0:d.trim())||Z.value.trim();return g?(!O&&D()&&Vt(!0,"system"),Z.value="",Z.style.height="auto",q.sendMessage(g),!0):!1},startVoiceRecognition(){var g,h;return q.isStreaming()?!1:((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype"?(q.isVoiceActive()||(!O&&D()&&Vt(!0,"system"),ct.manuallyDeactivated=!1,Hr(),q.toggleVoice().then(()=>{ct.active=q.isVoiceActive(),no("user"),q.isVoiceActive()&&ba()})),!0):Ho?!0:Vp()?(!O&&D()&&Vt(!0,"system"),ct.manuallyDeactivated=!1,Hr(),qs("user"),!0):!1},stopVoiceRecognition(){var d,g;return((g=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:g.type)==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{ct.active=!1,ct.manuallyDeactivated=!0,Hr(),no("user"),Ko()}),!0):!1:Ho?(ct.manuallyDeactivated=!0,Hr(),fn("user"),!0):!1},injectMessage(d){return!O&&D()&&Vt(!0,"system"),q.injectMessage(d)},injectAssistantMessage(d){!O&&D()&&Vt(!0,"system");let g=q.injectAssistantMessage(d);return J&&(J=!1,me&&(clearTimeout(me),me=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(d){return!O&&D()&&Vt(!0,"system"),q.injectUserMessage(d)},injectSystemMessage(d){return!O&&D()&&Vt(!0,"system"),q.injectSystemMessage(d)},injectMessageBatch(d){return!O&&D()&&Vt(!0,"system"),q.injectMessageBatch(d)},injectComponentDirective(d){return!O&&D()&&Vt(!0,"system"),q.injectComponentDirective(d)},injectTestMessage(d){!O&&D()&&Vt(!0,"system"),q.injectTestEvent(d)},async connectStream(d,g){return q.connectStream(d,g)},__pushEventStreamEvent(d){j&&(Q==null||Q.processEvent(d.type,d.payload),j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:d.type,timestamp:Date.now(),payload:JSON.stringify(d.payload)}))},showEventStream(){!le||!j||_o()},hideEventStream(){K&&uo()},isEventStreamVisible(){return K},showArtifacts(){po(o)&&(Mr=!1,Wr(),xt==null||xt.setMobileOpen(!0))},hideArtifacts(){po(o)&&(Mr=!0,Wr())},upsertArtifact(d){return po(o)?(Mr=!1,q.upsertArtifact(d)):null},selectArtifact(d){po(o)&&q.selectArtifact(d)},clearArtifacts(){po(o)&&q.clearArtifacts()},getArtifacts(){var d;return(d=q==null?void 0:q.getArtifacts())!=null?d:[]},getSelectedArtifactId(){var d;return(d=q==null?void 0:q.getSelectedArtifactId())!=null?d:null},focusInput(){return T&&!O&&!I()||!Z?!1:(Z.focus(),!0)},async resolveApproval(d,g,h){let R=q.getMessages().find(N=>{var z;return N.variant==="approval"&&((z=N.approval)==null?void 0:z.id)===d});if(!(R!=null&&R.approval))throw new Error(`Approval not found: ${d}`);if(R.approval.toolType==="webmcp"){q.resolveWebMcpApproval(R.id,g);return}return q.resolveApproval(R.approval,g,h)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(d){b(d)},on(d,g){return i.on(d,g)},off(d,g){i.off(d,g)},isOpen(){return D()&&O},isVoiceActive(){return ct.active},toggleReadAloud(d){q.toggleReadAloud(d)},stopReadAloud(){q.stopSpeaking()},getReadAloudState(d){return q.getReadAloudState(d)},onReadAloudChange(d){return q.onReadAloudChange(d)},getState(){return{open:D()&&O,launcherEnabled:T,voiceActive:ct.active,streaming:q.isStreaming()}},showCSATFeedback(d){!O&&D()&&Vt(!0,"system");let g=et.querySelector(".persona-feedback-container");g&&g.remove();let h=il({onSubmit:async(C,R)=>{var N;q.isClientTokenMode()&&await q.submitCSATFeedback(C,R),(N=d==null?void 0:d.onSubmit)==null||N.call(d,C,R)},onDismiss:d==null?void 0:d.onDismiss,...d});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(d){!O&&D()&&Vt(!0,"system");let g=et.querySelector(".persona-feedback-container");g&&g.remove();let h=ll({onSubmit:async(C,R)=>{var N;q.isClientTokenMode()&&await q.submitNPSFeedback(C,R),(N=d==null?void 0:d.onSubmit)==null||N.call(d,C,R)},onDismiss:d==null?void 0:d.onDismiss,...d});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(d,g){return q.submitCSATFeedback(d,g)},async submitNPSFeedback(d,g){return q.submitNPSFeedback(d,g)},destroy(){On!=null&&(clearInterval(On),On=null),ut.forEach(d=>d()),ge.remove(),dt==null||dt.remove(),Zt==null||Zt.destroy(),ir==null||ir.remove(),Lo&&P.removeEventListener("click",Lo)}};if((((Ju=r==null?void 0:r.debugTools)!=null?Ju:!1)||!!o.debug)&&typeof window!="undefined"){let d=window.AgentWidgetBrowser,g={controller:rr,getMessages:rr.getMessages,getStatus:rr.getStatus,getMetadata:rr.getPersistentMetadata,updateMetadata:rr.updatePersistentMetadata,clearHistory:()=>rr.clearChat(),setVoiceActive:h=>h?rr.startVoiceRecognition():rr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ut.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=d)})}if(typeof window!="undefined"){let d=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&rr.focusInput()};if(window.addEventListener("persona:focusInput",g),ut.push(()=>{window.removeEventListener("persona:focusInput",g)}),le){let U=oe=>{let ne=oe.detail;(!(ne!=null&&ne.instanceId)||ne.instanceId===d)&&rr.showEventStream()},_=oe=>{let ne=oe.detail;(!(ne!=null&&ne.instanceId)||ne.instanceId===d)&&rr.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",_),ut.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",_)})}let h=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&rr.showArtifacts()},C=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&rr.hideArtifacts()},R=U=>{let _=U.detail;_!=null&&_.instanceId&&_.instanceId!==d||_!=null&&_.artifact&&rr.upsertArtifact(_.artifact)},N=U=>{let _=U.detail;_!=null&&_.instanceId&&_.instanceId!==d||typeof(_==null?void 0:_.id)=="string"&&rr.selectArtifact(_.id)},z=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&rr.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",z),ut.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",z)})}let so=a0(o.persistState);if(so&&D()){let d=s0(so.storage),g=`${so.keyPrefix}widget-open`,h=`${so.keyPrefix}widget-voice`,C=`${so.keyPrefix}widget-voice-mode`;if(d){let R=((Qu=so.persist)==null?void 0:Qu.openState)&&d.getItem(g)==="true",N=((Yu=so.persist)==null?void 0:Yu.voiceState)&&d.getItem(h)==="true",z=((Zu=so.persist)==null?void 0:Zu.voiceState)&&d.getItem(C)==="true";if(R&&setTimeout(()=>{rr.open(),setTimeout(()=>{var U;if(N||z)rr.startVoiceRecognition();else if((U=so.persist)!=null&&U.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),(ef=so.persist)!=null&&ef.openState&&(i.on("widget:opened",()=>{d.setItem(g,"true")}),i.on("widget:closed",()=>{d.setItem(g,"false")})),(tf=so.persist)!=null&&tf.voiceState&&(i.on("voice:state",U=>{d.setItem(h,U.active?"true":"false")}),i.on("user:message",U=>{d.setItem(C,U.viaVoice?"true":"false")})),so.clearOnChatClear){let U=()=>{d.removeItem(g),d.removeItem(h),d.removeItem(C)},_=()=>U();window.addEventListener("persona:clear-chat",_),ut.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return u&&D()&&setTimeout(()=>{rr.open()},0),xa(),Fs||Gs().then(()=>{q&&(pa++,Ro.clear(),Ka(et,q.getMessages(),te))}).catch(()=>{}),rr};var i0=(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},l0=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},d0=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},c0=(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.")},cx=(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"},vp=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=""},px=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",vp(e)},xp=e=>{e.style.transition=""},yp=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"},pl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},p0=(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))},u0=(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)},ux=(e,t,r,o,n,a,s)=>{var x,b,L,E,A,T;let i=Qr(a),c=i.reveal==="push";p0(e,t,r,o,c),u0(e,t,r,o,i.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(b=(x=a==null?void 0:a.launcher)==null?void 0:x.mobileFullscreen)!=null?b:!0,f=(E=(L=a==null?void 0:a.launcher)==null?void 0:L.mobileBreakpoint)!=null?E:640,u=l!=null?l.innerWidth<=f:!1;if(p&&u&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),yp(t),xp(o),px(o),bp(r),pl(n,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((T=(A=a==null?void 0:a.launcher)==null?void 0:A.zIndex)!=null?T:Sr),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"),px(o),l0(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",yp(t),xp(o),bp(r),pl(n,o);let y=i.animate?"transform 180ms ease":"none",S=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=s?"translateX(0)":S;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=y,o.style.transform=v,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",xp(o),vp(o),pl(n,o);let y=i0(i.width,e.clientWidth),S=Math.max(0,e.clientWidth),v=i.animate?"margin-left 180ms ease":"none",M=i.side==="right"?s?-y:0:s?0:-y;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${S+y}px`,t.style.transition=v,t.style.marginLeft=`${M}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${S}px`,r.style.maxWidth=`${S}px`,r.style.minWidth=`${S}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",yp(t),vp(o),bp(r),pl(n,o);let y=i.reveal==="emerge";y?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=s?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",M=!s;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",d0(o,i.maxHeight),o.style.overflow=y||M?"hidden":"visible",o.style.transition=v,y&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.boxSizing="border-box")}},f0=(e,t)=>{let r=e.ownerDocument.createElement("div");return cx(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){cx(r,o)},destroy(){r.remove()}}},m0=(e,t)=>{var T,y,S,v;let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),c=r.createElement("div"),l=r.createElement("aside"),p=r.createElement("div"),f=(y=(T=t==null?void 0:t.launcher)==null?void 0:T.enabled)==null||y?(v=(S=t==null?void 0:t.launcher)==null?void 0:S.autoExpand)!=null?v:!1:!0;i.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),o.insertBefore(s,e),c.appendChild(e);let u=null,m=()=>{u==null||u.disconnect(),u=null},x=()=>{m(),Qr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{ux(s,i,c,l,p,t,f)}),u.observe(s))},b=!1,L=()=>{ux(s,i,c,l,p,t,f),x(),f&&!b&&s.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,c0(s,Qr(t)))},E=s.ownerDocument.defaultView,A=()=>{L()};return E==null||E.addEventListener("resize",A),Qr(t).reveal==="push"?(i.appendChild(c),i.appendChild(l),s.appendChild(i)):(s.appendChild(c),s.appendChild(l)),L(),{mode:"docked",host:p,shell:s,syncWidgetState(M){let W=M.launcherEnabled?M.open:!0;f!==W&&(f=W,L())},updateConfig(M){var W,H;t=M,((H=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)!=null?H:!0)===!1&&(f=!0),L()},destroy(){E==null||E.removeEventListener("resize",A),m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Bs=(e,t)=>nr(t)?m0(e,t):f0(e,t);var wp={},g0=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},h0=()=>{try{if(typeof wp!="undefined"&&wp.url)return new URL("../widget.css",wp.url).href}catch{}return null},fx=(e,t)=>{let r=h0(),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=>{var L;let t=g0(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Bs(t,n),s,i=[],c=(E,A)=>{var v,M;let y=!((M=(v=A==null?void 0:A.launcher)==null?void 0:v.enabled)!=null?M:!0)||nr(A),S=o.createElement("div");if(S.setAttribute("data-persona-root","true"),y&&(S.style.height="100%",S.style.display="flex",S.style.flexDirection="column",S.style.flex="1",S.style.minHeight="0"),r){let W=E.attachShadow({mode:"open"});W.appendChild(S),fx(W,o)}else E.appendChild(S),fx(E,o);return t.id&&S.setAttribute("data-persona-instance",t.id),S},l=()=>{a.syncWidgetState(s.getState())},p=()=>{i.forEach(E=>E()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},f=()=>{let E=c(a.host,n);s=cl(E,n,{debugTools:e.debugTools}),p()},u=()=>{i.forEach(E=>E()),i=[],s.destroy()};f(),(L=e.onChatReady)==null||L.call(e);let m=E=>{u(),a.destroy(),a=Bs(t,E),n=E,f()},x={update(E){var M,W,H,I,D,O;let A={...n,...E,launcher:{...(M=n==null?void 0:n.launcher)!=null?M:{},...(W=E==null?void 0:E.launcher)!=null?W:{},dock:{...(I=(H=n==null?void 0:n.launcher)==null?void 0:H.dock)!=null?I:{},...(O=(D=E==null?void 0:E.launcher)==null?void 0:D.dock)!=null?O:{}}}},T=nr(n),y=nr(A),S=Ln(n),v=Ln(A);if(T!==y||S!==v){m(A);return}n=A,a.updateConfig(n),s.update(E),l()},destroy(){u(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},b=new Proxy(x,{get(E,A,T){if(A==="host")return a.host;if(A in E)return Reflect.get(E,A,T);let y=s[A];return typeof y=="function"?y.bind(s):y}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=b),b};var bx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),x0=new Set(["button","a","input","select","textarea","details","summary"]),y0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Cp=/\b(product|card|item|listing|result)\b/i,Ap=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,b0=3e3,v0=100;function vx(e){let t=typeof e.className=="string"?e.className:"";if(Cp.test(t)||e.id&&Cp.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&Cp.test(o.value))return!0}return!1}function wx(e){var t;return Ap.test(((t=e.textContent)!=null?t:"").trim())}function Cx(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 w0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function gx(e){let t=e.match(Ap);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 C0(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 S0="commerce-card",A0="result-card";function xx(e){return!vx(e)||!wx(e)||!Cx(e)&&!w0(e)?0:5200}function yx(e){var o;return!vx(e)||wx(e)||!Cx(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 Mp=[{id:S0,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||Ap.test(o)&&o.length<32)}return!0},formatSummary(e,t){var c,l,p;if(xx(e)===0)return null;let{title:r,href:o}=hx(e),n=(p=(l=gx(((c=e.textContent)!=null?c:"").trim()))!=null?l:gx(t.text))!=null?p:"",a=C0(e);return[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
113
- `)}},{id:A0,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(`
114
- `)}}];function M0(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function T0(e){var p,f,u,m,x,b,L,E,A,T,y,S,v;let t=(p=e.options)!=null?p:{},r=(u=(f=t.maxElements)!=null?f:e.maxElements)!=null?u:80,o=(x=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",n=(L=(b=t.maxTextLength)!=null?b:e.maxTextLength)!=null?L:200,a=(A=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?A:!0,s=(T=t.root)!=null?T:e.root,i=(y=t.mode)!=null?y:"structured",c=(S=t.maxCandidates)!=null?S:Math.max(500,r*10),l=(v=e.rules)!=null?v:Mp;return i==="simple"&&e.rules&&e.rules.length>0?(M0(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:r,maxCandidates:c,excludeSelector:o,maxTextLength:n,visibleOnly:a,root:s,rules:l}}function Sp(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var E0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function k0(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"||x0.has(t)||r&&y0.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 L0(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let c=e.getAttribute("role");c&&(t.role=c);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Tp(e){let t=e.tagName.toLowerCase();if(e.id){let n=`#${Sp(e.id)}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}}for(let n of E0){let a=e.getAttribute(n);if(a){let s=`${t}[${n}="${Sp(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=>Sp(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 P0(e){return e==="static"?v0:b0}function Ax(e,t){var n;let r=e.tagName.toLowerCase(),o=((n=e.textContent)!=null?n:"").trim().substring(0,t);return{selector:Tp(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:k0(e),attributes:L0(e)}}function R0(e,t,r,o){let n=P0(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 I0(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 W0(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(bx.has(p)){i=s.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Sx(l)){i=s.nextNode();continue}let f=Ax(l,e.maxTextLength),u=f.text.length>0,m=Object.keys(f.attributes).length>0&&!Object.keys(f.attributes).every(L=>L==="role");if(!u&&!m){i=s.nextNode();continue}if(o.has(f.selector)){i=s.nextNode();continue}o.add(f.selector);let{score:x,formattingRule:b}=R0(l,f,e.rules,r);n.push({el:l,domIndex:a,enriched:f,score:x,formattingRule:b}),a+=1}i=s.nextNode()}n.sort((l,p)=>{let f=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return f!==u?f-u:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let c=[];for(let l of n){if(c.length>=e.maxElements)break;I0(c,l)||c.push(l)}return c.sort((l,p)=>{let f=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return f!==u?f-u:f===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),c.map(l=>{var u;let p;if((u=l.formattingRule)!=null&&u.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,r);m&&(p=m)}let f={...l.enriched};return p&&(f.formattedSummary=p),f})}function H0(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,l=c.tagName.toLowerCase();if(bx.has(l)){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 p=Ax(c,e.maxTextLength),f=p.text.length>0,u=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!f&&!u){a=n.nextNode();continue}o.has(p.selector)||(o.add(p.selector),r.push(p))}a=n.nextNode()}let s=[],i=[];for(let c of r)c.interactivity!=="static"?s.push(c):i.push(c);return[...s,...i].slice(0,e.maxElements)}function Mx(e={}){var o;let t=T0(e),r=(o=t.root)!=null?o:document.body;return r?t.mode==="simple"?H0(t,r):W0(t,r):[]}var ul=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:
112
+ `}if(!C&&!d){let Bt="max-height: -moz-available !important; max-height: stretch !important;",zt=m?"":"padding-top: 1.25em !important;",Dt=m?"":`z-index: ${(Xe=(Oo=o.launcher)==null?void 0:Oo.zIndex)!=null?Xe:Cr} !important;`;xe.style.cssText+=Bt+zt+Dt}je()};xn(),Hn(e,o),al(e,o),sl(e,o);let st=[];st.push(()=>{document.removeEventListener("keydown",Xo)}),st.push(()=>{uo!==null&&clearTimeout(uo)});let ar=null,sr=null;st.push(()=>{ar==null||ar(),ar=null,sr==null||sr(),sr=null}),Dr&&st.push(()=>{Dr==null||Dr.disconnect(),Dr=null}),st.push(()=>{Zr==null||Zr(),Zr=null,ya(),_t&&(_t.remove(),_t=null),ht==null||ht.element.style.removeProperty("width"),ht==null||ht.element.style.removeProperty("maxWidth")}),de&&st.push(()=>{pe!==null&&(cancelAnimationFrame(pe),pe=null),Ne==null||Ne.destroy(),Ne=null,j==null||j.destroy(),j=null,ke=null});let Io=null,Za=()=>{Io&&(Io(),Io=null),o.colorScheme==="auto"&&(Io=Fi(()=>{Hn(e,o)}))};Za(),st.push(()=>{Io&&(Io(),Io=null)}),st.push(s);let Jo=(nf=o.features)==null?void 0:nf.streamAnimation;if(Jo!=null&&Jo.type&&Jo.type!=="none"){let d=Rs(Jo.type,Jo.plugins);d&&(tp(d,e),st.push(()=>Fh(e)))}let zn=ox(Lt),Wo=null,q,ba=d=>{var C,R;if(!q)return;let m=d!=null?d:q.getMessages(),h=((R=(C=o.features)==null?void 0:C.suggestReplies)==null?void 0:R.enabled)!==!1?li(m):null;h?zn.render(h,q,Z,m,o.suggestionChipsConfig,{agentPushed:!0}):m.some(D=>D.role==="user")?zn.render([],q,Z,m):zn.render(o.suggestionChips,q,Z,m,o.suggestionChipsConfig)},mo=!1,Ho=kh(),Yo=new Map,Bo=new Map,go=new Map,va=0,zs=ta()!==null,yr=_i(),Mr=0,ho=null,Tr=!1,jn=!1,xo=0,br=null,Do=null,wa=!1,Gn=!1,Ca=null,Fo=!0,Ze=!1,k=null,z=4,V=24,G=80,me=new Map,oe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ut=(sf=(af=o.voiceRecognition)==null?void 0:af.autoResume)!=null?sf:!1,ct=d=>{i.emit("voice:state",{active:oe.active,source:d,timestamp:Date.now()})},Or=()=>{b(d=>({...d,voiceState:{active:oe.active,timestamp:Date.now(),manuallyDeactivated:oe.manuallyDeactivated}}))},yn=()=>{var C,R;if(((C=o.voiceRecognition)==null?void 0:C.enabled)===!1)return;let d=Sp(p.voiceState),m=!!d.active,h=Number((R=d.timestamp)!=null?R:0);oe.manuallyDeactivated=!!d.manuallyDeactivated,m&&Date.now()-h<w0&&setTimeout(()=>{var D,$;oe.active||(oe.manuallyDeactivated=!1,(($=(D=o.voiceRecognition)==null?void 0:D.provider)==null?void 0:$.type)==="runtype"?q.toggleVoice().then(()=>{oe.active=q.isVoiceActive(),ct("restore"),q.isVoiceActive()&&Ma()}):Gs("restore"))},1e3)},eo=()=>q?Cx(q.getMessages()).filter(d=>!d.__skipPersist):[];function ir(d){if(!(l!=null&&l.save))return;let h={messages:d?Cx(d):q?eo():[],metadata:p,artifacts:Fr.artifacts,selectedArtifactId:Fr.selectedId};try{let C=l.save(h);C instanceof Promise&&C.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(C){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)}}let to=null,Zo=()=>xe.querySelector("#persona-scroll-container")||be,ur=()=>{to!==null&&(cancelAnimationFrame(to),to=null),Tr=!1},Er=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),jn=!1,ur()},_r=()=>mo&&bl()&&(Ot()!=="anchor-top"||co()),yl=()=>{let d=gt()||"Jump to latest",m=_r();$t.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),xo>0?(Hr.textContent=String(xo),Hr.style.display="",$t.setAttribute("aria-label",`${d} (${xo} new)`)):(Hr.textContent="",Hr.style.display="none",$t.setAttribute("aria-label",m?`${d} (response streaming below)`:d))},_p=()=>{xo!==0&&(xo=0,yl())},bl=()=>tr()?!yr.isFollowing():!Bn(be,V),Ur=()=>{if(!Xt()||K){$t.parentNode&&$t.remove(),$t.style.display="none";return}$t.parentNode!==Ce&&Ce.appendChild($t),Xr();let m=Vo(be)>0&&bl();m?yl():_p(),$t.style.display=m?"":"none"},es=()=>{yr.pause()&&(Er(),Ur())},bn=()=>{yr.resume(),_p(),Ur()},vn=(d=!1)=>{tr()&&yr.isFollowing()&&(!d&&!mo||(ho!==null&&(cancelAnimationFrame(ho),ho=null),jn=!0,ho=requestAnimationFrame(()=>{ho=null,jn=!1,yr.isFollowing()&&iy(Zo(),d?220:140)})))},Up=(d,m,h,C=()=>!0)=>{let R=d.scrollTop,D=m(),$=D-R;if(ur(),Math.abs($)<1){Tr=!0,d.scrollTop=D,Mr=d.scrollTop,Tr=!1;return}let U=performance.now();Tr=!0;let _=ae=>1-Math.pow(1-ae,3),ie=ae=>{if(!C()){ur();return}let Y=m();Y!==D&&(D=Y,$=D-R);let ve=ae-U,De=Math.min(ve/h,1),Se=_(De),Je=R+$*Se;d.scrollTop=Je,Mr=d.scrollTop,De<1?to=requestAnimationFrame(ie):(d.scrollTop=D,Mr=d.scrollTop,to=null,Tr=!1)};to=requestAnimationFrame(ie)},iy=(d,m=500)=>{let h=Vo(d)-d.scrollTop;if(Math.abs(h)<1){Mr=d.scrollTop;return}if(Math.abs(h)>=G){ur(),Tr=!0,d.scrollTop=Vo(d),Mr=d.scrollTop,Tr=!1;return}Up(d,()=>Vo(d),m,()=>yr.isFollowing())},qp=()=>{let d=Zo();Tr=!0,d.scrollTop=Vo(d),Mr=d.scrollTop,Tr=!1,Ur()},Vp=d=>{let m=0,h=d;for(;h&&h!==be;)m+=h.offsetTop,h=h.offsetParent;return m},$p=()=>{var D;if(zo()!=="last-user-turn")return!1;let d=(D=q==null?void 0:q.getMessages())!=null?D:[];if(d.length<2)return!1;let m=[...d].reverse().find($=>$.role==="user");if(!m)return!1;let h=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),C=be.querySelector(`[data-message-id="${h}"]`);if(!C)return!1;let R=Math.min(Math.max(0,Vp(C)-To()),Vo(be));return Tr=!0,be.scrollTop=R,Mr=be.scrollTop,Tr=!1,Ot()==="follow"&&!Bn(be,V)&&yr.pause(),Ur(),!0},zp=d=>{Rr.style.height=`${Math.max(0,Math.round(d))}px`,br&&(br.spacerHeight=Math.max(0,d))},ts=()=>{Do!==null&&(cancelAnimationFrame(Do),Do=null),ur(),br=null,Rr.style.height="0px"},ly=d=>{Do!==null&&cancelAnimationFrame(Do),Do=requestAnimationFrame(()=>{var _;Do=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(d):d.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=be.querySelector(`[data-message-id="${m}"]`);if(!h)return;let C=Vp(h),R=(_=br==null?void 0:br.spacerHeight)!=null?_:0,D=be.scrollHeight-R,{targetScrollTop:$,spacerHeight:U}=Wh({anchorOffsetTop:C,topOffset:To(),viewportHeight:be.clientHeight,contentHeight:D});br={initialSpacerHeight:U,contentHeightAtAnchor:D,spacerHeight:U},zp(U),Up(be,()=>$,220)})},dy=()=>{if(tr()){if(!yr.isFollowing()||Bn(be,1))return;vn(!mo);return}if(br&&br.initialSpacerHeight>0){let d=be.scrollHeight-br.spacerHeight,m=Hh({initialSpacerHeight:br.initialSpacerHeight,contentHeightAtAnchor:br.contentHeightAtAnchor,currentContentHeight:d});m!==br.spacerHeight&&zp(m)}Ur()},cy=d=>{let m=Ot();m==="follow"?(bn(),vn(!0)):m==="anchor-top"&&(Fo=!1,Ze=!0,ly(d))},py=()=>{if(Ot()==="anchor-top"){if(Ze){Fo=!1;return}Fo=!0,ts(),bn(),vn(!0)}},uy=d=>{let m=new Map;d.forEach(h=>{let C=me.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!C&&h.role==="assistant"&&(i.emit("assistant:message",h),!Gn&&(Ot()!=="anchor-top"||co())&&bl()&&(xo+=1,yl(),Ur(),cn(xo===1?"1 new message below.":`${xo} new messages below.`))),h.role==="assistant"&&(C!=null&&C.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(C?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),me.clear(),m.forEach((h,C)=>{me.set(C,h)})},fy=(d,m,h)=>{var tt,Pe,Ee,ze,je,ft;let C=document.createElement("div"),D=(()=>{var Ie;let B=n.find(Re=>Re.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Ie=o.loadingIndicator)!=null&&Ie.render)return o.loadingIndicator.render})(),$=(B,Ie)=>Ie==null?!1:typeof Ie=="string"?(B.textContent=Ie,!0):(B.appendChild(Ie),!0),U=new Set,_=new Set,ie=n.some(B=>B.renderAskUserQuestion),ae=[],Y=[],ve=o.enableComponentStreaming!==!1,De=o.approval!==!1,Se=[];if(m.forEach(B=>{var Ke,Mt,or,no,Vr,Xn,Qn,Ea,ka,Gt,Jn,Sn,An,tn,Yn,yo,Oo;U.add(B.id);let Ie=ie&&rn(B),Re=De&&B.variant==="approval"&&!!B.approval,fe=!Ie&&B.role==="assistant"&&!B.variant&&ve&&cl(B);if(!Re&&go.has(B.id)){let Xe=d.querySelector(`#wrapper-${B.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime"),go.delete(B.id)}if(!fe&&Bo.has(B.id)){let Xe=d.querySelector(`#wrapper-${B.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime"),Bo.delete(B.id)}let Ht=rn(B)?`:${(Ke=B.agentMetadata)!=null&&Ke.askUserQuestionAnswered?"a":"u"}:${(Mt=B.agentMetadata)!=null&&Mt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Rt=Eh(B,va)+Ht,jt=Ie||Re||fe?null:Lh(Ho,B.id,Rt);if(jt){C.appendChild(jt.cloneNode(!0)),rn(B)&&((or=B.toolCall)!=null&&or.id)&&((no=B.agentMetadata)==null?void 0:no.awaitingLocalTool)===!0&&!((Vr=B.agentMetadata)!=null&&Vr.askUserQuestionAnswered)&&(_.add(B.toolCall.id),Ba(B,o,$e.composerOverlay));return}let mt=null,qt=n.find(Xe=>!!(B.variant==="reasoning"&&Xe.renderReasoning||B.variant==="tool"&&Xe.renderToolCall||!B.variant&&Xe.renderMessage)),qr=(Xn=o.layout)==null?void 0:Xn.messages;if(rn(B)&&((Qn=B.agentMetadata)==null?void 0:Qn.askUserQuestionAnswered)===!0){Yo.delete(B.id);let Xe=d.querySelector(`#wrapper-${B.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime");return}if(ys(B)&&((ka=(Ea=o.features)==null?void 0:Ea.suggestReplies)==null?void 0:ka.enabled)!==!1)return;if(rn(B)&&((Jn=(Gt=o.features)==null?void 0:Gt.askUserQuestion)==null?void 0:Jn.enabled)!==!1){let Xe=n.find(Bt=>typeof Bt.renderAskUserQuestion=="function");if(Xe&&wt.current){let Bt=Yo.get(B.id),zt=Bt!==Rt,Dt=null;if(zt){let{payload:Nt,complete:fr}=on(B),$r=B.id,_o=()=>{var mr;return(mr=wt.current)==null?void 0:mr.getMessages().find(gr=>gr.id===$r)};Dt=Xe.renderAskUserQuestion({message:B,payload:Nt,complete:fr,resolve:mr=>{var ao;let gr=_o();gr&&((ao=wt.current)==null||ao.resolveAskUserQuestion(gr,mr))},dismiss:()=>{var gr,ao,Mn;let mr=_o();(gr=mr==null?void 0:mr.agentMetadata)!=null&&gr.awaitingLocalTool&&((ao=wt.current)==null||ao.markAskUserQuestionResolved(mr),(Mn=wt.current)==null||Mn.resolveAskUserQuestion(mr,"(dismissed)"))},config:o})}let Kt=Bt!=null;if(zt&&Dt===null&&!Kt){((Sn=B.agentMetadata)==null?void 0:Sn.awaitingLocalTool)===!0&&!((An=B.agentMetadata)!=null&&An.askUserQuestionAnswered)&&(_.add(B.toolCall.id),Ba(B,o,$e.composerOverlay));return}let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id=`wrapper-${B.id}`,Tt.setAttribute("data-wrapper-id",B.id),Tt.setAttribute("data-ask-plugin-stub","true"),Tt.setAttribute("data-preserve-runtime","true"),C.appendChild(Tt),ae.push({messageId:B.id,fingerprint:Rt,bubble:Dt});return}else{((tn=B.agentMetadata)==null?void 0:tn.awaitingLocalTool)===!0&&!((Yn=B.agentMetadata)!=null&&Yn.askUserQuestionAnswered)&&(_.add(B.toolCall.id),Ba(B,o,$e.composerOverlay));return}}else if(Re){let Xe=(yo=n.find(Kt=>typeof Kt.renderApproval=="function"))!=null?yo:a,zt=go.get(B.id)!==Rt,Dt=null;if(zt&&(Xe!=null&&Xe.renderApproval)){let Kt=B.id,Tt=(Nt,fr)=>{var _o,mr,gr;let $r=(_o=wt.current)==null?void 0:_o.getMessages().find(ao=>ao.id===Kt);$r!=null&&$r.approval&&($r.approval.toolType==="webmcp"?(mr=wt.current)==null||mr.resolveWebMcpApproval($r.id,Nt):(gr=wt.current)==null||gr.resolveApproval($r.approval,Nt,fr))};Dt=Xe.renderApproval({message:B,defaultRenderer:()=>ol(B,o),config:o,approve:Nt=>Tt("approved",Nt),deny:Nt=>Tt("denied",Nt)})}if(zt&&Dt===null){let Kt=d.querySelector(`#wrapper-${B.id}`);Kt==null||Kt.removeAttribute("data-preserve-runtime"),go.delete(B.id),mt=ol(B,o)}else{let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id=`wrapper-${B.id}`,Kt.setAttribute("data-wrapper-id",B.id),Kt.setAttribute("data-approval-plugin-stub","true"),Kt.setAttribute("data-preserve-runtime","true"),C.appendChild(Kt),Se.push({messageId:B.id,fingerprint:Rt,bubble:Dt});return}}else if(qt)if(B.variant==="reasoning"&&B.reasoning&&qt.renderReasoning){if(!Te)return;mt=qt.renderReasoning({message:B,defaultRenderer:()=>fp(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&qt.renderToolCall){if(!We)return;mt=qt.renderToolCall({message:B,defaultRenderer:()=>gp(B,o),config:o})}else qt.renderMessage&&(mt=qt.renderMessage({message:B,defaultRenderer:()=>{let Xe=$a(B,h,qr,o.messageActions,ot,{loadingIndicatorRenderer:D,widgetConfig:o});return B.role!=="user"&&vp(Xe,B,o,q),Xe},config:o}));if(!mt&&fe){let Xe=pl(B);if(Xe){let Bt=Bo.get(B.id),zt=Bt!==Rt,Dt=o.wrapComponentDirectiveInBubble!==!1,Kt=null;if(zt){let Tt=dl(Xe,{config:o,message:B,transform:h});if(Tt)if(Dt){let Nt=document.createElement("div");if(Nt.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(" "),Nt.id=`bubble-${B.id}`,Nt.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let fr=document.createElement("div");fr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",fr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Nt.appendChild(fr)}Nt.appendChild(Tt),Kt=Nt}else{let Nt=document.createElement("div");if(Nt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Nt.id=`bubble-${B.id}`,Nt.setAttribute("data-message-id",B.id),Nt.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let fr=document.createElement("div");fr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",fr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Nt.appendChild(fr)}Nt.appendChild(Tt),Kt=Nt}}if(Kt||Bt!=null){let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id=`wrapper-${B.id}`,Tt.setAttribute("data-wrapper-id",B.id),Tt.setAttribute("data-component-directive-stub","true"),Tt.setAttribute("data-preserve-runtime","true"),Dt||Tt.classList.add("persona-w-full"),C.appendChild(Tt),Y.push({messageId:B.id,fingerprint:Rt,bubble:Kt});return}}}if(!mt)if(B.variant==="reasoning"&&B.reasoning){if(!Te)return;mt=fp(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!We)return;mt=gp(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;mt=ol(B,o)}else{let Xe=(Oo=o.layout)==null?void 0:Oo.messages;Xe!=null&&Xe.renderUserMessage&&B.role==="user"?mt=Xe.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):Xe!=null&&Xe.renderAssistantMessage&&B.role==="assistant"?mt=Xe.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):mt=$a(B,h,Xe,o.messageActions,ot,{loadingIndicatorRenderer:D,widgetConfig:o}),B.role!=="user"&&mt&&vp(mt,B,o,q)}let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-${B.id}`,Zt.setAttribute("data-wrapper-id",B.id),B.role==="user"&&Zt.classList.add("persona-justify-end"),(mt==null?void 0:mt.getAttribute("data-persona-component-directive"))==="true"&&Zt.classList.add("persona-w-full"),Zt.appendChild(mt),Ph(Ho,B.id,Rt,Zt),C.appendChild(Zt)}),$e.composerOverlay&&$e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ie=>{let Re=Ie.getAttribute("data-persona-ask-sheet-for");Re&&!_.has(Re)&&Ln($e.composerOverlay,Re)}),(Pe=(tt=o.features)==null?void 0:tt.toolCallDisplay)!=null&&Pe.grouped){let B=[],Ie=[];m.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&We){Ie.push(Re);return}Ie.length>1&&B.push(Ie),Ie=[]}),Ie.length>1&&B.push(Ie),B.forEach((Re,fe)=>{var Ke,Mt;let Ht=Re.map(or=>Array.from(C.children).find(no=>no instanceof HTMLElement&&no.getAttribute("data-wrapper-id")===or.id)).filter(or=>!!or);if(Ht.length<2)return;let Rt=document.createElement("div");Rt.className="persona-flex",Rt.id=`wrapper-tool-group-${fe}-${Re[0].id}`,Rt.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 mt=document.createElement("div");mt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Re.length} tools`,qr=(Mt=(Ke=o.toolCall)==null?void 0:Ke.renderGroupedSummary)==null?void 0:Mt.call(Ke,{messages:Re,toolCalls:Re.map(or=>or.toolCall).filter(or=>!!or),defaultSummary:qt,config:o});$(mt,qr)||(mt.textContent=qt);let Zt=document.createElement("div");Zt.className="persona-tool-group-stack persona-flex persona-flex-col",jt.append(mt,Zt),Rt.appendChild(jt),Ht[0].before(Rt),Ht.forEach((or,no)=>{let Vr=document.createElement("div");Vr.className="persona-tool-group-item persona-relative",Vr.setAttribute("data-persona-tool-group-item","true"),no<Ht.length-1&&Vr.setAttribute("data-persona-tool-group-connector","true"),Vr.appendChild(or),Zt.appendChild(Vr)})})}Rh(Ho,U);let Je=m.some(B=>B.role==="assistant"&&B.streaming),Ve=m[m.length-1],lt=(Ve==null?void 0:Ve.role)==="assistant"&&!Ve.streaming&&Ve.variant!=="approval";if(mo&&m.some(B=>B.role==="user")&&!Je&&!lt){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ua},Ie=n.find(fe=>fe.renderLoadingIndicator),Re=null;if(Ie!=null&&Ie.renderLoadingIndicator&&(Re=Ie.renderLoadingIndicator(B)),Re===null&&((Ee=o.loadingIndicator)!=null&&Ee.render)&&(Re=o.loadingIndicator.render(B)),Re===null&&(Re=ua()),Re){let fe=document.createElement("div"),Ht=((ze=o.loadingIndicator)==null?void 0:ze.showBubble)!==!1;fe.className=Ht?["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 Rt=document.createElement("div");Rt.className="persona-flex",Rt.id="wrapper-typing-indicator",Rt.setAttribute("data-wrapper-id","typing-indicator"),Rt.appendChild(fe),C.appendChild(Rt)}}if(!mo&&m.length>0){let B=m[m.length-1],Ie={config:o,lastMessage:B,messageCount:m.length},Re=n.find(Ht=>Ht.renderIdleIndicator),fe=null;if(Re!=null&&Re.renderIdleIndicator&&(fe=Re.renderIdleIndicator(Ie)),fe===null&&((je=o.loadingIndicator)!=null&&je.renderIdle)&&(fe=o.loadingIndicator.renderIdle(Ie)),fe){let Ht=document.createElement("div"),Rt=((ft=o.loadingIndicator)==null?void 0:ft.showBubble)!==!1;Ht.className=Rt?["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(" "),Ht.setAttribute("data-idle-indicator","true"),Ht.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(Ht),C.appendChild(jt)}}if(Ni(d,C),ae.length>0)for(let{messageId:B,fingerprint:Ie,bubble:Re}of ae){let fe=d.querySelector(`#wrapper-${B}`);fe&&Re!==null&&(fe.replaceChildren(Re),fe.setAttribute("data-bubble-fp",Ie),Yo.set(B,Ie))}if(Yo.size>0)for(let B of Yo.keys())U.has(B)||Yo.delete(B);if(Y.length>0)for(let{messageId:B,fingerprint:Ie,bubble:Re}of Y){let fe=d.querySelector(`#wrapper-${B}`);fe&&Re!==null&&(fe.replaceChildren(Re),fe.setAttribute("data-bubble-fp",Ie),Bo.set(B,Ie))}if(Bo.size>0)for(let B of Bo.keys())U.has(B)||Bo.delete(B);if(Se.length>0)for(let{messageId:B,fingerprint:Ie,bubble:Re}of Se){let fe=d.querySelector(`#wrapper-${B}`);fe&&Re!==null&&(fe.replaceChildren(Re),fe.setAttribute("data-bubble-fp",Ie),go.set(B,Ie))}if(go.size>0)for(let B of go.keys())U.has(B)||go.delete(B)},rs=(d,m,h)=>{fy(d,m,h),gn()},os=null,my=()=>{var h;if(os)return;let d=C=>{let R=C.composedPath();R.includes(xe)||dt&&R.includes(dt)||Ut(!1,"user")};os=d,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",d,!0)},jp=()=>{var m;if(!os)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",os,!0),os=null};st.push(()=>jp());let ns=null,gy=()=>{var h;if(ns)return;let d=C=>{C.key==="Escape"&&(C.isComposing||Ut(!1,"user"))};ns=d,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",d,!0)},Gp=()=>{var m;if(!ns)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",ns,!0),ns=null};st.push(()=>Gp());let as=!1,Kp=new Set,hy=()=>{var m,h,C,R;let d=(C=(h=(m=o.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:C.streamAnimation;return d||((R=o.features)==null?void 0:R.streamAnimation)},Sa=()=>{var lt,tt,Pe,Ee;if(!I())return;let d=$e.peekBanner,m=$e.peekTextNode;if(!d||!m)return;if(O){d.classList.remove("persona-pill-peek--visible");return}let h=(lt=q==null?void 0:q.getMessages())!=null?lt:[],C;for(let ze=h.length-1;ze>=0;ze--){let je=h[ze];if(je.role==="assistant"&&je.content){C=je;break}}if(!C){d.classList.remove("persona-pill-peek--visible");return}let R=C.content,D=!!C.streaming,$=hy(),U=Vi($),_=U.type!=="none"?Rs(U.type,$==null?void 0:$.plugins):null,ie=((tt=_==null?void 0:_.isAnimating)==null?void 0:tt.call(_,C))===!0,ae=_!==null&&(D||ie);ae&&_&&!Kp.has(_.name)&&(tp(_,e),Kp.add(_.name));let Y=ae&&(_!=null&&_.containerClass)?_.containerClass:null,ve=(Pe=m.dataset.personaPeekStreamClass)!=null?Pe:null;ve&&ve!==Y&&(m.classList.remove(ve),delete m.dataset.personaPeekStreamClass),Y&&ve!==Y&&(m.classList.add(Y),m.dataset.personaPeekStreamClass=Y),ae?(m.style.setProperty("--persona-stream-step",`${U.speed}ms`),m.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let De=ae?$i(R,U.buffer,_,C,D):R;if(ae&&U.placeholder==="skeleton"&&D&&(!De||!De.trim())){let ze=document.createElement("div"),je=Ws();je.classList.add("persona-pill-peek__skeleton"),ze.appendChild(je),Ni(m,ze)}else{let ze=Math.max(0,De.length-100),je=De.length>100?De.slice(-100):De,ft=Uo(je);if(!ae||!_){let B=De.length>100?`\u2026${je}`:je;m.textContent!==B&&(m.textContent=B)}else{let B=ft;(_.wrap==="char"||_.wrap==="word")&&(B=Is(ft,_.wrap,`peek-${C.id}`,{skipTags:_.skipTags,startIndex:ze}));let Ie=document.createElement("div");if(Ie.innerHTML=B,_.useCaret&&je.length>0){let Re=zi(),fe=Ie.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ht=fe[fe.length-1];Ht!=null&&Ht.parentNode?Ht.parentNode.insertBefore(Re,Ht.nextSibling):Ie.appendChild(Re)}Ni(m,Ie),(Ee=_.onAfterRender)==null||Ee.call(_,{container:m,bubble:d,messageId:C.id,message:C,speed:U.speed,duration:U.duration})}}let Ve=mo||as;d.classList.toggle("persona-pill-peek--visible",Ve)};if(I()){let d=$e.peekBanner;if(d){let C=R=>{R.preventDefault(),R.stopPropagation(),Ut(!0,"user")};d.addEventListener("pointerdown",C),st.push(()=>{d.removeEventListener("pointerdown",C)})}let m=()=>{as||(as=!0,Sa())},h=()=>{as&&(as=!1,Sa())};X.addEventListener("pointerenter",m),X.addEventListener("pointerleave",h),st.push(()=>{X.removeEventListener("pointerenter",m),X.removeEventListener("pointerleave",h)}),dt&&(dt.addEventListener("pointerenter",m),dt.addEventListener("pointerleave",h),st.push(()=>{dt.removeEventListener("pointerenter",m),dt.removeEventListener("pointerleave",h)}))}let xy=d=>{var ve,De,Se,Je,Ve,lt,tt,Pe;let m=(De=(ve=o.launcher)==null?void 0:ve.composerBar)!=null?De:{},h=(Se=m.expandedSize)!=null?Se:"anchored",C=(Je=m.bottomOffset)!=null?Je:"16px",R=m.collapsedMaxWidth,D=(Ve=m.expandedMaxWidth)!=null?Ve:"880px",$=(lt=m.expandedTopOffset)!=null?lt:"5vh",U=(tt=m.modalMaxWidth)!=null?tt:"880px",_=(Pe=m.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",ie="calc(100vw - 32px)",ae="var(--persona-pill-area-height, 80px)",Y=xe.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",dt){let Ee=dt.style;Ee.bottom=C,Ee.width=R!=null?R:""}if(d&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=U,Y.maxWidth=ie,Y.maxHeight=_,Y.height=_;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${C} + ${ae})`,Y.top=$,Y.width=D,Y.maxWidth=ie}},ss=()=>{var _,ie,ae,Y,ve,De,Se,Je;if(!F())return;if(I()){let lt=(ae=((ie=(_=o.launcher)==null?void 0:_.composerBar)!=null?ie:{}).expandedSize)!=null?ae:"anchored",tt=O?"expanded":"collapsed";xe.dataset.state=tt,xe.dataset.expandedSize=lt,dt&&(dt.dataset.state=tt,dt.dataset.expandedSize=lt),xe.style.removeProperty("display"),xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),xy(O),Ce.style.display=O?"flex":"none",xn(),O?(my(),gy()):(jp(),Gp()),Sa();return}let d=nr(o),m=(Y=e.ownerDocument.defaultView)!=null?Y:window,h=(De=(ve=o.launcher)==null?void 0:ve.mobileBreakpoint)!=null?De:640,C=(Je=(Se=o.launcher)==null?void 0:Se.mobileFullscreen)!=null?Je:!0,R=m.innerWidth<=h,D=C&&R&&T,$=Gr(o).reveal;O?(xe.style.removeProperty("display"),xe.style.display=d?"flex":"",xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0"),X.classList.add("persona-scale-100","persona-opacity-100"),Yt?Yt.element.style.display="none":lr&&(lr.style.display="none")):(d?d&&($==="overlay"||$==="push")&&!D?(xe.style.removeProperty("display"),xe.style.display="flex",xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(xe.style.setProperty("display","none","important"),xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(xe.style.display="",xe.classList.add("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100"),X.classList.add("persona-scale-95","persona-opacity-0")),Yt?Yt.element.style.display=d?"none":"":lr&&(lr.style.display=d?"none":""))},Ut=(d,m="user")=>{var D,$;if(!F()||O===d)return;let h=O;O=d,ss();let C=(()=>{var Se,Je,Ve,lt,tt,Pe,Ee,ze,je,ft;let U=(Je=(Se=o.launcher)==null?void 0:Se.sidebarMode)!=null?Je:!1,_=(Ve=e.ownerDocument.defaultView)!=null?Ve:window,ie=(tt=(lt=o.launcher)==null?void 0:lt.mobileFullscreen)!=null?tt:!0,ae=(Ee=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Ee:640,Y=_.innerWidth<=ae,ve=nr(o)&&ie&&Y,De=I()&&((ft=(je=(ze=o.launcher)==null?void 0:ze.composerBar)==null?void 0:je.expandedSize)!=null?ft:"fullscreen")==="fullscreen";return U||ie&&Y&&T||ve||De})();if(O&&C){if(!ar){let U=e.getRootNode(),_=U instanceof ShadowRoot?U.host:e.closest(".persona-host");_&&(ar=rp(_,($=(D=o.launcher)==null?void 0:D.zIndex)!=null?$:Cr))}sr||(sr=op(e.ownerDocument))}else O||(ar==null||ar(),ar=null,sr==null||sr(),sr=null);O&&(is(),$p()||(Ot()==="follow"?vn(!0):qp()));let R={open:O,source:m,timestamp:Date.now()};O&&!h?i.emit("widget:opened",R):!O&&h&&i.emit("widget:closed",R),i.emit("widget:state",{open:O,launcherEnabled:T,voiceActive:oe.active,streaming:q.isStreaming()})},vl=d=>{se(d?"stop":"send"),N&&(N.disabled=d),zn.buttons.forEach(m=>{m.disabled=d}),Be.dataset.personaComposerStreaming=d?"true":"false",Be.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=d)})},wl=()=>{oe.active||Z&&Z.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>wl(),200)});let Xp=()=>{var h,C,R,D,$,U,_,ie,ae,Y,ve;Ao.textContent=(C=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?C:"Hello \u{1F44B}",Mo.textContent=(D=(R=o.copy)==null?void 0:R.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",Z.placeholder=(U=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?U:"How can I help...";let d=be.querySelector("[data-persona-intro-card]");if(d){let De=((_=o.copy)==null?void 0:_.showWelcomeCard)!==!1;d.style.display=De?"":"none",De?(be.classList.remove("persona-gap-3"),be.classList.add("persona-gap-6")):(be.classList.remove("persona-gap-6"),be.classList.add("persona-gap-3"))}!((ae=(ie=o.sendButton)==null?void 0:ie.useIcon)!=null&&ae)&&!(q!=null&&q.isStreaming())&&(Ue.textContent=(ve=(Y=o.copy)==null?void 0:Y.sendButtonLabel)!=null?ve:"Send"),Z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Z.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let d=p.sessionId;return typeof d=="string"?d:null},setStoredSessionId:d=>{b(m=>({...m,sessionId:d}))}});let Kn=null,yy=()=>{Kn==null&&(Kn=setInterval(()=>{let d=et.querySelectorAll("[data-tool-elapsed]");if(d.length===0){clearInterval(Kn),Kn=null;return}let m=Date.now();d.forEach(h=>{let C=Number(h.getAttribute("data-tool-elapsed"));C&&(h.textContent=ci(m-C))})},100))};q=new Na(o,{onMessagesChanged(d){var R,D;rs(et,d,te),yy(),ba(d),vn(!mo),uy(d);let m=[...d].reverse().find($=>$.role==="user"),h=[...d].reverse().find($=>$.role==="assistant");d.length===0&&(ts(),Fo=!0,Ze=!1),!wa||Gn?(wa=!0,Ca=(R=m==null?void 0:m.id)!=null?R:null,k=(D=h==null?void 0:h.id)!=null?D:null):m&&m.id!==Ca?(Ca=m.id,cy(m.id)):h&&h.id!==k&&py(),h&&(k=h.id);let C=oe.lastUserMessageId;m&&m.id!==C&&(oe.lastUserMessageId=m.id,i.emit("user:message",m)),oe.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),ir(d),Sa()},onStatusChanged(d){var C;let m=(C=o.statusIndicator)!=null?C:{};Qt(xr,(R=>{var D,$,U,_;return R==="idle"?(D=m.idleText)!=null?D:wr.idle:R==="connecting"?($=m.connectingText)!=null?$:wr.connecting:R==="connected"?(U=m.connectedText)!=null?U:wr.connected:R==="error"?(_=m.errorText)!=null?_:wr.error:wr[R]})(d),m,d)},onStreamingChanged(d){mo=d,vl(d),q&&rs(et,q.getMessages(),te),d||vn(!0),Ur(),cn(d?"Responding\u2026":"Response complete."),Sa()},onVoiceStatusChanged(d){var m,h;if(i.emit("voice:status",{status:d,timestamp:Date.now()}),((h=(m=o.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(d){case"listening":en(),Ma();break;case"processing":en(),Sy();break;case"speaking":en(),Ay();break;default:d==="idle"&&q.isBargeInActive()?(en(),Ma(),N==null||N.setAttribute("aria-label","End voice session")):(oe.active=!1,en(),ct("system"),Or());break}},onArtifactsState(d){Fr=d,Ro(),ir()}}),wt.current=q;let Cl=null;if(q.onReadAloudChange((d,m)=>{var R;fn=d,mn=m,gn();let h=d!=null?d:Cl;d&&(Cl=d);let C=h&&(R=q.getMessages().find(D=>D.id===h))!=null?R:null;i.emit("message:read-aloud",{messageId:h,message:C,state:m,timestamp:Date.now()}),m==="idle"&&(Cl=null)}),wa=!0,((df=(lf=o.voiceRecognition)==null?void 0:lf.provider)==null?void 0:df.type)==="runtype")try{q.setupVoice()}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",d)}o.clientToken&&q.initClientSession().catch(d=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",d)}),(j||o.onSSEEvent)&&q.setSSEEventCallback((d,m)=>{var h;(h=o.onSSEEvent)==null||h.call(o,d,m),J==null||J.processEvent(d,m),j==null||j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:d,timestamp:Date.now(),payload:JSON.stringify(m)})}),f&&f.then(d=>{var m,h,C;if(d){if(d.metadata&&(p=Sp(d.metadata),A.syncFromMetadata()),(m=d.messages)!=null&&m.length){Gn=!0;try{q.hydrateMessages(d.messages)}finally{Gn=!1}}(h=d.artifacts)!=null&&h.length&&q.hydrateArtifacts(d.artifacts,(C=d.selectedArtifactId)!=null?C:null)}}).catch(d=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",d)});let Qp=()=>{var m,h,C;!I()||O||!((C=(h=(m=o.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||C)||Ut(!0,"auto")},Jp=d=>{var R;if(d.preventDefault(),q.isStreaming()){q.cancel(),J==null||J.reset(),Ne==null||Ne.update();return}let m=Z.value.trim(),h=(R=vt==null?void 0:vt.hasAttachments())!=null?R:!1;if(!m&&!h)return;Qp();let C;h&&(C=[],C.push(...vt.getContentParts()),m&&C.push(Ss(m))),Z.value="",Z.style.height="auto",js(),q.sendMessage(m,{contentParts:C}),h&&vt.clearAttachments()},by=()=>{var d;return((d=o.features)==null?void 0:d.composerHistory)!==!1},Sl={...Oi},Al=!1,js=()=>{Sl={...Oi}},vy=()=>q.getMessages().filter(d=>d.role==="user").map(d=>{var m;return(m=d.content)!=null?m:""}).filter(d=>d.length>0),wy=d=>{if(!Z)return;Al=!0,Z.value=d,Z.dispatchEvent(new Event("input",{bubbles:!0})),Al=!1;let m=Z.value.length;Z.setSelectionRange(m,m)},Yp=()=>{Al||js()},Zp=d=>{if(Z){if(by()&&(d.key==="ArrowUp"||d.key==="ArrowDown")&&!d.shiftKey&&!d.metaKey&&!d.ctrlKey&&!d.altKey&&!d.isComposing){let m=Z.selectionStart===0&&Z.selectionEnd===0,h=Th({direction:d.key==="ArrowUp"?"up":"down",history:vy(),currentValue:Z.value,atStart:m,state:Sl});if(Sl=h.state,h.handled){d.preventDefault(),h.value!==void 0&&wy(h.value);return}}if(d.key==="Enter"&&!d.shiftKey){if(q.isStreaming()){d.preventDefault();return}js(),d.preventDefault(),Ue.click()}}},eu=d=>{d.key!=="Escape"||d.isComposing||q.isStreaming()&&d.composedPath().includes(Ce)&&(q.cancel(),J==null||J.reset(),Ne==null||Ne.update(),js(),d.preventDefault(),d.stopImmediatePropagation())},tu=async d=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!vt)return;let m=S0(d.clipboardData);m.length!==0&&(d.preventDefault(),await vt.handleFiles(m))},ro=null,No=!1,Aa=null,it=null,ru=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Gs=(d="user")=>{var D,$,U,_,ie,ae,Y;if(No||q.isStreaming())return;let m=ru();if(!m)return;ro=new m;let C=($=((D=o.voiceRecognition)!=null?D:{}).pauseDuration)!=null?$:2e3;ro.continuous=!0,ro.interimResults=!0,ro.lang="en-US";let R=Z.value;ro.onresult=ve=>{let De="",Se="";for(let Ve=0;Ve<ve.results.length;Ve++){let lt=ve.results[Ve],tt=lt[0].transcript;lt.isFinal?De+=tt+" ":Se=tt}let Je=R+De+Se;Z.value=Je,Aa&&clearTimeout(Aa),(De||Se)&&(Aa=window.setTimeout(()=>{let Ve=Z.value.trim();Ve&&ro&&No&&(wn(),Z.value="",Z.style.height="auto",q.sendMessage(Ve,{viaVoice:!0}))},C))},ro.onerror=ve=>{ve.error!=="no-speech"&&wn()},ro.onend=()=>{if(No){let ve=Z.value.trim();ve&&ve!==R.trim()&&(Z.value="",Z.style.height="auto",q.sendMessage(ve,{viaVoice:!0})),wn()}};try{if(ro.start(),No=!0,oe.active=!0,d!=="system"&&(oe.manuallyDeactivated=!1),ct(d),Or(),N){let ve=(U=o.voiceRecognition)!=null?U:{};it={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(_=ve.iconName)!=null?_:"mic",iconSize:parseFloat((Y=(ae=ve.iconSize)!=null?ae:(ie=o.sendButton)==null?void 0:ie.size)!=null?Y:"40")||24};let De=ve.recordingBackgroundColor,Se=ve.recordingIconColor,Je=ve.recordingBorderColor;if(N.classList.add("persona-voice-recording"),N.style.backgroundColor=De!=null?De:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let Ve=N.querySelector("svg");Ve&&Ve.setAttribute("stroke",Se)}Je&&(N.style.borderColor=Je),N.setAttribute("aria-label","Stop voice recognition")}}catch{wn("system")}},wn=(d="user")=>{if(No){if(No=!1,Aa&&(clearTimeout(Aa),Aa=null),ro){try{ro.stop()}catch{}ro=null}if(oe.active=!1,ct(d),Or(),N){if(N.classList.remove("persona-voice-recording"),it){N.style.backgroundColor=it.backgroundColor,N.style.color=it.color,N.style.borderColor=it.borderColor;let m=N.querySelector("svg");m&&m.setAttribute("stroke",it.color||"currentColor"),it=null}N.setAttribute("aria-label","Start voice recognition")}}},Cy=(d,m)=>{var tt,Pe,Ee,ze,je,ft,B,Ie,Re;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),C=((tt=d==null?void 0:d.provider)==null?void 0:tt.type)==="runtype",R=((Pe=d==null?void 0:d.provider)==null?void 0:Pe.type)==="custom";if(!(h||C||R))return null;let $=w("div","persona-send-button-wrapper"),U=w("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let _=(Ee=d==null?void 0:d.iconName)!=null?Ee:"mic",ie=(ze=m==null?void 0:m.size)!=null?ze:"40px",ae=(je=d==null?void 0:d.iconSize)!=null?je:ie,Y=parseFloat(ae)||24,ve=(ft=d==null?void 0:d.backgroundColor)!=null?ft:m==null?void 0:m.backgroundColor,De=(B=d==null?void 0:d.iconColor)!=null?B:m==null?void 0:m.textColor;U.style.width=ae,U.style.height=ae,U.style.minWidth=ae,U.style.minHeight=ae,U.style.fontSize="18px",U.style.lineHeight="1",De?U.style.color=De:U.style.color="var(--persona-text, #111827)";let Je=ge(_,Y,De||"currentColor",1.5);Je?U.appendChild(Je):U.textContent="\u{1F3A4}",ve?U.style.backgroundColor=ve:U.style.backgroundColor="",d!=null&&d.borderWidth&&(U.style.borderWidth=d.borderWidth,U.style.borderStyle="solid"),d!=null&&d.borderColor&&(U.style.borderColor=d.borderColor),d!=null&&d.paddingX&&(U.style.paddingLeft=d.paddingX,U.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(U.style.paddingTop=d.paddingY,U.style.paddingBottom=d.paddingY),$.appendChild(U);let Ve=(Ie=d==null?void 0:d.tooltipText)!=null?Ie:"Start voice recognition";if(((Re=d==null?void 0:d.showTooltip)!=null?Re:!1)&&Ve){let fe=w("div","persona-send-button-tooltip");fe.textContent=Ve,$.appendChild(fe)}return{micButton:U,micButtonWrapper:$}},Ml=()=>{var m,h,C,R,D;if(!N||it)return;let d=(m=o.voiceRecognition)!=null?m:{};it={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(h=d.iconName)!=null?h:"mic",iconSize:parseFloat((D=(R=d.iconSize)!=null?R:(C=o.sendButton)==null?void 0:C.size)!=null?D:"40")||24}},Tl=(d,m)=>{var D,$,U,_,ie;if(!N)return;let h=N.querySelector("svg");h&&h.remove();let C=(ie=it==null?void 0:it.iconSize)!=null?ie:parseFloat((_=(U=(D=o.voiceRecognition)==null?void 0:D.iconSize)!=null?U:($=o.sendButton)==null?void 0:$.size)!=null?_:"40")||24,R=ge(d,C,m,1.5);R&&N.appendChild(R)},Ks=()=>{N&&N.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ma=()=>{var R;if(!N)return;Ml();let d=(R=o.voiceRecognition)!=null?R:{},m=d.recordingBackgroundColor,h=d.recordingIconColor,C=d.recordingBorderColor;if(Ks(),N.classList.add("persona-voice-recording"),N.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let D=N.querySelector("svg");D&&D.setAttribute("stroke",h)}C&&(N.style.borderColor=C),N.setAttribute("aria-label","Stop voice recognition")},Sy=()=>{var U,_,ie,ae,Y,ve,De,Se;if(!N)return;Ml();let d=(U=o.voiceRecognition)!=null?U:{},m=q.getVoiceInterruptionMode(),h=(_=d.processingIconName)!=null?_:"loader",C=(ae=(ie=d.processingIconColor)!=null?ie:it==null?void 0:it.color)!=null?ae:"",R=(ve=(Y=d.processingBackgroundColor)!=null?Y:it==null?void 0:it.backgroundColor)!=null?ve:"",D=(Se=(De=d.processingBorderColor)!=null?De:it==null?void 0:it.borderColor)!=null?Se:"";Ks(),N.classList.add("persona-voice-processing"),N.style.backgroundColor=R,N.style.borderColor=D;let $=C||"currentColor";N.style.color=$,Tl(h,$),N.setAttribute("aria-label","Processing voice input"),m==="none"&&(N.style.cursor="default")},Ay=()=>{var ie,ae,Y,ve,De,Se,Je,Ve,lt,tt,Pe,Ee;if(!N)return;Ml();let d=(ie=o.voiceRecognition)!=null?ie:{},m=q.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",C=(ae=d.speakingIconName)!=null?ae:h,R=(Se=d.speakingIconColor)!=null?Se:m==="barge-in"?(ve=(Y=d.recordingIconColor)!=null?Y:it==null?void 0:it.color)!=null?ve:"":(De=it==null?void 0:it.color)!=null?De:"",D=(lt=d.speakingBackgroundColor)!=null?lt:m==="barge-in"?(Je=d.recordingBackgroundColor)!=null?Je:"var(--persona-voice-recording-bg, #ef4444)":(Ve=it==null?void 0:it.backgroundColor)!=null?Ve:"",$=(Ee=d.speakingBorderColor)!=null?Ee:m==="barge-in"?(tt=d.recordingBorderColor)!=null?tt:"":(Pe=it==null?void 0:it.borderColor)!=null?Pe:"";Ks(),N.classList.add("persona-voice-speaking"),N.style.backgroundColor=D,N.style.borderColor=$;let U=R||"currentColor";N.style.color=U,Tl(C,U);let _=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";N.setAttribute("aria-label",_),m==="none"&&(N.style.cursor="default"),m==="barge-in"&&N.classList.add("persona-voice-recording")},en=()=>{var d,m,h;N&&(Ks(),it&&(N.style.backgroundColor=(d=it.backgroundColor)!=null?d:"",N.style.color=(m=it.color)!=null?m:"",N.style.borderColor=(h=it.borderColor)!=null?h:"",Tl(it.iconName,it.color||"currentColor"),it=null),N.style.cursor="",N.setAttribute("aria-label","Start voice recognition"))},Xs=()=>{var d,m;if(((m=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:m.type)==="runtype"){let h=q.getVoiceStatus(),C=q.getVoiceInterruptionMode();if(C==="none"&&(h==="processing"||h==="speaking"))return;if(C==="cancel"&&(h==="processing"||h==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{oe.active=!1,oe.manuallyDeactivated=!0,Or(),ct("user"),en()});return}q.toggleVoice().then(()=>{oe.active=q.isVoiceActive(),oe.manuallyDeactivated=!q.isVoiceActive(),Or(),ct("user"),q.isVoiceActive()?Ma():en()});return}if(No){let h=Z.value.trim();oe.manuallyDeactivated=!0,Or(),wn("user"),h&&(Z.value="",Z.style.height="auto",q.sendMessage(h))}else oe.manuallyDeactivated=!1,Or(),Gs("user")};ko=Xs,N&&(N.addEventListener("click",Xs),st.push(()=>{var d,m;((m=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:m.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),en()):wn("system"),N&&N.removeEventListener("click",Xs)}));let My=i.on("assistant:complete",()=>{ut&&(oe.active||oe.manuallyDeactivated||ut==="assistant"&&!oe.lastUserMessageWasVoice||setTimeout(()=>{var d,m;!oe.active&&!oe.manuallyDeactivated&&(((m=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:m.type)==="runtype"?q.toggleVoice().then(()=>{oe.active=q.isVoiceActive(),ct("auto"),q.isVoiceActive()&&Ma()}):Gs("auto"))},600))});st.push(My);let Ty=i.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});st.push(Ty);let ou=()=>{Ut(!O,"user")},Yt=null,lr=null;if(T&&!I()){let{instance:d,element:m}=lp({config:o,plugins:n,onToggle:ou});Yt=d,d||(lr=m)}Yt?e.appendChild(Yt.element):lr&&e.appendChild(lr),ss(),ba(),Xp(),vl(q.isStreaming()),$p()||(Ot()==="follow"?vn(!0):qp()),yn(),S&&(!T||I()?setTimeout(()=>wl(),0):O&&setTimeout(()=>wl(),200));let is=()=>{var _,ie,ae,Y,ve,De,Se,Je,Ve,lt,tt,Pe,Ee,ze,je,ft,B,Ie,Re,fe,Ht,Rt;if(I()){Xr(),ss();return}let d=nr(o),m=(ie=(_=o.launcher)==null?void 0:_.sidebarMode)!=null?ie:!1,h=d||m||((Y=(ae=o.launcher)==null?void 0:ae.fullHeight)!=null?Y:!1),C=(ve=e.ownerDocument.defaultView)!=null?ve:window,R=(Se=(De=o.launcher)==null?void 0:De.mobileFullscreen)!=null?Se:!0,D=(Ve=(Je=o.launcher)==null?void 0:Je.mobileBreakpoint)!=null?Ve:640,$=C.innerWidth<=D,U=R&&$&&T;try{if(U){xn(),Hn(e,o);return}if(H&&(H=!1,xn(),Hn(e,o)),!T&&!d){X.style.height="",X.style.width="";return}if(!m&&!d){let jt=(tt=(lt=o==null?void 0:o.launcher)==null?void 0:lt.width)!=null?tt:o==null?void 0:o.launcherWidth,mt=jt!=null?jt:jr;X.style.width=mt,X.style.maxWidth=mt}if($n(),!h){let jt=C.innerHeight,mt=64,qt=(Ee=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Ee:0,qr=Math.max(200,jt-mt),Zt=Math.min(640,qr),Ke=Math.max(200,Zt-qt);X.style.height=`${Ke}px`}}finally{if(Xr(),ss(),O&&T){let mt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((ft=(je=o.launcher)==null?void 0:je.mobileBreakpoint)!=null?ft:640),qt=(Ie=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Ie:!1,qr=(fe=(Re=o.launcher)==null?void 0:Re.mobileFullscreen)!=null?fe:!0,Zt=nr(o)&&qr&&mt,Ke=qt||qr&&mt&&T||Zt;if(Ke&&!sr){let Mt=e.getRootNode(),or=Mt instanceof ShadowRoot?Mt.host:e.closest(".persona-host");or&&!ar&&(ar=rp(or,(Rt=(Ht=o.launcher)==null?void 0:Ht.zIndex)!=null?Rt:Cr)),sr=op(e.ownerDocument)}else Ke||(ar==null||ar(),ar=null,sr==null||sr(),sr=null)}}};is();let nu=(cf=e.ownerDocument.defaultView)!=null?cf:window;if(nu.addEventListener("resize",is),st.push(()=>nu.removeEventListener("resize",is)),typeof ResizeObserver!="undefined"){let d=new ResizeObserver(()=>{Xr()});d.observe(Be),st.push(()=>d.disconnect())}Mr=be.scrollTop;let au=Vo(be),Ey=()=>{let d=be.getRootNode(),m=typeof d.getSelection=="function"?d.getSelection():null;return m!=null?m:be.ownerDocument.getSelection()},El=()=>Ih(Ey(),be),su=()=>{let d=be.scrollTop,m=Vo(be),h=m<au;if(au=m,!tr()){Mr=d,Ur();return}let{action:C,nextLastScrollTop:R}=Ui({following:yr.isFollowing(),currentScrollTop:d,lastScrollTop:Mr,nearBottom:Bn(be,V),userScrollThreshold:z,isAutoScrolling:Tr||jn||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Mr=R,C==="resume"){El()||bn();return}C==="pause"&&es()};if(be.addEventListener("scroll",su,{passive:!0}),st.push(()=>be.removeEventListener("scroll",su)),typeof ResizeObserver!="undefined"){let d=new ResizeObserver(()=>{dy()});d.observe(et),d.observe(be),st.push(()=>d.disconnect())}let iu=()=>{tr()&&yr.isFollowing()&&El()&&es()},lu=be.ownerDocument;lu.addEventListener("selectionchange",iu),st.push(()=>{lu.removeEventListener("selectionchange",iu)});let ky=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),du=d=>{lo()&&tr()&&yr.isFollowing()&&ky.has(d.key)&&es()},cu=d=>{if(!lo()||!tr()||!yr.isFollowing())return;let m=d.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&es()};be.addEventListener("keydown",du),be.addEventListener("focusin",cu),st.push(()=>{be.removeEventListener("keydown",du),be.removeEventListener("focusin",cu)});let pu=d=>{if(!tr())return;let m=qi({following:yr.isFollowing(),deltaY:d.deltaY,nearBottom:Bn(be,V),resumeWhenNearBottom:!0});m==="pause"?es():m==="resume"&&!El()&&bn()};be.addEventListener("wheel",pu,{passive:!0}),st.push(()=>be.removeEventListener("wheel",pu)),$t.addEventListener("click",()=>{ts(),be.scrollTop=be.scrollHeight,Mr=be.scrollTop,bn(),vn(!0),Ur()}),st.push(()=>$t.remove()),st.push(()=>{Er(),ts()});let uu=()=>{P&&(Wo&&(P.removeEventListener("click",Wo),Wo=null),F()?(P.style.display="",Wo=()=>{Ut(!1,"user")},P.addEventListener("click",Wo)):P.style.display="none")};uu(),(()=>{let{clearChatButton:d}=$e;d&&d.addEventListener("click",()=>{q.clearMessages(),Ho.clear(),bn(),Ln($e.composerOverlay);try{localStorage.removeItem(Xa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xa}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Xa)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 m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),l!=null&&l.clear)try{let h=l.clear();h instanceof Promise&&h.catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},A.syncFromMetadata(),j==null||j.clear(),J==null||J.reset(),Ne==null||Ne.update()})})(),yt&&yt.addEventListener("submit",Jp),Z==null||Z.addEventListener("keydown",Zp),Z==null||Z.addEventListener("input",Yp),Z==null||Z.addEventListener("paste",tu);let fu=(pf=e.ownerDocument)!=null?pf:document;fu.addEventListener("keydown",eu,!0);let mu="persona-attachment-drop-active",ls=0,kl=()=>{ls=0,Ce.classList.remove(mu)},Ta=()=>{var d;return((d=o.attachments)==null?void 0:d.enabled)===!0&&vt!==null},gu=d=>{!ml(d.dataTransfer)||!Ta()||(ls++,ls===1&&Ce.classList.add(mu))},hu=d=>{!ml(d.dataTransfer)||!Ta()||(ls--,ls<=0&&kl())},xu=d=>{!ml(d.dataTransfer)||!Ta()||(d.preventDefault(),d.dataTransfer.dropEffect="copy")},yu=d=>{var h;if(!ml(d.dataTransfer)||!Ta())return;d.preventDefault(),d.stopPropagation(),kl();let m=Array.from((h=d.dataTransfer.files)!=null?h:[]);m.length!==0&&vt.handleFiles(m)},Cn=!0;Ce.addEventListener("dragenter",gu,Cn),Ce.addEventListener("dragleave",hu,Cn),e.addEventListener("dragover",xu,Cn),e.addEventListener("drop",yu,Cn);let Qs=e.ownerDocument,bu=d=>{Ta()&&d.preventDefault()},vu=d=>{Ta()&&d.preventDefault()};Qs.addEventListener("dragover",bu),Qs.addEventListener("drop",vu),st.push(()=>{yt&&yt.removeEventListener("submit",Jp),Z==null||Z.removeEventListener("keydown",Zp),Z==null||Z.removeEventListener("input",Yp),Z==null||Z.removeEventListener("paste",tu),fu.removeEventListener("keydown",eu,!0)}),st.push(()=>{Ce.removeEventListener("dragenter",gu,Cn),Ce.removeEventListener("dragleave",hu,Cn),e.removeEventListener("dragover",xu,Cn),e.removeEventListener("drop",yu,Cn),Qs.removeEventListener("dragover",bu),Qs.removeEventListener("drop",vu),kl()}),st.push(()=>{q.cancel()}),Yt?st.push(()=>{Yt==null||Yt.destroy()}):lr&&st.push(()=>{lr==null||lr.remove()});let rr={update(d){var Nt,fr,$r,_o,mr,gr,ao,Mn,yf,bf,vf,wf,Cf,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,wm,Cm,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,dg,cg,pg,ug,fg,mg,gg,hg;let m=o.toolCall,h=o.messageActions,C=(Nt=o.layout)==null?void 0:Nt.messages,R=o.colorScheme,D=o.loadingIndicator,$=o.iterationDisplay,U=(fr=o.features)==null?void 0:fr.showReasoning,_=($r=o.features)==null?void 0:$r.showToolCalls,ie=(_o=o.features)==null?void 0:_o.toolCallDisplay,ae=(mr=o.features)==null?void 0:mr.reasoningDisplay;o={...o,...d},xn(),Hn(e,o),al(e,o),sl(e,o),Ro(),o.colorScheme!==R&&Za();let Y=_s.getForInstance(o.plugins);n.length=0,n.push(...Y),T=(ao=(gr=o.launcher)==null?void 0:gr.enabled)!=null?ao:!0,y=(yf=(Mn=o.launcher)==null?void 0:Mn.autoExpand)!=null?yf:!1,Te=(vf=(bf=o.features)==null?void 0:bf.showReasoning)!=null?vf:!0,We=(Cf=(wf=o.features)==null?void 0:wf.showToolCalls)!=null?Cf:!0,Ae=(Af=(Sf=o.features)==null?void 0:Sf.scrollToBottom)!=null?Af:{};let ve=Ot();ne=(Tf=(Mf=o.features)==null?void 0:Mf.scrollBehavior)!=null?Tf:{},ve!==Ot()&&(ts(),bn()),pn(),Ur();let De=de;if(de=(kf=(Ef=o.features)==null?void 0:Ef.showEventStreamToggle)!=null?kf:!1,de&&!De){if(j||(ke=new Ns(ue),j=new Fs(Fe,ke),J=J!=null?J:new Os,ke.open().then(()=>j==null?void 0:j.restore()).catch(()=>{}),q.setSSEEventCallback((re,Ct)=>{var Vt;(Vt=o.onSSEEvent)==null||Vt.call(o,re,Ct),J==null||J.processEvent(re,Ct),j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(Ct)})})),!pt&&Le){let re=(Pf=(Lf=o.features)==null?void 0:Lf.eventStream)==null?void 0:Pf.classNames,Ct="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"+(re!=null&&re.toggleButton?" "+re.toggleButton:"");pt=w("button",Ct),pt.style.width="28px",pt.style.height="28px",pt.style.color=Pr.actionIconColor,pt.type="button",pt.setAttribute("aria-label","Event Stream"),pt.title="Event Stream";let Vt=ge("activity","18px","currentColor",1.5);Vt&&pt.appendChild(Vt);let rt=$e.clearChatButtonWrapper,Et=$e.closeButtonWrapper,dr=rt||Et;dr&&dr.parentNode===Le?Le.insertBefore(pt,dr):Le.appendChild(pt),pt.addEventListener("click",()=>{K?fo():Go()})}}else!de&&De&&(fo(),pt&&(pt.remove(),pt=null),j==null||j.clear(),ke==null||ke.destroy(),j=null,ke=null,J==null||J.reset(),J=null);if(((Rf=o.launcher)==null?void 0:Rf.enabled)===!1&&Yt&&(Yt.destroy(),Yt=null),((If=o.launcher)==null?void 0:If.enabled)===!1&&lr&&(lr.remove(),lr=null),((Wf=o.launcher)==null?void 0:Wf.enabled)!==!1&&!Yt&&!lr){let{instance:re,element:Ct}=lp({config:o,plugins:n,onToggle:ou});Yt=re,re||(lr=Ct),e.appendChild(Ct)}Yt&&Yt.update(o),Me&&((Hf=o.launcher)==null?void 0:Hf.title)!==void 0&&(Me.textContent=o.launcher.title),He&&((Bf=o.launcher)==null?void 0:Bf.subtitle)!==void 0&&(He.textContent=o.launcher.subtitle);let Se=(Df=o.layout)==null?void 0:Df.header;if((Se==null?void 0:Se.layout)!==W&&Le){let re=Se?qa(o,Se,{showClose:F(),onClose:()=>Ut(!1,"user")}):sn({config:o,showClose:F(),onClose:()=>Ut(!1,"user")});Ye.replaceHeader(re),Le=Ye.header.element,ee=Ye.header.iconHolder,Me=Ye.header.headerTitle,He=Ye.header.headerSubtitle,P=Ye.header.closeButton,W=Se==null?void 0:Se.layout}else if(Se&&(ee&&(ee.style.display=Se.showIcon===!1?"none":""),Me&&(Me.style.display=Se.showTitle===!1?"none":""),He&&(He.style.display=Se.showSubtitle===!1?"none":""),P&&(P.style.display=Se.showCloseButton===!1?"none":""),$e.clearChatButtonWrapper)){let re=Se.showClearChat;if(re!==void 0){$e.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:Ct}=$e;Ct&&!Ct.classList.contains("persona-absolute")&&(re?Ct.classList.remove("persona-ml-auto"):Ct.classList.add("persona-ml-auto"))}}let Ve=((Ff=o.layout)==null?void 0:Ff.showHeader)!==!1;Le&&(Le.style.display=Ve?"":"none");let lt=((Nf=o.layout)==null?void 0:Nf.showFooter)!==!1;Be&&(Be.style.display=lt?"":"none"),Xr(),Ur(),T!==M?T?Ut(y,"auto"):(O=!0,ss()):y!==v&&Ut(y,"auto"),v=y,M=T,is(),uu();let Ee=JSON.stringify(d.toolCall)!==JSON.stringify(m),ze=JSON.stringify(o.messageActions)!==JSON.stringify(h),je=JSON.stringify((Of=o.layout)==null?void 0:Of.messages)!==JSON.stringify(C),ft=((_f=o.loadingIndicator)==null?void 0:_f.render)!==(D==null?void 0:D.render)||((Uf=o.loadingIndicator)==null?void 0:Uf.renderIdle)!==(D==null?void 0:D.renderIdle)||((qf=o.loadingIndicator)==null?void 0:qf.showBubble)!==(D==null?void 0:D.showBubble),B=o.iterationDisplay!==$,Ie=(($f=(Vf=o.features)==null?void 0:Vf.showReasoning)!=null?$f:!0)!==(U!=null?U:!0)||((jf=(zf=o.features)==null?void 0:zf.showToolCalls)!=null?jf:!0)!==(_!=null?_:!0)||JSON.stringify((Gf=o.features)==null?void 0:Gf.toolCallDisplay)!==JSON.stringify(ie)||JSON.stringify((Kf=o.features)==null?void 0:Kf.reasoningDisplay)!==JSON.stringify(ae);(Ee||ze||je||ft||B||Ie)&&q&&(va++,rs(et,q.getMessages(),te));let fe=(Xf=o.launcher)!=null?Xf:{},Ht=(Qf=fe.headerIconHidden)!=null?Qf:!1,Rt=(Yf=(Jf=o.layout)==null?void 0:Jf.header)==null?void 0:Yf.showIcon,jt=Ht||Rt===!1,mt=fe.headerIconName,qt=(Zf=fe.headerIconSize)!=null?Zf:"48px";if(ee){let re=Ce.querySelector(".persona-border-b-persona-divider"),Ct=re==null?void 0:re.querySelector(".persona-flex-col");if(jt)ee.style.display="none",re&&Ct&&!re.contains(Ct)&&re.insertBefore(Ct,re.firstChild);else{if(ee.style.display="",ee.style.height=qt,ee.style.width=qt,re&&Ct&&(re.contains(ee)?ee.nextSibling!==Ct&&(ee.remove(),re.insertBefore(ee,Ct)):re.insertBefore(ee,Ct)),mt){let rt=parseFloat(qt)||24,Et=ge(mt,rt*.6,"currentColor",1);Et?ee.replaceChildren(Et):ee.textContent=(em=fe.agentIconText)!=null?em:"\u{1F4AC}"}else if(fe.iconUrl){let rt=ee.querySelector("img");if(rt)rt.src=fe.iconUrl,rt.style.height=qt,rt.style.width=qt;else{let Et=document.createElement("img");Et.src=fe.iconUrl,Et.alt="",Et.className="persona-rounded-xl persona-object-cover",Et.style.height=qt,Et.style.width=qt,ee.replaceChildren(Et)}}else{let rt=ee.querySelector("svg"),Et=ee.querySelector("img");(rt||Et)&&ee.replaceChildren(),ee.textContent=(tm=fe.agentIconText)!=null?tm:"\u{1F4AC}"}let Vt=ee.querySelector("img");Vt&&(Vt.style.height=qt,Vt.style.width=qt)}}let qr=(om=(rm=o.layout)==null?void 0:rm.header)==null?void 0:om.showTitle,Zt=(am=(nm=o.layout)==null?void 0:nm.header)==null?void 0:am.showSubtitle;if(Me&&(Me.style.display=qr===!1?"none":""),He&&(He.style.display=Zt===!1?"none":""),P){((im=(sm=o.layout)==null?void 0:sm.header)==null?void 0:im.showCloseButton)===!1?P.style.display="none":P.style.display="";let Ct=(lm=fe.closeButtonSize)!=null?lm:"32px",Vt=(dm=fe.closeButtonPlacement)!=null?dm:"inline";P.style.height=Ct,P.style.width=Ct;let{closeButtonWrapper:rt}=$e,Et=Vt==="top-right",dr=rt==null?void 0:rt.classList.contains("persona-absolute");if(rt&&Et!==dr)if(rt.remove(),Et)rt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ce.style.position="relative",Ce.appendChild(rt);else{let nt=(pm=(cm=fe.clearChat)==null?void 0:cm.placement)!=null?pm:"inline",cr=(fm=(um=fe.clearChat)==null?void 0:um.enabled)!=null?fm:!0;rt.className=cr&&nt==="inline"?"":"persona-ml-auto";let Wr=Ce.querySelector(".persona-border-b-persona-divider");Wr&&Wr.appendChild(rt)}if(P.style.color=fe.closeButtonColor||Pr.actionIconColor,fe.closeButtonBackgroundColor?(P.style.backgroundColor=fe.closeButtonBackgroundColor,P.classList.remove("hover:persona-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let nt=fe.closeButtonBorderWidth||"0px",cr=fe.closeButtonBorderColor||"transparent";P.style.border=`${nt} solid ${cr}`,P.classList.remove("persona-border-none")}else P.style.border="",P.classList.add("persona-border-none");fe.closeButtonBorderRadius?(P.style.borderRadius=fe.closeButtonBorderRadius,P.classList.remove("persona-rounded-full")):(P.style.borderRadius="",P.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(P.style.paddingLeft=fe.closeButtonPaddingX,P.style.paddingRight=fe.closeButtonPaddingX):(P.style.paddingLeft="",P.style.paddingRight=""),fe.closeButtonPaddingY?(P.style.paddingTop=fe.closeButtonPaddingY,P.style.paddingBottom=fe.closeButtonPaddingY):(P.style.paddingTop="",P.style.paddingBottom="");let vr=(mm=fe.closeButtonIconName)!=null?mm:"x",bo=(gm=fe.closeButtonIconText)!=null?gm:"\xD7";P.innerHTML="";let kr=ge(vr,"28px","currentColor",1);kr?P.appendChild(kr):P.textContent=bo;let Jt=(hm=fe.closeButtonTooltipText)!=null?hm:"Close chat",zr=(xm=fe.closeButtonShowTooltip)!=null?xm:!0;if(P.setAttribute("aria-label",Jt),rt&&(rt._cleanupTooltip&&(rt._cleanupTooltip(),delete rt._cleanupTooltip),zr&&Jt)){let nt=null,cr=()=>{if(nt||!P)return;let Zn=P.ownerDocument,ds=Zn.body;if(!ds)return;nt=qo(Zn,"div","persona-clear-chat-tooltip"),nt.textContent=Jt;let cs=qo(Zn,"div");cs.className="persona-clear-chat-tooltip-arrow",nt.appendChild(cs);let ea=P.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Dn),nt.style.left=`${ea.left+ea.width/2}px`,nt.style.top=`${ea.top-8}px`,nt.style.transform="translate(-50%, -100%)",ds.appendChild(nt)},Wr=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};rt.addEventListener("mouseenter",cr),rt.addEventListener("mouseleave",Wr),P.addEventListener("focus",cr),P.addEventListener("blur",Wr),rt._cleanupTooltip=()=>{Wr(),rt&&(rt.removeEventListener("mouseenter",cr),rt.removeEventListener("mouseleave",Wr)),P&&(P.removeEventListener("focus",cr),P.removeEventListener("blur",Wr))}}}let{clearChatButton:Ke,clearChatButtonWrapper:Mt}=$e;if(Ke){let re=(ym=fe.clearChat)!=null?ym:{},Ct=(bm=re.enabled)!=null?bm:!0,Vt=(wm=(vm=o.layout)==null?void 0:vm.header)==null?void 0:wm.showClearChat,rt=Vt!==void 0?Vt:Ct,Et=(Cm=re.placement)!=null?Cm:"inline";if(Mt){Mt.style.display=rt?"":"none";let{closeButtonWrapper:dr}=$e;!I()&&dr&&!dr.classList.contains("persona-absolute")&&(rt?dr.classList.remove("persona-ml-auto"):dr.classList.add("persona-ml-auto"));let vr=Et==="top-right",bo=Mt.classList.contains("persona-absolute");if(!I()&&vr!==bo&&rt){if(Mt.remove(),vr)Mt.className="persona-absolute persona-top-4 persona-z-50",Mt.style.right="48px",Ce.style.position="relative",Ce.appendChild(Mt);else{Mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Mt.style.right="";let Jt=Ce.querySelector(".persona-border-b-persona-divider"),zr=$e.closeButtonWrapper;Jt&&zr&&zr.parentElement===Jt?Jt.insertBefore(Mt,zr):Jt&&Jt.appendChild(Mt)}let kr=$e.closeButtonWrapper;kr&&!kr.classList.contains("persona-absolute")&&(vr?kr.classList.add("persona-ml-auto"):kr.classList.remove("persona-ml-auto"))}}if(rt){if(!I()){let nt=(Sm=re.size)!=null?Sm:"32px";Ke.style.height=nt,Ke.style.width=nt}let dr=(Am=re.iconName)!=null?Am:"refresh-cw",vr=(Mm=re.iconColor)!=null?Mm:"";Ke.style.color=vr||Pr.actionIconColor,Ke.innerHTML="";let bo=I()?"14px":"20px",kr=ge(dr,bo,"currentColor",2);if(kr&&Ke.appendChild(kr),re.backgroundColor?(Ke.style.backgroundColor=re.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let nt=re.borderWidth||"0px",cr=re.borderColor||"transparent";Ke.style.border=`${nt} solid ${cr}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");re.borderRadius?(Ke.style.borderRadius=re.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),re.paddingX?(Ke.style.paddingLeft=re.paddingX,Ke.style.paddingRight=re.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),re.paddingY?(Ke.style.paddingTop=re.paddingY,Ke.style.paddingBottom=re.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let Jt=(Tm=re.tooltipText)!=null?Tm:"Clear chat",zr=(Em=re.showTooltip)!=null?Em:!0;if(Ke.setAttribute("aria-label",Jt),Mt&&(Mt._cleanupTooltip&&(Mt._cleanupTooltip(),delete Mt._cleanupTooltip),zr&&Jt)){let nt=null,cr=()=>{if(nt||!Ke)return;let Zn=Ke.ownerDocument,ds=Zn.body;if(!ds)return;nt=qo(Zn,"div","persona-clear-chat-tooltip"),nt.textContent=Jt;let cs=qo(Zn,"div");cs.className="persona-clear-chat-tooltip-arrow",nt.appendChild(cs);let ea=Ke.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Dn),nt.style.left=`${ea.left+ea.width/2}px`,nt.style.top=`${ea.top-8}px`,nt.style.transform="translate(-50%, -100%)",ds.appendChild(nt)},Wr=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Mt.addEventListener("mouseenter",cr),Mt.addEventListener("mouseleave",Wr),Ke.addEventListener("focus",cr),Ke.addEventListener("blur",Wr),Mt._cleanupTooltip=()=>{Wr(),Mt&&(Mt.removeEventListener("mouseenter",cr),Mt.removeEventListener("mouseleave",Wr)),Ke&&(Ke.removeEventListener("focus",cr),Ke.removeEventListener("blur",Wr))}}}}let or=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Us],no=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ha.message,ha.messageAndClick];A=qs({parsers:or,handlers:no,getSessionMetadata:x,updateSessionMetadata:b,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),te=Sx(o,A,ce),q.updateConfig(o),rs(et,q.getMessages(),te),ba(),Xp(),vl(q.isStreaming());let Vr=((km=o.voiceRecognition)==null?void 0:km.enabled)===!0,Xn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Qn=((Pm=(Lm=o.voiceRecognition)==null?void 0:Lm.provider)==null?void 0:Pm.type)==="runtype";if(Vr&&(Xn||Qn))if(!N||!ye){let re=Cy(o.voiceRecognition,o.sendButton);re&&(N=re.micButton,ye=re.micButtonWrapper,Pt.insertBefore(ye,Sr),N.addEventListener("click",Xs),N.disabled=q.isStreaming())}else{let re=(Rm=o.voiceRecognition)!=null?Rm:{},Ct=(Im=o.sendButton)!=null?Im:{},Vt=(Wm=re.iconName)!=null?Wm:"mic",rt=(Hm=Ct.size)!=null?Hm:"40px",Et=(Bm=re.iconSize)!=null?Bm:rt,dr=parseFloat(Et)||24;N.style.width=Et,N.style.height=Et,N.style.minWidth=Et,N.style.minHeight=Et;let vr=(Fm=(Dm=re.iconColor)!=null?Dm:Ct.textColor)!=null?Fm:"currentColor";N.innerHTML="";let bo=ge(Vt,dr,vr,2);bo?N.appendChild(bo):N.textContent="\u{1F3A4}";let kr=(Nm=re.backgroundColor)!=null?Nm:Ct.backgroundColor;kr?N.style.backgroundColor=kr:N.style.backgroundColor="",vr?N.style.color=vr:N.style.color="var(--persona-text, #111827)",re.borderWidth?(N.style.borderWidth=re.borderWidth,N.style.borderStyle="solid"):(N.style.borderWidth="",N.style.borderStyle=""),re.borderColor?N.style.borderColor=re.borderColor:N.style.borderColor="",re.paddingX?(N.style.paddingLeft=re.paddingX,N.style.paddingRight=re.paddingX):(N.style.paddingLeft="",N.style.paddingRight=""),re.paddingY?(N.style.paddingTop=re.paddingY,N.style.paddingBottom=re.paddingY):(N.style.paddingTop="",N.style.paddingBottom="");let Jt=ye==null?void 0:ye.querySelector(".persona-send-button-tooltip"),zr=(Om=re.tooltipText)!=null?Om:"Start voice recognition";if(((_m=re.showTooltip)!=null?_m:!1)&&zr)if(Jt)Jt.textContent=zr,Jt.style.display="";else{let cr=document.createElement("div");cr.className="persona-send-button-tooltip",cr.textContent=zr,ye==null||ye.insertBefore(cr,N)}else Jt&&(Jt.style.display="none");ye.style.display="",N.disabled=q.isStreaming()}else N&&ye&&(ye.style.display="none",((qm=(Um=o.voiceRecognition)==null?void 0:Um.provider)==null?void 0:qm.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():No&&wn());if(((Vm=o.attachments)==null?void 0:Vm.enabled)===!0)if(!bt||!Oe){let re=($m=o.attachments)!=null?$m:{},Vt=(jm=((zm=o.sendButton)!=null?zm:{}).size)!=null?jm:"40px";Wt||(Wt=w("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Wt.style.display="none",yt.insertBefore(Wt,Z)),Qe||(Qe=document.createElement("input"),Qe.type="file",Qe.accept=((Gm=re.allowedTypes)!=null?Gm:an).join(","),Qe.multiple=((Km=re.maxFiles)!=null?Km:4)>1,Qe.style.display="none",Qe.setAttribute("aria-label","Attach files"),yt.insertBefore(Qe,Z)),bt=w("div","persona-send-button-wrapper"),Oe=w("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",(Xm=re.buttonTooltipText)!=null?Xm:"Attach file");let rt=(Qm=re.buttonIconName)!=null?Qm:"paperclip",Et=Vt,dr=parseFloat(Et)||40,vr=Math.round(dr*.6);Oe.style.width=Et,Oe.style.height=Et,Oe.style.minWidth=Et,Oe.style.minHeight=Et,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 bo=ge(rt,vr,"currentColor",1.5);bo?Oe.appendChild(bo):Oe.textContent="\u{1F4CE}",Oe.addEventListener("click",zr=>{zr.preventDefault(),Qe==null||Qe.click()}),bt.appendChild(Oe);let kr=(Jm=re.buttonTooltipText)!=null?Jm:"Attach file",Jt=w("div","persona-send-button-tooltip");Jt.textContent=kr,bt.appendChild(Jt),at.append(bt),!vt&&Qe&&Wt&&(vt=da.fromConfig(re),vt.setPreviewsContainer(Wt),Qe.addEventListener("change",async()=>{vt&&(Qe!=null&&Qe.files)&&(await vt.handleFileSelect(Qe.files),Qe.value="")})),Ce.querySelector(".persona-attachment-drop-overlay")||Ce.appendChild(Ax(re.dropOverlay))}else{bt.style.display="";let re=(Ym=o.attachments)!=null?Ym:{};Qe&&(Qe.accept=((Zm=re.allowedTypes)!=null?Zm:an).join(","),Qe.multiple=((eg=re.maxFiles)!=null?eg:4)>1),vt&&vt.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}else bt&&(bt.style.display="none"),vt&&vt.clearAttachments(),(tg=Ce.querySelector(".persona-attachment-drop-overlay"))==null||tg.remove();let Gt=(rg=o.sendButton)!=null?rg:{},Jn=(og=Gt.useIcon)!=null?og:!1,Sn=(ng=Gt.iconText)!=null?ng:"\u2191",An=Gt.iconName,tn=(ag=Gt.tooltipText)!=null?ag:"Send message",Yn=(sg=Gt.showTooltip)!=null?sg:!1,yo=(ig=Gt.size)!=null?ig:"40px",Oo=Gt.backgroundColor,Xe=Gt.textColor;if(Jn){if(Ue.style.width=yo,Ue.style.height=yo,Ue.style.minWidth=yo,Ue.style.minHeight=yo,Ue.style.fontSize="18px",Ue.style.lineHeight="1",Ue.innerHTML="",Xe?Ue.style.color=Xe:Ue.style.color="var(--persona-button-primary-fg, #ffffff)",An){let re=parseFloat(yo)||24,Ct=(Xe==null?void 0:Xe.trim())||"currentColor",Vt=ge(An,re,Ct,2);Vt?Ue.appendChild(Vt):Ue.textContent=Sn}else Ue.textContent=Sn;Ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Oo?(Ue.style.backgroundColor=Oo,Ue.classList.remove("persona-bg-persona-primary")):(Ue.style.backgroundColor="",Ue.classList.add("persona-bg-persona-primary"))}else Ue.textContent=(dg=(lg=o.copy)==null?void 0:lg.sendButtonLabel)!=null?dg:"Send",Ue.style.width="",Ue.style.height="",Ue.style.minWidth="",Ue.style.minHeight="",Ue.style.fontSize="",Ue.style.lineHeight="",Ue.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",Oo?(Ue.style.backgroundColor=Oo,Ue.classList.remove("persona-bg-persona-accent")):Ue.classList.add("persona-bg-persona-accent"),Xe?Ue.style.color=Xe:Ue.classList.add("persona-text-white");Gt.borderWidth?(Ue.style.borderWidth=Gt.borderWidth,Ue.style.borderStyle="solid"):(Ue.style.borderWidth="",Ue.style.borderStyle=""),Gt.borderColor?Ue.style.borderColor=Gt.borderColor:Ue.style.borderColor="",Gt.paddingX?(Ue.style.paddingLeft=Gt.paddingX,Ue.style.paddingRight=Gt.paddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Gt.paddingY?(Ue.style.paddingTop=Gt.paddingY,Ue.style.paddingBottom=Gt.paddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let Bt=Sr==null?void 0:Sr.querySelector(".persona-send-button-tooltip");if(Yn&&tn)if(Bt)Bt.textContent=tn,Bt.style.display="";else{let re=document.createElement("div");re.className="persona-send-button-tooltip",re.textContent=tn,Sr==null||Sr.insertBefore(re,Ue)}else Bt&&(Bt.style.display="none");let zt=(mg=(cg=o.layout)==null?void 0:cg.contentMaxWidth)!=null?mg:I()?(fg=(ug=(pg=o.launcher)==null?void 0:pg.composerBar)==null?void 0:ug.contentMaxWidth)!=null?fg:"720px":void 0;zt?(et.style.maxWidth=zt,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%",yt&&(yt.style.maxWidth=zt,yt.style.marginLeft="auto",yt.style.marginRight="auto"),Lt&&(Lt.style.maxWidth=zt,Lt.style.marginLeft="auto",Lt.style.marginRight="auto")):(et.style.maxWidth="",et.style.marginLeft="",et.style.marginRight="",et.style.width="",yt&&(yt.style.maxWidth="",yt.style.marginLeft="",yt.style.marginRight=""),Lt&&(Lt.style.maxWidth="",Lt.style.marginLeft="",Lt.style.marginRight=""));let Dt=(gg=o.statusIndicator)!=null?gg:{},Kt=(hg=Dt.visible)!=null?hg:!0;if(xr.style.display=Kt?"":"none",q){let re=q.getStatus();Qt(xr,(Vt=>{var rt,Et,dr,vr;return Vt==="idle"?(rt=Dt.idleText)!=null?rt:wr.idle:Vt==="connecting"?(Et=Dt.connectingText)!=null?Et:wr.connecting:Vt==="connected"?(dr=Dt.connectedText)!=null?dr:wr.connected:Vt==="error"?(vr=Dt.errorText)!=null?vr:wr.error:wr[Vt]})(re),Dt,re)}xr.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Tt=Dt.align==="left"?"persona-text-left":Dt.align==="center"?"persona-text-center":"persona-text-right";xr.classList.add(Tt)},open(){F()&&Ut(!0,"api")},close(){F()&&Ut(!1,"api")},toggle(){F()&&Ut(!O,"api")},clearChat(){Ar=!1,q.clearMessages(),Ho.clear(),bn();try{localStorage.removeItem(Xa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xa}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Xa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let d=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(d),l!=null&&l.clear)try{let m=l.clear();m instanceof Promise&&m.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}p={},A.syncFromMetadata(),j==null||j.clear(),J==null||J.reset(),Ne==null||Ne.update()},setMessage(d){return!Z||q.isStreaming()?!1:(!O&&F()&&Ut(!0,"system"),Z.value=d,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(d){if(q.isStreaming())return!1;let m=(d==null?void 0:d.trim())||Z.value.trim();return m?(!O&&F()&&Ut(!0,"system"),Z.value="",Z.style.height="auto",q.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return q.isStreaming()?!1:((h=(m=o.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(q.isVoiceActive()||(!O&&F()&&Ut(!0,"system"),oe.manuallyDeactivated=!1,Or(),q.toggleVoice().then(()=>{oe.active=q.isVoiceActive(),ct("user"),q.isVoiceActive()&&Ma()})),!0):No?!0:ru()?(!O&&F()&&Ut(!0,"system"),oe.manuallyDeactivated=!1,Or(),Gs("user"),!0):!1},stopVoiceRecognition(){var d,m;return((m=(d=o.voiceRecognition)==null?void 0:d.provider)==null?void 0:m.type)==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{oe.active=!1,oe.manuallyDeactivated=!0,Or(),ct("user"),en()}),!0):!1:No?(oe.manuallyDeactivated=!0,Or(),wn("user"),!0):!1},injectMessage(d){return!O&&F()&&Ut(!0,"system"),q.injectMessage(d)},injectAssistantMessage(d){!O&&F()&&Ut(!0,"system");let m=q.injectAssistantMessage(d);return Q&&(Q=!1,he&&(clearTimeout(he),he=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),m},injectUserMessage(d){return!O&&F()&&Ut(!0,"system"),q.injectUserMessage(d)},injectSystemMessage(d){return!O&&F()&&Ut(!0,"system"),q.injectSystemMessage(d)},injectMessageBatch(d){return!O&&F()&&Ut(!0,"system"),q.injectMessageBatch(d)},injectComponentDirective(d){return!O&&F()&&Ut(!0,"system"),q.injectComponentDirective(d)},injectTestMessage(d){!O&&F()&&Ut(!0,"system"),q.injectTestEvent(d)},async connectStream(d,m){return q.connectStream(d,m)},__pushEventStreamEvent(d){j&&(J==null||J.processEvent(d.type,d.payload),j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:d.type,timestamp:Date.now(),payload:JSON.stringify(d.payload)}))},showEventStream(){!de||!j||Go()},hideEventStream(){K&&fo()},isEventStreamVisible(){return K},showArtifacts(){io(o)&&(Ar=!1,Ro(),ht==null||ht.setMobileOpen(!0))},hideArtifacts(){io(o)&&(Ar=!0,Ro())},upsertArtifact(d){return io(o)?(Ar=!1,q.upsertArtifact(d)):null},selectArtifact(d){io(o)&&q.selectArtifact(d)},clearArtifacts(){io(o)&&q.clearArtifacts()},getArtifacts(){var d;return(d=q==null?void 0:q.getArtifacts())!=null?d:[]},getSelectedArtifactId(){var d;return(d=q==null?void 0:q.getSelectedArtifactId())!=null?d:null},focusInput(){return T&&!O&&!I()||!Z?!1:(Z.focus(),!0)},async resolveApproval(d,m,h){let R=q.getMessages().find(D=>{var $;return D.variant==="approval"&&(($=D.approval)==null?void 0:$.id)===d});if(!(R!=null&&R.approval))throw new Error(`Approval not found: ${d}`);if(R.approval.toolType==="webmcp"){q.resolveWebMcpApproval(R.id,m);return}return q.resolveApproval(R.approval,m,h)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(d){b(d)},on(d,m){return i.on(d,m)},off(d,m){i.off(d,m)},isOpen(){return F()&&O},isVoiceActive(){return oe.active},toggleReadAloud(d){q.toggleReadAloud(d)},stopReadAloud(){q.stopSpeaking()},getReadAloudState(d){return q.getReadAloudState(d)},onReadAloudChange(d){return q.onReadAloudChange(d)},getState(){return{open:F()&&O,launcherEnabled:T,voiceActive:oe.active,streaming:q.isStreaming()}},showCSATFeedback(d){!O&&F()&&Ut(!0,"system");let m=et.querySelector(".persona-feedback-container");m&&m.remove();let h=ul({onSubmit:async(C,R)=>{var D;q.isClientTokenMode()&&await q.submitCSATFeedback(C,R),(D=d==null?void 0:d.onSubmit)==null||D.call(d,C,R)},onDismiss:d==null?void 0:d.onDismiss,...d});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(d){!O&&F()&&Ut(!0,"system");let m=et.querySelector(".persona-feedback-container");m&&m.remove();let h=fl({onSubmit:async(C,R)=>{var D;q.isClientTokenMode()&&await q.submitNPSFeedback(C,R),(D=d==null?void 0:d.onSubmit)==null||D.call(d,C,R)},onDismiss:d==null?void 0:d.onDismiss,...d});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(d,m){return q.submitCSATFeedback(d,m)},async submitNPSFeedback(d,m){return q.submitNPSFeedback(d,m)},destroy(){Kn!=null&&(clearInterval(Kn),Kn=null),st.forEach(d=>d()),xe.remove(),dt==null||dt.remove(),Yt==null||Yt.destroy(),lr==null||lr.remove(),Wo&&P.removeEventListener("click",Wo)}};if((((uf=r==null?void 0:r.debugTools)!=null?uf:!1)||!!o.debug)&&typeof window!="undefined"){let d=window.AgentWidgetBrowser,m={controller:rr,getMessages:rr.getMessages,getStatus:rr.getStatus,getMetadata:rr.getPersistentMetadata,updateMetadata:rr.updatePersistentMetadata,clearHistory:()=>rr.clearChat(),setVoiceActive:h=>h?rr.startVoiceRecognition():rr.stopVoiceRecognition()};window.AgentWidgetBrowser=m,st.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=d)})}if(typeof window!="undefined"){let d=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&rr.focusInput()};if(window.addEventListener("persona:focusInput",m),st.push(()=>{window.removeEventListener("persona:focusInput",m)}),de){let U=ie=>{let ae=ie.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===d)&&rr.showEventStream()},_=ie=>{let ae=ie.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===d)&&rr.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",_),st.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",_)})}let h=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&rr.showArtifacts()},C=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&rr.hideArtifacts()},R=U=>{let _=U.detail;_!=null&&_.instanceId&&_.instanceId!==d||_!=null&&_.artifact&&rr.upsertArtifact(_.artifact)},D=U=>{let _=U.detail;_!=null&&_.instanceId&&_.instanceId!==d||typeof(_==null?void 0:_.id)=="string"&&rr.selectArtifact(_.id)},$=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===d)&&rr.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",$),st.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",$)})}let oo=A0(o.persistState);if(oo&&F()){let d=M0(oo.storage),m=`${oo.keyPrefix}widget-open`,h=`${oo.keyPrefix}widget-voice`,C=`${oo.keyPrefix}widget-voice-mode`;if(d){let R=((ff=oo.persist)==null?void 0:ff.openState)&&d.getItem(m)==="true",D=((mf=oo.persist)==null?void 0:mf.voiceState)&&d.getItem(h)==="true",$=((gf=oo.persist)==null?void 0:gf.voiceState)&&d.getItem(C)==="true";if(R&&setTimeout(()=>{rr.open(),setTimeout(()=>{var U;if(D||$)rr.startVoiceRecognition();else if((U=oo.persist)!=null&&U.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),(hf=oo.persist)!=null&&hf.openState&&(i.on("widget:opened",()=>{d.setItem(m,"true")}),i.on("widget:closed",()=>{d.setItem(m,"false")})),(xf=oo.persist)!=null&&xf.voiceState&&(i.on("voice:state",U=>{d.setItem(h,U.active?"true":"false")}),i.on("user:message",U=>{d.setItem(C,U.viaVoice?"true":"false")})),oo.clearOnChatClear){let U=()=>{d.removeItem(m),d.removeItem(h),d.removeItem(C)},_=()=>U();window.addEventListener("persona:clear-chat",_),st.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return u&&F()&&setTimeout(()=>{rr.open()},0),Sa(),zs||Ys().then(()=>{q&&(va++,Ho.clear(),rs(et,q.getMessages(),te))}).catch(()=>{}),rr};var T0=(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},E0=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},k0=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},L0=(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.")},Mx=(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"},Ep=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=""},Tx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Ep(e)},Ap=e=>{e.style.transition=""},Mp=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=""},Tp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},hl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},P0=(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))},R0=(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)},Ex=(e,t,r,o,n,a,s)=>{var x,b,L,E,A,T;let i=Gr(a),c=i.reveal==="push";P0(e,t,r,o,c),R0(e,t,r,o,i.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(b=(x=a==null?void 0:a.launcher)==null?void 0:x.mobileFullscreen)!=null?b:!0,f=(E=(L=a==null?void 0:a.launcher)==null?void 0:L.mobileBreakpoint)!=null?E:640,u=l!=null?l.innerWidth<=f:!1;if(p&&u&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Mp(t),Ap(o),Tx(o),Tp(r),hl(n,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((T=(A=a==null?void 0:a.launcher)==null?void 0:A.zIndex)!=null?T:Cr),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"),Tx(o),E0(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",Mp(t),Ap(o),Tp(r),hl(n,o);let y=i.animate?"transform 180ms ease":"none",S=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=s?"translateX(0)":S;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=y,o.style.transform=v,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Ap(o),Ep(o),hl(n,o);let y=T0(i.width,e.clientWidth),S=Math.max(0,e.clientWidth),v=i.animate?"margin-left 180ms ease":"none",M=i.side==="right"?s?-y:0:s?0:-y;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${S+y}px`,t.style.transition=v,t.style.marginLeft=`${M}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${S}px`,r.style.maxWidth=`${S}px`,r.style.minWidth=`${S}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Mp(t),Ep(o),Tp(r),hl(n,o);let y=i.reveal==="emerge";y?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=s?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",M=!s;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",k0(o,i.maxHeight),o.style.overflow=y||M?"hidden":"visible",o.style.transition=v,y&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.boxSizing="border-box")}},I0=(e,t)=>{let r=e.ownerDocument.createElement("div");return Mx(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){Mx(r,o)},destroy(){r.remove()}}},W0=(e,t)=>{var T,y,S,v;let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),c=r.createElement("div"),l=r.createElement("aside"),p=r.createElement("div"),f=(y=(T=t==null?void 0:t.launcher)==null?void 0:T.enabled)==null||y?(v=(S=t==null?void 0:t.launcher)==null?void 0:S.autoExpand)!=null?v:!1:!0;i.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),o.insertBefore(s,e),c.appendChild(e);let u=null,g=()=>{u==null||u.disconnect(),u=null},x=()=>{g(),Gr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{Ex(s,i,c,l,p,t,f)}),u.observe(s))},b=!1,L=()=>{Ex(s,i,c,l,p,t,f),x(),f&&!b&&s.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,L0(s,Gr(t)))},E=s.ownerDocument.defaultView,A=()=>{L()};return E==null||E.addEventListener("resize",A),Gr(t).reveal==="push"?(i.appendChild(c),i.appendChild(l),s.appendChild(i)):(s.appendChild(c),s.appendChild(l)),L(),{mode:"docked",host:p,shell:s,syncWidgetState(M){let W=M.launcherEnabled?M.open:!0;f!==W&&(f=W,L())},updateConfig(M){var W,H;t=M,((H=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)!=null?H:!0)===!1&&(f=!0),L()},destroy(){E==null||E.removeEventListener("resize",A),g(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Vs=(e,t)=>nr(t)?W0(e,t):I0(e,t);var kp={},H0=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},B0=()=>{try{if(typeof kp!="undefined"&&kp.url)return new URL("../widget.css",kp.url).href}catch{}return null},kx=(e,t)=>{let r=B0(),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)}},Lx=e=>{var L;let t=H0(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Vs(t,n),s,i=[],c=(E,A)=>{var v,M;let y=!((M=(v=A==null?void 0:A.launcher)==null?void 0:v.enabled)!=null?M:!0)||nr(A),S=o.createElement("div");if(S.setAttribute("data-persona-root","true"),y&&(S.style.height="100%",S.style.display="flex",S.style.flexDirection="column",S.style.flex="1",S.style.minHeight="0"),r){let W=E.attachShadow({mode:"open"});W.appendChild(S),kx(W,o)}else E.appendChild(S),kx(E,o);return t.id&&S.setAttribute("data-persona-instance",t.id),S},l=()=>{a.syncWidgetState(s.getState())},p=()=>{i.forEach(E=>E()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},f=()=>{let E=c(a.host,n);s=gl(E,n,{debugTools:e.debugTools}),p()},u=()=>{i.forEach(E=>E()),i=[],s.destroy()};f(),(L=e.onChatReady)==null||L.call(e);let g=E=>{u(),a.destroy(),a=Vs(t,E),n=E,f()},x={update(E){var M,W,H,I,F,O;let A={...n,...E,launcher:{...(M=n==null?void 0:n.launcher)!=null?M:{},...(W=E==null?void 0:E.launcher)!=null?W:{},dock:{...(I=(H=n==null?void 0:n.launcher)==null?void 0:H.dock)!=null?I:{},...(O=(F=E==null?void 0:E.launcher)==null?void 0:F.dock)!=null?O:{}}}},T=nr(n),y=nr(A),S=Nn(n),v=Nn(A);if(T!==y||S!==v){g(A);return}n=A,a.updateConfig(n),s.update(E),l()},destroy(){u(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},b=new Proxy(x,{get(E,A,T){if(A==="host")return a.host;if(A in E)return Reflect.get(E,A,T);let y=s[A];return typeof y=="function"?y.bind(s):y}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=b),b};var Hx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),D0=new Set(["button","a","input","select","textarea","details","summary"]),F0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Lp=/\b(product|card|item|listing|result)\b/i,Rp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,N0=3e3,O0=100;function Bx(e){let t=typeof e.className=="string"?e.className:"";if(Lp.test(t)||e.id&&Lp.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&Lp.test(o.value))return!0}return!1}function Dx(e){var t;return Rp.test(((t=e.textContent)!=null?t:"").trim())}function Fx(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 _0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Px(e){let t=e.match(Rp);return t?t[0]:null}function Rx(e){var o,n,a;let t=(o=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?o:e.querySelector("a[href]");if(t&&((n=t.textContent)!=null&&n.trim())){let s=t.getAttribute("href");return{title:t.textContent.trim(),href:s&&s!=="#"?s:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return(a=r==null?void 0:r.textContent)!=null&&a.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function U0(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 q0="commerce-card",V0="result-card";function Ix(e){return!Bx(e)||!Dx(e)||!Fx(e)&&!_0(e)?0:5200}function Wx(e){var o;return!Bx(e)||Dx(e)||!Fx(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 Ip=[{id:q0,scoreElement(e){return Ix(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||Rp.test(o)&&o.length<32)}return!0},formatSummary(e,t){var c,l,p;if(Ix(e)===0)return null;let{title:r,href:o}=Rx(e),n=(p=(l=Px(((c=e.textContent)!=null?c:"").trim()))!=null?l:Px(t.text))!=null?p:"",a=U0(e);return[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
113
+ `)}},{id:V0,scoreElement(e){return Wx(e)},formatSummary(e,t){if(Wx(e)===0)return null;let{title:r,href:o}=Rx(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
114
+ `)}}];function $0(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function z0(e){var p,f,u,g,x,b,L,E,A,T,y,S,v;let t=(p=e.options)!=null?p:{},r=(u=(f=t.maxElements)!=null?f:e.maxElements)!=null?u:80,o=(x=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?x:".persona-host",n=(L=(b=t.maxTextLength)!=null?b:e.maxTextLength)!=null?L:200,a=(A=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?A:!0,s=(T=t.root)!=null?T:e.root,i=(y=t.mode)!=null?y:"structured",c=(S=t.maxCandidates)!=null?S:Math.max(500,r*10),l=(v=e.rules)!=null?v:Ip;return i==="simple"&&e.rules&&e.rules.length>0?($0(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:r,maxCandidates:c,excludeSelector:o,maxTextLength:n,visibleOnly:a,root:s,rules:l}}function Pp(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var j0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function G0(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"||D0.has(t)||r&&F0.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Nx(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 K0(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let c=e.getAttribute("role");c&&(t.role=c);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Wp(e){let t=e.tagName.toLowerCase();if(e.id){let n=`#${Pp(e.id)}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}}for(let n of j0){let a=e.getAttribute(n);if(a){let s=`${t}[${n}="${Pp(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=>Pp(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 X0(e){return e==="static"?O0:N0}function Ox(e,t){var n;let r=e.tagName.toLowerCase(),o=((n=e.textContent)!=null?n:"").trim().substring(0,t);return{selector:Wp(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:G0(e),attributes:K0(e)}}function Q0(e,t,r,o){let n=X0(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 J0(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 Y0(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(Hx.has(p)){i=s.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Nx(l)){i=s.nextNode();continue}let f=Ox(l,e.maxTextLength),u=f.text.length>0,g=Object.keys(f.attributes).length>0&&!Object.keys(f.attributes).every(L=>L==="role");if(!u&&!g){i=s.nextNode();continue}if(o.has(f.selector)){i=s.nextNode();continue}o.add(f.selector);let{score:x,formattingRule:b}=Q0(l,f,e.rules,r);n.push({el:l,domIndex:a,enriched:f,score:x,formattingRule:b}),a+=1}i=s.nextNode()}n.sort((l,p)=>{let f=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return f!==u?f-u:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let c=[];for(let l of n){if(c.length>=e.maxElements)break;J0(c,l)||c.push(l)}return c.sort((l,p)=>{let f=l.enriched.interactivity==="static"?1:0,u=p.enriched.interactivity==="static"?1:0;return f!==u?f-u:f===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),c.map(l=>{var u;let p;if((u=l.formattingRule)!=null&&u.formatSummary){let g=l.formattingRule.formatSummary(l.el,l.enriched,r);g&&(p=g)}let f={...l.enriched};return p&&(f.formattedSummary=p),f})}function Z0(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,l=c.tagName.toLowerCase();if(Hx.has(l)){a=n.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!Nx(c)){a=n.nextNode();continue}let p=Ox(c,e.maxTextLength),f=p.text.length>0,u=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!f&&!u){a=n.nextNode();continue}o.has(p.selector)||(o.add(p.selector),r.push(p))}a=n.nextNode()}let s=[],i=[];for(let c of r)c.interactivity!=="static"?s.push(c):i.push(c);return[...s,...i].slice(0,e.maxElements)}function _x(e={}){var o;let t=z0(e),r=(o=t.root)!=null?o:document.body;return r?t.mode==="simple"?Z0(t,r):Y0(t,r):[]}var xl=100;function Ux(e,t={}){var a;if(e.length===0)return"No page elements found.";let r=(a=t.mode)!=null?a:"structured",o=[];if(r==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
115
115
  ${s.map(i=>`- ${i.split(`
116
116
  `).join(`
117
117
  `)}`).join(`
118
- `)}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let s of e)r==="structured"&&s.formattedSummary||n[s.interactivity].push(s);if(n.clickable.length>0){let s=n.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,ul)}" (clickable)`);o.push(`Interactive elements:
118
+ `)}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let s of e)r==="structured"&&s.formattedSummary||n[s.interactivity].push(s);if(n.clickable.length>0){let s=n.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,xl)}" (clickable)`);o.push(`Interactive elements:
119
119
  ${s.join(`
120
- `)}`)}if(n.navigable.length>0){let s=n.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,ul)}" (navigable)`);o.push(`Navigation links:
120
+ `)}`)}if(n.navigable.length>0){let s=n.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,xl)}" (navigable)`);o.push(`Navigation links:
121
121
  ${s.join(`
122
- `)}`)}if(n.input.length>0){let s=n.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,ul)}" (input)`);o.push(`Form inputs:
122
+ `)}`)}if(n.input.length>0){let s=n.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,xl)}" (input)`);o.push(`Form inputs:
123
123
  ${s.join(`
124
- `)}`)}if(n.static.length>0){let s=n.static.map(i=>`- ${i.selector}: "${i.text.substring(0,ul)}"`);o.push(`Content:
124
+ `)}`)}if(n.static.length>0){let s=n.static.map(i=>`- ${i.selector}: "${i.text.substring(0,xl)}"`);o.push(`Content:
125
125
  ${s.join(`
126
126
  `)}`)}return o.join(`
127
127
 
128
- `)}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:Oo(e.colors.primary,.95),100:Oo(e.colors.primary,.9),200:Oo(e.colors.primary,.8),300:Oo(e.colors.primary,.7),400:Oo(e.colors.primary,.6),500:e.colors.primary,600:Oo(e.colors.primary,.8),700:Oo(e.colors.primary,.7),800:Oo(e.colors.primary,.6),900:Oo(e.colors.primary,.5),950:Oo(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 Rx(){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 Oo(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 Ix(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var B0={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"}}},Ep={id:"shop",label:"Shopping Assistant",config:{theme:B0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Jr},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?"]}},kp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Wx}},Lp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Wx}},Pp={shop:Ep,minimal:kp,fullscreen:Lp};function Hx(e){return Pp[e]}var D0=`
128
+ `)}function qx(){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 Vx(){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 $x(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 zx(){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 jx(){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 Gx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var ew={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"}}},Kx={components:{panel:{borderRadius:"0",shadow:"none"}}},Hp={id:"shop",label:"Shopping Assistant",config:{theme:ew,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:jr},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?"]}},Bp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Kx}},Dp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Kx}},Fp={shop:Hp,minimal:Bp,fullscreen:Dp};function Xx(e){return Fp[e]}var tw=`
129
129
  @keyframes persona-stream-wipe {
130
130
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
131
131
  to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
@@ -161,7 +161,7 @@ ${s.join(`
161
161
  mask-image: none !important;
162
162
  }
163
163
  }
164
- `.trim(),F0={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:D0};ra(F0);var N0=`
164
+ `.trim(),rw={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:tw};ca(rw);var ow=`
165
165
  [data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
166
166
  animation: persona-stream-glyph-cycle-fade
167
167
  calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
@@ -179,7 +179,7 @@ ${s.join(`
179
179
  opacity: 1 !important;
180
180
  }
181
181
  }
182
- `.trim(),Ds="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",O0=10,_0=120,Rp=120,U0=.4,q0=50,V0=e=>{var o;if(!e)return Rp;let r=((o=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:o.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Rp},qx=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=V0(t);return _0*r/Rp},Ip=e=>{let t=Ds[Math.floor(Math.random()*Ds.length)];return e&&t===e&&(t=Ds[(Ds.indexOf(t)+1)%Ds.length]),t},z0=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()<U0&&(n.textContent=Ip())}},Bx=new WeakMap,Dx=25,Fx=.5,$0=6,Nx=.25,Ox=new WeakMap,_x=new WeakMap,j0=(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($0,o*Fx)},za=new Map,G0=e=>{var r;let t=e.closest("[data-message-id]");return(r=t==null?void 0:t.dataset.messageId)!=null?r:null},K0=e=>{var t;e&&za.set(e,((t=za.get(e))!=null?t:0)+1)},X0=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)},Vx=e=>{var l;if(e.dataset.glyphCycleScheduled==="true")return;let t=(l=e.textContent)!=null?l:"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Ip();let r=G0(e);r&&(e.dataset.glyphCycleMessageId=r),K0(r);let o=e.closest(".persona-stream-glyph-cycle"),n=Date.now(),a=j0(o,n),s=qx(e),i=O0*s,c=n+i;if(o){let p=Bx.get(o);p!==void 0&&(c=Math.max(c,p)),Bx.set(o,c+a)}J0(e,t,c)},J0=(e,t,r)=>{var s;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=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,X0((c=e.dataset.glyphCycleMessageId)!=null?c:null),delete e.dataset.glyphCycleMessageId;return}let i=Ip(n);e.textContent=i,n=i,z0(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)},Q0=e=>e.nodeType===1,Y0={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:N0,bufferContent(e){if(e.length<q0)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){Ux(e);let t=new MutationObserver(r=>{for(let o of r)for(let n of Array.from(o.addedNodes))Q0(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()}};ra(Y0);var zx,$x,tr=typeof document!="undefined"&&($x=(zx=document.currentScript)==null?void 0:zx.src)!=null?$x:null;hg(()=>{let e=tr==null?void 0:tr.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===tr?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${tr!=null?tr:"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)});ng(()=>{let e=tr==null?void 0:tr.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===tr?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${tr!=null?tr:"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});Gs().catch(e=>{typeof console!="undefined"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});eh(()=>{let e=tr==null?void 0:tr.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===tr?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${tr!=null?tr:"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 hy(Z0);})();
182
+ `.trim(),$s="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",nw=10,aw=120,Np=120,sw=.4,iw=50,lw=e=>{var o;if(!e)return Np;let r=((o=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:o.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Np},oy=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=lw(t);return aw*r/Np},Op=e=>{let t=$s[Math.floor(Math.random()*$s.length)];return e&&t===e&&(t=$s[($s.indexOf(t)+1)%$s.length]),t},dw=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()<sw&&(n.textContent=Op())}},Qx=new WeakMap,Jx=25,Yx=.5,cw=6,Zx=.25,ey=new WeakMap,ty=new WeakMap,pw=(e,t)=>{var n;if(!e)return Jx*Yx;let r=ey.get(e);ey.set(e,t);let o=(n=ty.get(e))!=null?n:Jx;if(r!==void 0){let a=t-r;a>1&&(o=o*(1-Zx)+a*Zx,ty.set(e,o))}return Math.max(cw,o*Yx)},Qa=new Map,uw=e=>{var r;let t=e.closest("[data-message-id]");return(r=t==null?void 0:t.dataset.messageId)!=null?r:null},fw=e=>{var t;e&&Qa.set(e,((t=Qa.get(e))!=null?t:0)+1)},mw=e=>{var r;if(!e)return;let t=(r=Qa.get(e))!=null?r:0;t<=1?Qa.delete(e):Qa.set(e,t-1)},ny=e=>{var l;if(e.dataset.glyphCycleScheduled==="true")return;let t=(l=e.textContent)!=null?l:"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Op();let r=uw(e);r&&(e.dataset.glyphCycleMessageId=r),fw(r);let o=e.closest(".persona-stream-glyph-cycle"),n=Date.now(),a=pw(o,n),s=oy(e),i=nw*s,c=n+i;if(o){let p=Qx.get(o);p!==void 0&&(c=Math.max(c,p)),Qx.set(o,c+a)}gw(e,t,c)},gw=(e,t,r)=>{var s;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=oy(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,mw((c=e.dataset.glyphCycleMessageId)!=null?c:null),delete e.dataset.glyphCycleMessageId;return}let i=Op(n);e.textContent=i,n=i,dw(e),setTimeout(a,o)};setTimeout(a,o)},ry=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))ny(o)},hw=e=>e.nodeType===1,xw={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:ow,bufferContent(e){if(e.length<iw)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=Qa.get(e.id))!=null?t:0)>0},onAttach(e){ry(e);let t=new MutationObserver(r=>{for(let o of r)for(let n of Array.from(o.addedNodes))hw(n)&&(n.classList.contains("persona-stream-char")&&n.closest(".persona-stream-glyph-cycle")?ny(n):ry(n))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};ca(xw);var ay,sy,er=typeof document!="undefined"&&(sy=(ay=document.currentScript)==null?void 0:ay.src)!=null?sy:null;Rg(()=>{let e=er==null?void 0:er.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===er?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${er!=null?er:"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)});bg(()=>{let e=er==null?void 0:er.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===er?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${er!=null?er:"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});Ys().catch(e=>{typeof console!="undefined"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});gh(()=>{let e=er==null?void 0:er.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===er?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${er!=null?er:"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 By(yw);})();
183
183
  /*! Bundled license information:
184
184
 
185
185
  lucide/dist/esm/icons/activity.mjs: