@runtypelabs/persona 3.35.0 → 3.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,21 @@
1
- "use strict";var AgentWidget=(()=>{var Xx=Object.create;var ui=Object.defineProperty;var Qx=Object.getOwnPropertyDescriptor;var Jx=Object.getOwnPropertyNames;var Yx=Object.getPrototypeOf,Zx=Object.prototype.hasOwnProperty;var Nl=(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 lg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ey=(e,t)=>{for(var r in t)ui(e,r,{get:t[r],enumerable:!0})},dg=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Jx(t))!Zx.call(e,n)&&n!==r&&ui(e,n,{get:()=>t[n],enumerable:!(o=Qx(t,n))||o.enumerable});return e};var La=(e,t,r)=>(r=e!=null?Xx(Yx(e)):{},dg(t||!e||!e.__esModule?ui(r,"default",{value:e,enumerable:!0}):r,e)),ty=e=>dg(ui({},"__esModule",{value:!0}),e);var zl=lg(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.Allow=Fe.ALL=Fe.COLLECTION=Fe.ATOM=Fe.SPECIAL=Fe.INF=Fe._INFINITY=Fe.INFINITY=Fe.NAN=Fe.BOOL=Fe.NULL=Fe.OBJ=Fe.ARR=Fe.NUM=Fe.STR=void 0;Fe.STR=1;Fe.NUM=2;Fe.ARR=4;Fe.OBJ=8;Fe.NULL=16;Fe.BOOL=32;Fe.NAN=64;Fe.INFINITY=128;Fe._INFINITY=256;Fe.INF=Fe.INFINITY|Fe._INFINITY;Fe.SPECIAL=Fe.NULL|Fe.BOOL|Fe.INF|Fe.NAN;Fe.ATOM=Fe.STR|Fe.NUM|Fe.SPECIAL;Fe.COLLECTION=Fe.ARR|Fe.OBJ;Fe.ALL=Fe.ATOM|Fe.COLLECTION;Fe.Allow={STR:Fe.STR,NUM:Fe.NUM,ARR:Fe.ARR,OBJ:Fe.OBJ,NULL:Fe.NULL,BOOL:Fe.BOOL,NAN:Fe.NAN,INFINITY:Fe.INFINITY,_INFINITY:Fe._INFINITY,INF:Fe.INF,SPECIAL:Fe.SPECIAL,ATOM:Fe.ATOM,COLLECTION:Fe.COLLECTION,ALL:Fe.ALL};Fe.default=Fe.Allow});var yi=lg(Ar=>{"use strict";var my=Ar&&Ar.__createBinding||(Object.create?(function(e,t,r,o){o===void 0&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}):(function(e,t,r,o){o===void 0&&(o=r),e[o]=t[r]})),gy=Ar&&Ar.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&my(t,e,r)};Object.defineProperty(Ar,"__esModule",{value:!0});Ar.Allow=Ar.MalformedJSON=Ar.PartialJSON=Ar.parseJSON=Ar.parse=void 0;var Or=zl();Object.defineProperty(Ar,"Allow",{enumerable:!0,get:function(){return Or.Allow}});gy(zl(),Ar);var hi=class extends Error{};Ar.PartialJSON=hi;var xi=class extends Error{};Ar.MalformedJSON=xi;function vg(e,t=Or.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return hy(e.trim(),t)}Ar.parseJSON=vg;var hy=(e,t)=>{let r=e.length,o=0,n=p=>{throw new hi(`${p} at position ${o}`)},a=p=>{throw new xi(`${p} at position ${o}`)},s=()=>(g(),o>=r&&n("Unexpected end of input"),e[o]==='"'?i():e[o]==="{"?c():e[o]==="["?d():e.substring(o,o+4)==="null"||Or.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Or.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Or.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Or.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Or.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Or.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):u()),i=()=>{let p=o,m=!1;for(o++;o<r&&(e[o]!=='"'||m&&e[o-1]==="\\");)m=e[o]==="\\"?!m:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(p,++o-Number(m)))}catch(x){a(String(x))}else if(Or.Allow.STR&t)try{return JSON.parse(e.substring(p,o-Number(m))+'"')}catch{return JSON.parse(e.substring(p,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{o++,g();let p={};try{for(;e[o]!=="}";){if(g(),o>=r&&Or.Allow.OBJ&t)return p;let m=i();g(),o++;try{let x=s();p[m]=x}catch(x){if(Or.Allow.OBJ&t)return p;throw x}g(),e[o]===","&&o++}}catch{if(Or.Allow.OBJ&t)return p;n("Expected '}' at end of object")}return o++,p},d=()=>{o++;let p=[];try{for(;e[o]!=="]";)p.push(s()),g(),e[o]===","&&o++}catch{if(Or.Allow.ARR&t)return p;n("Expected ']' at end of array")}return o++,p},u=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Or.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let p=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==r&&!(Or.Allow.NUM&t)&&n("Unterminated number literal");try{return JSON.parse(e.substring(p,o))}catch{e.substring(p,o)==="-"&&n("Not sure what '-' is");try{return JSON.parse(e.substring(p,e.lastIndexOf("e")))}catch(x){a(String(x))}}},g=()=>{for(;o<r&&`
2
- \r `.includes(e[o]);)o++};return s()},xy=vg;Ar.parse=xy});var E0={};ey(E0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>td,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>ed,ASK_USER_QUESTION_TOOL_NAME:()=>Cs,AgentWidgetClient:()=>oa,AgentWidgetSession:()=>_a,AttachmentManager:()=>ia,BrowserSpeechEngine:()=>In,DEFAULT_COMPONENTS:()=>np,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Xi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>oo,DEFAULT_PALETTE:()=>rp,DEFAULT_SEMANTIC:()=>op,DEFAULT_WIDGET_CONFIG:()=>_t,PRESETS:()=>zp,PRESET_FULLSCREEN:()=>$p,PRESET_MINIMAL:()=>Vp,PRESET_SHOP:()=>qp,ReadAloudController:()=>sa,SUGGEST_REPLIES_CLIENT_TOOL:()=>wi,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Jl,SUGGEST_REPLIES_TOOL_NAME:()=>Mo,THEME_ZONES:()=>sh,VERSION:()=>Sx,WEBMCP_TOOL_PREFIX:()=>tn,WebMcpBridge:()=>Wa,accessibilityPlugin:()=>Ax,animationsPlugin:()=>Mx,applyThemeVariables:()=>Wn,attachHeaderToContainer:()=>ca,brandPlugin:()=>Tx,buildComposer:()=>za,buildDefaultHeader:()=>mp,buildHeader:()=>ln,buildHeaderWithLayout:()=>$a,buildMinimalHeader:()=>gp,builtInClientToolsForDispatch:()=>As,collectEnrichedPageContext:()=>vx,componentRegistry:()=>dn,createActionManager:()=>js,createAgentExperience:()=>Rl,createAskUserQuestionBubble:()=>Wg,createBestAvailableVoiceProvider:()=>Fi,createBubbleWithLayout:()=>Lh,createCSATFeedback:()=>kl,createComboButton:()=>cl,createComponentMiddleware:()=>Zh,createComponentStreamParser:()=>Al,createDefaultSanitizer:()=>Ul,createDirectivePostprocessor:()=>mg,createDropdownMenu:()=>Fn,createFlexibleJsonStreamParser:()=>Fg,createIconButton:()=>yr,createImagePart:()=>$g,createJsonStreamParser:()=>Pi,createLabelButton:()=>_s,createLocalStorageAdapter:()=>Sl,createMarkdownProcessor:()=>ys,createMarkdownProcessorFromConfig:()=>Zn,createMessageActions:()=>wp,createNPSFeedback:()=>Ll,createPlainTextParser:()=>ki,createPlugin:()=>Lx,createRegexJsonParser:()=>Li,createStandardBubble:()=>ja,createTextPart:()=>Es,createTheme:()=>qa,createThemeObserver:()=>Zi,createToggleGroup:()=>Ch,createTypingIndicator:()=>pa,createVoiceProvider:()=>Rn,createWidgetHostLayout:()=>Gs,createXmlParser:()=>Ri,defaultActionHandlers:()=>fa,defaultJsonActionParser:()=>zs,defaultParseRules:()=>_p,detectColorScheme:()=>Is,directivePostprocessor:()=>gg,ensureAskUserQuestionSheet:()=>Da,escapeHtml:()=>qo,extractComponentDirectiveFromMessage:()=>El,fileToImagePart:()=>zg,formatEnrichedContext:()=>Cx,generateAssistantMessageId:()=>na,generateMessageId:()=>Og,generateStableSelector:()=>Up,generateUserMessageId:()=>Na,getActiveTheme:()=>Va,getColorScheme:()=>sp,getDisplayText:()=>Ug,getHeaderLayout:()=>hp,getImageParts:()=>Vg,getPreset:()=>Rx,hasComponentDirective:()=>Tl,hasImages:()=>qg,headerLayouts:()=>pl,highContrastPlugin:()=>kx,initAgentWidget:()=>dx,isAskUserQuestionMessage:()=>rn,isComponentDirectiveType:()=>Yh,isDockedMountMode:()=>pr,isSuggestRepliesMessage:()=>Ss,isVoiceSupported:()=>Ls,isWebMcpToolName:()=>ea,latestAgentSuggestions:()=>Si,listRegisteredStreamAnimations:()=>cp,markdownPostprocessor:()=>_l,mergeWithDefaults:()=>Qi,normalizeContent:()=>_g,parseAskUserQuestionPayload:()=>on,parseSuggestRepliesPayload:()=>Zl,pickBestVoice:()=>Oa,pluginRegistry:()=>$s,reducedMotionPlugin:()=>Ex,registerStreamAnimationPlugin:()=>da,removeAskUserQuestionSheet:()=>Ln,renderComponentDirective:()=>Ml,renderLoadingIndicatorWithFallback:()=>Cp,renderLucideIcon:()=>ve,resolveDockConfig:()=>no,resolveSanitizer:()=>Ia,resolveTokens:()=>Ji,stripWebMcpPrefix:()=>gi,themeToCssVariables:()=>Yi,unregisterStreamAnimationPlugin:()=>dp,validateImageFile:()=>jg,validateTheme:()=>ap});var Ol=null,xs=null,Pa=null,cg=e=>{Ol=e};var fi=()=>xs?Promise.resolve(xs):Pa||(Ol?(Pa=Ol().then(e=>(xs=e,e)),Pa):(Pa=import("./markdown-parsers-entry").then(e=>(xs=e,e)),Pa)),Ra=()=>xs;var ry=e=>{if(e)return e},ys=e=>{let t=null;return r=>{var n,a;let o=Ra();if(!o)return qo(r);if(!t){let{Marked:s}=o,i=e==null?void 0:e.markedOptions;t=new s({gfm:(n=i==null?void 0:i.gfm)!=null?n:!0,breaks:(a=i==null?void 0:i.breaks)!=null?a:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let c=ry(e==null?void 0:e.renderer);c&&t.use({renderer:c})}return t.parse(r)}},Zn=e=>e?ys({markedOptions:e.options,renderer:e.renderer}):ys(),oy=ys(),_l=e=>oy(e),qo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),ug=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),pg=e=>`%%FORM_PLACEHOLDER_${e}%%`,fg=(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=pg(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=pg(t.length);return t.push({token:a,type:n}),a}),r},mg=e=>{let t=Zn(e);return r=>{let o=[],n=fg(r,o),a=t(n);return o.forEach(({token:s,type:i})=>{let c=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${ug(i)}"></div>`;a=a.replace(c,u)}),a}},gg=e=>{let t=[],r=fg(e,t),o=_l(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="${ug(a)}"></div>`;o=o.replace(s,c)}),o};var ny={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},ay=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ul=()=>{let e=null;return t=>{let r=Ra();if(!r)return qo(t);if(!e){let{DOMPurify:o}=r;e=o(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(n,a)=>{if(a.attrName==="src"||a.attrName==="href"){let s=a.attrValue;s.toLowerCase().startsWith("data:")&&!ay.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,ny)}},Ia=e=>e===!1?null:typeof e=="function"?e:Ul();var tn="webmcp:",ql=new Map,hg=e=>{var t;ql.clear();for(let r of e){let o=(t=r.title)==null?void 0:t.trim();o&&ql.set(r.name,o)}},$l=e=>ql.get(gi(e)),mi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Vl=null,yg=e=>{Vl=e};function bg(e){if(e.length===0)return"0:empty";let t=e.map(r=>{var o,n;return[r.name,(o=r.description)!=null?o:"",r.parametersSchema?JSON.stringify(r.parametersSchema):"",(n=r.origin)!=null?n:"",r.annotations?JSON.stringify(r.annotations):""].join("")}).sort();return`${e.length}:${sy(t.join(""))}`}function xg(e,t){let r=3735928559^t,o=1103547991^t;for(let n=0;n<e.length;n++){let a=e.charCodeAt(n);r=Math.imul(r^a,2654435761),o=Math.imul(o^a,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&o)+(r>>>0)}function sy(e){let t=xg(e,0).toString(36),r=xg(e,2654435761).toString(36);return`${t}.${r}`}var Wa=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var r;this.confirmHandler=(r=t.onConfirm)!=null?r:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let r;try{r=await t.getTools()}catch(n){return mi.warn("getTools() threw: shipping an empty WebMCP snapshot.",n),[]}hg(r);let o=typeof location!="undefined"?location.origin:"";return r.filter(n=>this.passesClientAllowlist(n.name)).map(n=>{let a={name:n.name,description:n.description,origin:"webmcp",...o?{pageOrigin:o}:{}},s=ly(n.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,r,o){if(await this.ensureReady(),this.config.enabled!==!0)return Ao("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let x=typeof document!="undefined"&&!!document.modelContext;return Ao(x?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let a=gi(t),s;try{s=await n.getTools()}catch(x){let C=x instanceof Error?x.message:String(x);return Ao(`Failed to read WebMCP registry: ${C}`)}hg(s);let i=s.find(x=>x.name===a);if(!i)return Ao(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Ao(`WebMCP tool not allowed by client allowlist: ${a}`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let c=$l(a),d={toolName:a,args:r,description:i.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(d))return Ao("User declined the tool call.");if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let u=new AbortController,g=!1,p=setTimeout(()=>{g=!0,u.abort()},this.timeoutMs),m=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",m,{once:!0}));try{let x=await n.executeTool(i,uy(r),{signal:u.signal});return dy(x)}catch(x){if(g)return Ao(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let C=x instanceof Error?x.message:String(x);return Ao(C)}finally{clearTimeout(p),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Vl?await Vl():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){mi.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,mi.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let r=(o=this.confirmHandler)!=null?o:cy;try{return await r(t)}catch(n){return mi.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,n),!1}}passesClientAllowlist(t){let r=this.config.allowlist;return!r||r.length===0?!0:r.some(o=>iy(t,o))}},gi=e=>e.startsWith(tn)?e.slice(tn.length):e,ea=e=>e.startsWith(tn),iy=(e,t)=>{if(t==="*")return!0;let r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)},ly=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},dy=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:fy(t)}]}},Ao=e=>({isError:!0,content:[{type:"text",text:e}]}),cy=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=py(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var AgentWidget=(()=>{var Xx=Object.create;var fi=Object.defineProperty;var Qx=Object.getOwnPropertyDescriptor;var Jx=Object.getOwnPropertyNames;var Yx=Object.getPrototypeOf,Zx=Object.prototype.hasOwnProperty;var Ol=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,r)=>(typeof require!="undefined"?require:t)[r]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var dg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ey=(e,t)=>{for(var r in t)fi(e,r,{get:t[r],enumerable:!0})},cg=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Jx(t))!Zx.call(e,n)&&n!==r&&fi(e,n,{get:()=>t[n],enumerable:!(o=Qx(t,n))||o.enumerable});return e};var Pa=(e,t,r)=>(r=e!=null?Xx(Yx(e)):{},cg(t||!e||!e.__esModule?fi(r,"default",{value:e,enumerable:!0}):r,e)),ty=e=>cg(fi({},"__esModule",{value:!0}),e);var jl=dg(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.Allow=Fe.ALL=Fe.COLLECTION=Fe.ATOM=Fe.SPECIAL=Fe.INF=Fe._INFINITY=Fe.INFINITY=Fe.NAN=Fe.BOOL=Fe.NULL=Fe.OBJ=Fe.ARR=Fe.NUM=Fe.STR=void 0;Fe.STR=1;Fe.NUM=2;Fe.ARR=4;Fe.OBJ=8;Fe.NULL=16;Fe.BOOL=32;Fe.NAN=64;Fe.INFINITY=128;Fe._INFINITY=256;Fe.INF=Fe.INFINITY|Fe._INFINITY;Fe.SPECIAL=Fe.NULL|Fe.BOOL|Fe.INF|Fe.NAN;Fe.ATOM=Fe.STR|Fe.NUM|Fe.SPECIAL;Fe.COLLECTION=Fe.ARR|Fe.OBJ;Fe.ALL=Fe.ATOM|Fe.COLLECTION;Fe.Allow={STR:Fe.STR,NUM:Fe.NUM,ARR:Fe.ARR,OBJ:Fe.OBJ,NULL:Fe.NULL,BOOL:Fe.BOOL,NAN:Fe.NAN,INFINITY:Fe.INFINITY,_INFINITY:Fe._INFINITY,INF:Fe.INF,SPECIAL:Fe.SPECIAL,ATOM:Fe.ATOM,COLLECTION:Fe.COLLECTION,ALL:Fe.ALL};Fe.default=Fe.Allow});var bi=dg(Ar=>{"use strict";var my=Ar&&Ar.__createBinding||(Object.create?(function(e,t,r,o){o===void 0&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}):(function(e,t,r,o){o===void 0&&(o=r),e[o]=t[r]})),gy=Ar&&Ar.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&my(t,e,r)};Object.defineProperty(Ar,"__esModule",{value:!0});Ar.Allow=Ar.MalformedJSON=Ar.PartialJSON=Ar.parseJSON=Ar.parse=void 0;var Or=jl();Object.defineProperty(Ar,"Allow",{enumerable:!0,get:function(){return Or.Allow}});gy(jl(),Ar);var xi=class extends Error{};Ar.PartialJSON=xi;var yi=class extends Error{};Ar.MalformedJSON=yi;function Cg(e,t=Or.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return hy(e.trim(),t)}Ar.parseJSON=Cg;var hy=(e,t)=>{let r=e.length,o=0,n=p=>{throw new xi(`${p} at position ${o}`)},a=p=>{throw new yi(`${p} at position ${o}`)},s=()=>(g(),o>=r&&n("Unexpected end of input"),e[o]==='"'?i():e[o]==="{"?c():e[o]==="["?d():e.substring(o,o+4)==="null"||Or.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Or.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Or.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Or.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Or.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Or.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):u()),i=()=>{let p=o,m=!1;for(o++;o<r&&(e[o]!=='"'||m&&e[o-1]==="\\");)m=e[o]==="\\"?!m:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(p,++o-Number(m)))}catch(x){a(String(x))}else if(Or.Allow.STR&t)try{return JSON.parse(e.substring(p,o-Number(m))+'"')}catch{return JSON.parse(e.substring(p,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{o++,g();let p={};try{for(;e[o]!=="}";){if(g(),o>=r&&Or.Allow.OBJ&t)return p;let m=i();g(),o++;try{let x=s();p[m]=x}catch(x){if(Or.Allow.OBJ&t)return p;throw x}g(),e[o]===","&&o++}}catch{if(Or.Allow.OBJ&t)return p;n("Expected '}' at end of object")}return o++,p},d=()=>{o++;let p=[];try{for(;e[o]!=="]";)p.push(s()),g(),e[o]===","&&o++}catch{if(Or.Allow.ARR&t)return p;n("Expected ']' at end of array")}return o++,p},u=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Or.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let p=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==r&&!(Or.Allow.NUM&t)&&n("Unterminated number literal");try{return JSON.parse(e.substring(p,o))}catch{e.substring(p,o)==="-"&&n("Not sure what '-' is");try{return JSON.parse(e.substring(p,e.lastIndexOf("e")))}catch(x){a(String(x))}}},g=()=>{for(;o<r&&`
2
+ \r `.includes(e[o]);)o++};return s()},xy=Cg;Ar.parse=xy});var E0={};ey(E0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>rd,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>td,ASK_USER_QUESTION_TOOL_NAME:()=>ws,AgentWidgetClient:()=>na,AgentWidgetSession:()=>Ua,AttachmentManager:()=>la,BrowserSpeechEngine:()=>In,DEFAULT_COMPONENTS:()=>ap,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Qi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>oo,DEFAULT_PALETTE:()=>op,DEFAULT_SEMANTIC:()=>np,DEFAULT_WIDGET_CONFIG:()=>_t,PRESETS:()=>jp,PRESET_FULLSCREEN:()=>zp,PRESET_MINIMAL:()=>$p,PRESET_SHOP:()=>Vp,ReadAloudController:()=>ia,SUGGEST_REPLIES_CLIENT_TOOL:()=>Si,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Yl,SUGGEST_REPLIES_TOOL_NAME:()=>Mo,THEME_ZONES:()=>lh,VERSION:()=>oa,WEBMCP_TOOL_PREFIX:()=>tn,WebMcpBridge:()=>Ha,accessibilityPlugin:()=>Ax,animationsPlugin:()=>Mx,applyThemeVariables:()=>Wn,attachHeaderToContainer:()=>pa,brandPlugin:()=>Tx,buildComposer:()=>ja,buildDefaultHeader:()=>gp,buildHeader:()=>ln,buildHeaderWithLayout:()=>za,buildMinimalHeader:()=>hp,builtInClientToolsForDispatch:()=>Ms,collectEnrichedPageContext:()=>wx,componentRegistry:()=>dn,createActionManager:()=>Gs,createAgentExperience:()=>Il,createAskUserQuestionBubble:()=>Hg,createBestAvailableVoiceProvider:()=>Ni,createBubbleWithLayout:()=>Rh,createCSATFeedback:()=>Ll,createComboButton:()=>pl,createComponentMiddleware:()=>tx,createComponentStreamParser:()=>Ml,createDefaultSanitizer:()=>ql,createDirectivePostprocessor:()=>gg,createDropdownMenu:()=>Fn,createFlexibleJsonStreamParser:()=>Ng,createIconButton:()=>yr,createImagePart:()=>jg,createJsonStreamParser:()=>Ri,createLabelButton:()=>Us,createLocalStorageAdapter:()=>Al,createMarkdownProcessor:()=>bs,createMarkdownProcessorFromConfig:()=>Zn,createMessageActions:()=>Sp,createNPSFeedback:()=>Pl,createPlainTextParser:()=>Li,createPlugin:()=>Lx,createRegexJsonParser:()=>Pi,createStandardBubble:()=>Ga,createTextPart:()=>ks,createTheme:()=>Va,createThemeObserver:()=>el,createToggleGroup:()=>Sh,createTypingIndicator:()=>ua,createVoiceProvider:()=>Rn,createWidgetHostLayout:()=>Ks,createXmlParser:()=>Ii,defaultActionHandlers:()=>ma,defaultJsonActionParser:()=>js,defaultParseRules:()=>Up,detectColorScheme:()=>Ws,directivePostprocessor:()=>hg,ensureAskUserQuestionSheet:()=>Fa,escapeHtml:()=>qo,extractComponentDirectiveFromMessage:()=>kl,fileToImagePart:()=>Gg,formatEnrichedContext:()=>Sx,generateAssistantMessageId:()=>aa,generateMessageId:()=>Ug,generateStableSelector:()=>qp,generateUserMessageId:()=>Oa,getActiveTheme:()=>$a,getColorScheme:()=>ip,getDisplayText:()=>Vg,getHeaderLayout:()=>xp,getImageParts:()=>zg,getPreset:()=>Rx,hasComponentDirective:()=>El,hasImages:()=>$g,headerLayouts:()=>ul,highContrastPlugin:()=>kx,initAgentWidget:()=>px,isAskUserQuestionMessage:()=>rn,isComponentDirectiveType:()=>ex,isDockedMountMode:()=>pr,isSuggestRepliesMessage:()=>As,isVoiceSupported:()=>Ps,isWebMcpToolName:()=>ea,latestAgentSuggestions:()=>Ai,listRegisteredStreamAnimations:()=>pp,markdownPostprocessor:()=>Ul,mergeWithDefaults:()=>Ji,normalizeContent:()=>qg,parseAskUserQuestionPayload:()=>on,parseSuggestRepliesPayload:()=>ed,pickBestVoice:()=>_a,pluginRegistry:()=>zs,reducedMotionPlugin:()=>Ex,registerStreamAnimationPlugin:()=>ca,removeAskUserQuestionSheet:()=>Ln,renderComponentDirective:()=>Tl,renderLoadingIndicatorWithFallback:()=>wp,renderLucideIcon:()=>ve,resolveDockConfig:()=>no,resolveSanitizer:()=>Wa,resolveTokens:()=>Yi,stripWebMcpPrefix:()=>hi,themeToCssVariables:()=>Zi,unregisterStreamAnimationPlugin:()=>cp,validateImageFile:()=>Kg,validateTheme:()=>sp});var _l=null,ys=null,Ra=null,pg=e=>{_l=e};var mi=()=>ys?Promise.resolve(ys):Ra||(_l?(Ra=_l().then(e=>(ys=e,e)),Ra):(Ra=import("./markdown-parsers-entry").then(e=>(ys=e,e)),Ra)),Ia=()=>ys;var ry=e=>{if(e)return e},bs=e=>{let t=null;return r=>{var n,a;let o=Ia();if(!o)return qo(r);if(!t){let{Marked:s}=o,i=e==null?void 0:e.markedOptions;t=new s({gfm:(n=i==null?void 0:i.gfm)!=null?n:!0,breaks:(a=i==null?void 0:i.breaks)!=null?a:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let c=ry(e==null?void 0:e.renderer);c&&t.use({renderer:c})}return t.parse(r)}},Zn=e=>e?bs({markedOptions:e.options,renderer:e.renderer}):bs(),oy=bs(),Ul=e=>oy(e),qo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),fg=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),ug=e=>`%%FORM_PLACEHOLDER_${e}%%`,mg=(e,t)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,n)=>{try{let a=JSON.parse(n.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=ug(t.length);return t.push({token:s,type:String(a.type)}),s}}catch{return o}return o}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,n)=>{let a=ug(t.length);return t.push({token:a,type:n}),a}),r},gg=e=>{let t=Zn(e);return r=>{let o=[],n=mg(r,o),a=t(n);return o.forEach(({token:s,type:i})=>{let c=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${fg(i)}"></div>`;a=a.replace(c,u)}),a}},hg=e=>{let t=[],r=mg(e,t),o=Ul(r);return t.forEach(({token:n,type:a})=>{let s=new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${fg(a)}"></div>`;o=o.replace(s,c)}),o};var ny={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},ay=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ql=()=>{let e=null;return t=>{let r=Ia();if(!r)return qo(t);if(!e){let{DOMPurify:o}=r;e=o(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(n,a)=>{if(a.attrName==="src"||a.attrName==="href"){let s=a.attrValue;s.toLowerCase().startsWith("data:")&&!ay.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,ny)}},Wa=e=>e===!1?null:typeof e=="function"?e:ql();var tn="webmcp:",Vl=new Map,xg=e=>{var t;Vl.clear();for(let r of e){let o=(t=r.title)==null?void 0:t.trim();o&&Vl.set(r.name,o)}},zl=e=>Vl.get(hi(e)),gi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},$l=null,bg=e=>{$l=e};function vg(e){if(e.length===0)return"0:empty";let t=e.map(r=>{var o,n;return[r.name,(o=r.description)!=null?o:"",r.parametersSchema?JSON.stringify(r.parametersSchema):"",(n=r.origin)!=null?n:"",r.annotations?JSON.stringify(r.annotations):""].join("")}).sort();return`${e.length}:${sy(t.join(""))}`}function yg(e,t){let r=3735928559^t,o=1103547991^t;for(let n=0;n<e.length;n++){let a=e.charCodeAt(n);r=Math.imul(r^a,2654435761),o=Math.imul(o^a,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&o)+(r>>>0)}function sy(e){let t=yg(e,0).toString(36),r=yg(e,2654435761).toString(36);return`${t}.${r}`}var Ha=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var r;this.confirmHandler=(r=t.onConfirm)!=null?r:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let r;try{r=await t.getTools()}catch(n){return gi.warn("getTools() threw: shipping an empty WebMCP snapshot.",n),[]}xg(r);let o=typeof location!="undefined"?location.origin:"";return r.filter(n=>this.passesClientAllowlist(n.name)).map(n=>{let a={name:n.name,description:n.description,origin:"webmcp",...o?{pageOrigin:o}:{}},s=ly(n.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,r,o){if(await this.ensureReady(),this.config.enabled!==!0)return Ao("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let x=typeof document!="undefined"&&!!document.modelContext;return Ao(x?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let a=hi(t),s;try{s=await n.getTools()}catch(x){let C=x instanceof Error?x.message:String(x);return Ao(`Failed to read WebMCP registry: ${C}`)}xg(s);let i=s.find(x=>x.name===a);if(!i)return Ao(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Ao(`WebMCP tool not allowed by client allowlist: ${a}`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let c=zl(a),d={toolName:a,args:r,description:i.description,...c?{title:c}:{},reason:"gate"};if(!await this.requestConfirm(d))return Ao("User declined the tool call.");if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let u=new AbortController,g=!1,p=setTimeout(()=>{g=!0,u.abort()},this.timeoutMs),m=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",m,{once:!0}));try{let x=await n.executeTool(i,uy(r),{signal:u.signal});return dy(x)}catch(x){if(g)return Ao(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let C=x instanceof Error?x.message:String(x);return Ao(C)}finally{clearTimeout(p),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}($l?await $l():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){gi.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let r=t;return typeof r.getTools!="function"||typeof r.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,gi.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let r=(o=this.confirmHandler)!=null?o:cy;try{return await r(t)}catch(n){return gi.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,n),!1}}passesClientAllowlist(t){let r=this.config.allowlist;return!r||r.length===0?!0:r.some(o=>iy(t,o))}},hi=e=>e.startsWith(tn)?e.slice(tn.length):e,ea=e=>e.startsWith(tn),iy=(e,t)=>{if(t==="*")return!0;let r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)},ly=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},dy=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:fy(t)}]}},Ao=e=>({isError:!0,content:[{type:"text",text:e}]}),cy=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=py(e.args),r=`Allow the AI to call ${e.toolName}`+(t?`
3
3
 
4
4
  Arguments:
5
5
  ${t}`:"")+(e.description?`
6
6
 
7
- ${e.description}`:"");return window.confirm(r)},py=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},uy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},fy=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var En=La(yi(),1);var S=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},Vo=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var kt=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let i of Object.keys(s)){let c=s[i];c!=null&&(a[i]=c)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},bs=(...e)=>e.filter(Boolean).join(" ");var Cs="ask_user_question",vs=8,Ha="data-persona-ask-sheet-for",yy="Other",by="Other\u2026",wg="Type your own answer here",Sg="Send",vy="Next",Cy="Back",wy="Submit all",Sy="Skip",Ay=3,jl="data-ask-current-index",Gl="data-ask-question-count",Ag="data-ask-answers",Kl="data-ask-grouped",Mg="data-ask-layout",My=e=>e.layout==="pills"?"pills":"rows",Ty=e=>e.getAttribute(Mg)==="pills"?"pills":"rows",Cg=!1,Tg=e=>e.replace(/["\\]/g,"\\$&"),rn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Cs,bi=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},on=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:r};try{let n=o.join(""),a=(0,En.parse)(n,En.STR|En.OBJ|En.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},ws=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>vs&&!Cg&&(Cg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${vs}.`)),t.slice(0,vs)},Ey=e=>{var t;return(t=ws(e)[0])!=null?t:null},ky=(e,t)=>{var r;return(r=ws(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=S("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=S("span","persona-ask-row-check");o.appendChild(n)}else{let n=S("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Ly=(e,t,r,o)=>{let a=S("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),r==="rows"){let s=S("span","persona-ask-row-content"),i=S("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let d=S("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let c=kg(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Py=e=>{let r=S("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return r.setAttribute("aria-hidden","true"),r},Ry=(e,t,r,o)=>{var u,g,p;let a=S("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),c=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(c.length===0&&!r){for(let m=0;m<Ay;m++)a.appendChild(Py(o));return a}if(c.forEach((m,x)=>{a.appendChild(Ly(m,x,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?yy:by;if(o==="rows"){let x=S("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(c.length)),x.setAttribute("data-ask-other-row","true");let C=S("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=t.freeTextPlaceholder)!=null?u:wg,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),C.appendChild(T),x.appendChild(C);let E=kg(o,s,c.length);E&&x.appendChild(E),a.appendChild(x)}else{let x=S("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(p=t.freeTextLabel)!=null?p:m,a.appendChild(x)}}return a},Lg=(e,t)=>{var a,s;let o=S("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=e.freeTextPlaceholder)!=null?a:wg,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=S("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Sg,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Iy=e=>{var o;let t=S("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=S("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:Sg,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Wy=(e,t,r)=>{var d,u,g,p;let o=S("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=S("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(d=r.backLabel)!=null?d:Cy,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=S("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=S("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=r.skipLabel)!=null?u:Sy,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=S("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(g=r.submitAllLabel)!=null?g:wy:(p=r.nextLabel)!=null?p:vy,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},ta=e=>{let t=e.getAttribute(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))},ho=e=>{var r;let t=Number((r=e.getAttribute(jl))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Hy=(e,t)=>{e.setAttribute(jl,String(Math.max(0,Math.floor(t))))},Ba=e=>{var r;let t=Number((r=e.getAttribute(Gl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},kn=e=>e.getAttribute(Kl)==="true",By=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let o={};return t.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let c=r[i];(typeof c=="string"||Array.isArray(c))&&(o[s]=c)}}),o},Dy=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},vi=(e,t)=>{let{payload:r}=on(t),o=ws(r),n=ta(e),a={},s=new Set;return o.forEach((i,c)=>{let d=typeof(i==null?void 0:i.question)=="string"?i.question:"";d&&(s.has(d)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(n,c)&&(a[d]=n[c]))}),a},Rg=e=>{let t=ta(e),r=ho(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var g;let d=(g=c.getAttribute("data-option-label"))!=null?g:"",u=n.has(d);c.setAttribute("aria-pressed",u?"true":"false"),c.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(a).map(c=>{var d;return(d=c.getAttribute("data-option-label"))!=null?d:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},Ig=e=>{if(!kn(e))return;let t=ta(e),r=ho(e),o=t[r],n=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Xl=(e,t,r)=>{let o=bi(r),n=Ty(e),{payload:a,complete:s}=on(t),i=kn(e),c=ho(e),d=Ba(e),u=i?ky(a,c):Ey(a),g=!!(u!=null&&u.multiSelect),p=e.querySelector('[data-ask-step-inline="true"]');p&&(p.textContent=i?`${c+1}/${d}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let M=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=M,x.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let M=Ry(u,o,s,n);C.replaceWith(M)}if(n!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(Lg(o,n))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!T?e.appendChild(Iy(o)):(!g||i)&&T&&T.remove(),e.setAttribute("data-multi-select",g?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let M=Wy(c,d,o);E?E.replaceWith(M):e.appendChild(M)}else E&&E.remove();Rg(e),Ig(e)},Fy=(e,t,r)=>{let o=bi(t),n=My(o),a=e.toolCall.id,s=ws(r),i=Math.max(1,s.length),c=i>1,d=By(e,s),u=c?Dy(e,i):0,g=S("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Ha,a),g.setAttribute("data-tool-call-id",a),g.setAttribute("data-message-id",e.id),g.setAttribute(Gl,String(i)),g.setAttribute(jl,String(u)),g.setAttribute(Kl,c?"true":"false"),g.setAttribute(Mg,n),Pg(g,d),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Eg(g,o);let p=S("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=S("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",p.appendChild(m);let x=S("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",p.appendChild(x),g.appendChild(p);let T=S("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),n!=="rows"&&g.appendChild(Lg(o,n)),Xl(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Ny=(e,t,r)=>{let{payload:o}=on(t),n=Math.max(1,ws(o).length);n>Ba(e)&&(e.setAttribute(Gl,String(n)),n>1&&!kn(e)&&e.setAttribute(Kl,"true")),Xl(e,t,r)},Wg=(e,t)=>{let r=S("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let o=bi(t);Eg(r,o);let n=S("span","persona-ask-stub-label"),{complete:a}=on(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Da=(e,t,r)=>{if(!r||!rn(e)||bi(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Ha}]`).forEach(d=>{d.getAttribute(Ha)!==n&&d.remove()});let s=r.querySelector(`[${Ha}="${Tg(n)}"]`);if(s){Ny(s,e,t);return}let{payload:i}=on(e),c=Fy(e,t,i);r.appendChild(c)},Ln=(e,t)=>{if(!e)return;let r=t?`[${Ha}="${Tg(t)}"]`:`[${Ha}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Ql=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Pn=(e,t)=>{let r=ta(e),o=ho(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,Pg(e,r),Rg(e),Ig(e)},Ci=(e,t,r,o)=>{let n=Ba(e),a=Math.max(0,Math.min(n-1,o));Hy(e,a),Xl(e,t,r)};var Mo="suggest_replies";var Jl={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},wi={name:Mo,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Jl,origin:"sdk",annotations:{readOnlyHint:!0}},Yl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ss=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Mo},Zl=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},Si=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!Ss(o))continue;let n=Zl((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 ed={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:vs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},td={name:Cs,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:ed,origin:"sdk",annotations:{readOnlyHint:!0}},As=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(td),Hg(e)&&t.push(wi),t};var nn=La(yi(),1),Ai=e=>e.replace(/\\n/g,`
8
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Fa=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Oy=e=>{var s,i;let t=(s=e.completedAt)!=null?s:Date.now(),r=(i=e.startedAt)!=null?i:t,n=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-r))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},Bg=e=>e.status==="complete"?Oy(e):e.status==="pending"?"Waiting":"",_y=e=>{var n,a,s;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(a=e.startedAt)!=null?a:e.completedAt)!=null?s:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Dg=e=>e.status==="complete"?_y(e):"Using tool...",Mi=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ts=e=>{var r,o,n;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return Mi(t)},Ti=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 Mi(t)},rd=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=Ts(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},Ei=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&Ms(o,r.slice(a,s.index),[]),s[1]!==void 0?Ms(o,s[1],["bold"]):s[2]!==void 0?Ms(o,s[2],["italic"]):s[3]!==void 0&&Ms(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&Ms(o,r.slice(a),[]),o},Ms=(e,t,r)=>{let o=t.split("{duration}");for(let n=0;n<o.length;n++)o[n]&&e.push({text:o[n],styles:r}),n<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},Uy=()=>{let e=null,t=0,r=o=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(n);if(a&&a[1])try{return a[1].replace(/\\n/g,`
7
+ ${e.description}`:"");return window.confirm(r)},py=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},uy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},fy=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var En=Pa(bi(),1);var S=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},Vo=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var kt=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let i of Object.keys(s)){let c=s[i];c!=null&&(a[i]=c)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},vs=(...e)=>e.filter(Boolean).join(" ");var ws="ask_user_question",Cs=8,Ba="data-persona-ask-sheet-for",yy="Other",by="Other\u2026",Sg="Type your own answer here",Ag="Send",vy="Next",Cy="Back",wy="Submit all",Sy="Skip",Ay=3,Gl="data-ask-current-index",Kl="data-ask-question-count",Mg="data-ask-answers",Xl="data-ask-grouped",Tg="data-ask-layout",My=e=>e.layout==="pills"?"pills":"rows",Ty=e=>e.getAttribute(Tg)==="pills"?"pills":"rows",wg=!1,Eg=e=>e.replace(/["\\]/g,"\\$&"),rn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ws,vi=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},on=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:r};try{let n=o.join(""),a=(0,En.parse)(n,En.STR|En.OBJ|En.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},Ss=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Cs&&!wg&&(wg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cs}.`)),t.slice(0,Cs)},Ey=e=>{var t;return(t=Ss(e)[0])!=null?t:null},ky=(e,t)=>{var r;return(r=Ss(e)[t])!=null?r:null},kg=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},Lg=(e,t,r)=>{if(e!=="rows")return null;let o=S("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=S("span","persona-ask-row-check");o.appendChild(n)}else{let n=S("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Ly=(e,t,r,o)=>{let a=S("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),r==="rows"){let s=S("span","persona-ask-row-content"),i=S("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let d=S("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let c=Lg(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Py=e=>{let r=S("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return r.setAttribute("aria-hidden","true"),r},Ry=(e,t,r,o)=>{var u,g,p;let a=S("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),c=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(c.length===0&&!r){for(let m=0;m<Ay;m++)a.appendChild(Py(o));return a}if(c.forEach((m,x)=>{a.appendChild(Ly(m,x,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?yy:by;if(o==="rows"){let x=S("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(c.length)),x.setAttribute("data-ask-other-row","true");let C=S("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=t.freeTextPlaceholder)!=null?u:Sg,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),C.appendChild(T),x.appendChild(C);let E=Lg(o,s,c.length);E&&x.appendChild(E),a.appendChild(x)}else{let x=S("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(p=t.freeTextLabel)!=null?p:m,a.appendChild(x)}}return a},Pg=(e,t)=>{var a,s;let o=S("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=e.freeTextPlaceholder)!=null?a:Sg,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=S("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Ag,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Iy=e=>{var o;let t=S("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=S("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:Ag,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Wy=(e,t,r)=>{var d,u,g,p;let o=S("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=S("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(d=r.backLabel)!=null?d:Cy,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=S("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=S("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=r.skipLabel)!=null?u:Sy,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=S("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(g=r.submitAllLabel)!=null?g:wy:(p=r.nextLabel)!=null?p:vy,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},ta=e=>{let t=e.getAttribute(Mg);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Rg=(e,t)=>{e.setAttribute(Mg,JSON.stringify(t))},ho=e=>{var r;let t=Number((r=e.getAttribute(Gl))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Hy=(e,t)=>{e.setAttribute(Gl,String(Math.max(0,Math.floor(t))))},Da=e=>{var r;let t=Number((r=e.getAttribute(Kl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},kn=e=>e.getAttribute(Xl)==="true",By=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let o={};return t.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let c=r[i];(typeof c=="string"||Array.isArray(c))&&(o[s]=c)}}),o},Dy=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},Ci=(e,t)=>{let{payload:r}=on(t),o=Ss(r),n=ta(e),a={},s=new Set;return o.forEach((i,c)=>{let d=typeof(i==null?void 0:i.question)=="string"?i.question:"";d&&(s.has(d)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(n,c)&&(a[d]=n[c]))}),a},Ig=e=>{let t=ta(e),r=ho(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var g;let d=(g=c.getAttribute("data-option-label"))!=null?g:"",u=n.has(d);c.setAttribute("aria-pressed",u?"true":"false"),c.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(a).map(c=>{var d;return(d=c.getAttribute("data-option-label"))!=null?d:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},Wg=e=>{if(!kn(e))return;let t=ta(e),r=ho(e),o=t[r],n=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Ql=(e,t,r)=>{let o=vi(r),n=Ty(e),{payload:a,complete:s}=on(t),i=kn(e),c=ho(e),d=Da(e),u=i?ky(a,c):Ey(a),g=!!(u!=null&&u.multiSelect),p=e.querySelector('[data-ask-step-inline="true"]');p&&(p.textContent=i?`${c+1}/${d}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let M=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=M,x.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let M=Ry(u,o,s,n);C.replaceWith(M)}if(n!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(Pg(o,n))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!T?e.appendChild(Iy(o)):(!g||i)&&T&&T.remove(),e.setAttribute("data-multi-select",g?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let M=Wy(c,d,o);E?E.replaceWith(M):e.appendChild(M)}else E&&E.remove();Ig(e),Wg(e)},Fy=(e,t,r)=>{let o=vi(t),n=My(o),a=e.toolCall.id,s=Ss(r),i=Math.max(1,s.length),c=i>1,d=By(e,s),u=c?Dy(e,i):0,g=S("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Ba,a),g.setAttribute("data-tool-call-id",a),g.setAttribute("data-message-id",e.id),g.setAttribute(Kl,String(i)),g.setAttribute(Gl,String(u)),g.setAttribute(Xl,c?"true":"false"),g.setAttribute(Tg,n),Rg(g,d),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),kg(g,o);let p=S("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=S("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",p.appendChild(m);let x=S("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",p.appendChild(x),g.appendChild(p);let T=S("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),n!=="rows"&&g.appendChild(Pg(o,n)),Ql(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Ny=(e,t,r)=>{let{payload:o}=on(t),n=Math.max(1,Ss(o).length);n>Da(e)&&(e.setAttribute(Kl,String(n)),n>1&&!kn(e)&&e.setAttribute(Xl,"true")),Ql(e,t,r)},Hg=(e,t)=>{let r=S("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let o=vi(t);kg(r,o);let n=S("span","persona-ask-stub-label"),{complete:a}=on(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Fa=(e,t,r)=>{if(!r||!rn(e)||vi(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Ba}]`).forEach(d=>{d.getAttribute(Ba)!==n&&d.remove()});let s=r.querySelector(`[${Ba}="${Eg(n)}"]`);if(s){Ny(s,e,t);return}let{payload:i}=on(e),c=Fy(e,t,i);r.appendChild(c)},Ln=(e,t)=>{if(!e)return;let r=t?`[${Ba}="${Eg(t)}"]`:`[${Ba}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Jl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Pn=(e,t)=>{let r=ta(e),o=ho(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,Rg(e,r),Ig(e),Wg(e)},wi=(e,t,r,o)=>{let n=Da(e),a=Math.max(0,Math.min(n-1,o));Hy(e,a),Ql(e,t,r)};var Mo="suggest_replies";var Yl={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Si={name:Mo,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Yl,origin:"sdk",annotations:{readOnlyHint:!0}},Zl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),As=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Mo},ed=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let r=t==null?void 0:t.suggestions;if(!Array.isArray(r))return[];let o=r.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Ai=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!As(o))continue;let n=ed((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},Bg=e=>{var r;let t=(r=e==null?void 0:e.features)==null?void 0:r.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var td={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Cs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},rd={name:ws,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:td,origin:"sdk",annotations:{readOnlyHint:!0}},Ms=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(rd),Bg(e)&&t.push(Si),t};var nn=Pa(bi(),1),Mi=e=>e.replace(/\\n/g,`
8
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Na=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Oy=e=>{var s,i;let t=(s=e.completedAt)!=null?s:Date.now(),r=(i=e.startedAt)!=null?i:t,n=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-r))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},Dg=e=>e.status==="complete"?Oy(e):e.status==="pending"?"Waiting":"",_y=e=>{var n,a,s;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(a=e.startedAt)!=null?a:e.completedAt)!=null?s:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Fg=e=>e.status==="complete"?_y(e):"Using tool...",Ti=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Es=e=>{var r,o,n;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return Ti(t)},Ei=e=>{var r,o,n;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return Ti(t)},od=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=Es(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},ki=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&Ts(o,r.slice(a,s.index),[]),s[1]!==void 0?Ts(o,s[1],["bold"]):s[2]!==void 0?Ts(o,s[2],["italic"]):s[3]!==void 0&&Ts(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&Ts(o,r.slice(a),[]),o},Ts=(e,t,r)=>{let o=t.split("{duration}");for(let n=0;n<o.length;n++)o[n]&&e.push({text:o[n],styles:r}),n<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},Uy=()=>{let e=null,t=0,r=o=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(n);if(a&&a[1])try{return a[1].replace(/\\n/g,`
9
9
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
10
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ra=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ki=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Li=()=>{var t;let e=Uy();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Pi=()=>{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"?Ai(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=Ai(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"?Ai(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Ai(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:()=>{}}},Ri=()=>{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 Ii=class{constructor(t,r=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=r}push(t,r){var a,s,i;let o=(i=(a=r==null?void 0:r.seq)!=null?a:r==null?void 0:r.sequenceIndex)!=null?i:(s=r==null?void 0:r.agentContext)==null?void 0:s.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,r);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,r),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,r);return}let n=this.buffer.get(o);n!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${n.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(n.payloadType,n.payload)),this.buffer.set(o,{payloadType:t,payload:r,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((r,o)=>r[0]-o[0]);for(let[r,o]of t)this.buffer.delete(r),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var qy="https://api.runtype.com/v1/dispatch",Wi="https://api.runtype.com";function Vy(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 od=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function $y(e){switch(e){case"json":return Pi;case"regex-json":return Li;case"xml":return Ri;default:return ki}}var Ng=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function zy(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=Ng(r);if(!Ng(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ra(e);return ra(t)!==null&&s===null?t:e}var oa=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;this.apiUrl=(r=t.apiUrl)!=null?r:qy,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:$y(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Wa(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Wi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let t=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let n=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(n.sessionId),{sessionId:n.sessionId,expiresAt:new Date(n.expiresAt),flow:n.flow,config:{welcomeMessage:n.config.welcomeMessage,placeholder:n.config.placeholder,theme:n.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Wi}/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"},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let d=await this.buildPayload(t.messages),u=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,g={sessionId:c.sessionId,messages:t.messages.filter(od).map(y=>{var w,b,A;return{id:y.id,role:y.role,content:(A=(b=(w=y.contentParts)!=null?w:y.llmContent)!=null?b:y.rawContent)!=null?A:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},p=d.clientTools,m=!!(p&&p.length>0),x=m?bg(p):void 0,C=this.clientToolsFingerprintSessionId===c.sessionId,T=m&&C&&this.lastSentClientToolsFingerprint===x,E=!1,M=null,P;for(let y=0;;y++){let b={...g,...m&&(E||!T)&&p?{clientTools:p}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",b),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b),signal:o.signal}),P.status===409&&y===0&&m){let A=await P.json().catch(()=>null);if((A==null?void 0:A.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}M=A!=null?A:{error:"Chat request failed"}}break}if(!P.ok){let y=M!=null?M:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let b=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:b}),b}if(P.status===429){let b=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:b}),b}let w=new Error(y.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!P.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(P.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let d=c instanceof Error?c:new Error(String(c));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&r({type:"error",error:d}),d}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Wi}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var d,u;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((d=this.config.apiUrl)==null?void 0:d.replace(/\/+$/,""))||Wi}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var a,s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(od).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,c)=>{let d=new Date(i.createdAt).getTime(),u=new Date(c.createdAt).getTime();return d-u}).map(i=>{var c,d,u;return{role:i.role,content:(u=(d=(c=i.contentParts)!=null?c:i.llmContent)!=null?d:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),o={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},n=[...As(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async c=>{try{let d=await c({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(i,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(i).length&&(o.context=i)}return o}async buildPayload(t){var a,s;let o={messages:t.slice().filter(od).sort((i,c)=>{let d=new Date(i.createdAt).getTime(),u=new Date(c.createdAt).getTime();return d-u}).map(i=>{var c,d,u;return{role:i.role,content:(u=(d=(c=i.contentParts)!=null?c:i.llmContent)!=null?d:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},n=[...As(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async c=>{try{let d=await c({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(i,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(i).length&&(o.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...o},config:this.config});if(i&&typeof i=="object"){let c=i;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return o}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...u!==void 0&&{partId:u}};return o.current=g,n(g),g},d=u=>o.current?o.current:c(u);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let u=d(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,n(u)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var Cr,Wt,ur,Eo;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,d=()=>i+c++,u=V=>{let j=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,he=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,Xe=V.tools?V.tools.map(et=>({...et,chunks:et.chunks?[...et.chunks]:void 0})):void 0;return{...V,reasoning:j,toolCall:he,tools:Xe}},g=V=>{if(V.role!=="assistant"||V.variant)return!0;let j=Array.isArray(V.contentParts)&&V.contentParts.length>0,he=typeof V.rawContent=="string"&&V.rawContent.trim()!=="";return typeof V.content=="string"&&V.content.trim()!==""||j||he||!!V.stopReason},p=V=>{g(V)&&r({type:"message",message:u(V)})},m=null,x=null,C={current:null},T={current:null},E=!1,M=new Map,P=new Map,y=new Map,w=new Map,b={lastId:null,byStep:new Map},A={lastId:null,byCall:new Map},H=(V,j,he="")=>`${V}::${j}::${he}`,W=(V,j)=>`${V}::${j}::`,k=(V,j,he,Xe)=>{let et=H(V,j,he),qe=y.get(et);if(qe)return qe;let Ne=he?`-${he}`:"",Pt={id:`nested-${V}-${j}${Ne}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...he?{partId:he}:{},agentMetadata:{executionId:Xe,parentToolId:V,parentStepId:j}};return y.set(et,Pt),p(Pt),Pt},N=V=>{if(V==null)return null;try{return String(V)}catch{return null}},q=V=>{var j,he,Xe,et,qe;return N((qe=(et=(Xe=(he=(j=V.stepId)!=null?j:V.step_id)!=null?he:V.step)!=null?Xe:V.parentId)!=null?et:V.flowStepId)!=null?qe:V.flow_step_id)},Z=V=>{var j,he,Xe,et,qe,Ne,Pt;return N((Pt=(Ne=(qe=(et=(Xe=(he=(j=V.callId)!=null?j:V.call_id)!=null?he:V.requestId)!=null?Xe:V.request_id)!=null?et:V.toolCallId)!=null?qe:V.tool_call_id)!=null?Ne:V.stepId)!=null?Pt:V.step_id)},me=o,Ke=!1,Ce=()=>{if(m)return m;let V;return!Ke&&me?(V=me,Ke=!0):me&&T.current?V=`${me}_${T.current}`:V=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:V,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d()},p(m),m},Ie=(V,j)=>{b.lastId=j,V&&b.byStep.set(V,j)},Ue=(V,j)=>{var qe;let he=(qe=V.reasoningId)!=null?qe:V.id,Xe=q(V);if(he){let Ne=String(he);return Ie(Xe,Ne),Ne}if(Xe){let Ne=b.byStep.get(Xe);if(Ne)return b.lastId=Ne,Ne}if(b.lastId&&!j)return b.lastId;if(!j)return null;let et=`reason-${d()}`;return Ie(Xe,et),et},Te=V=>{let j=M.get(V);if(j)return j;let he={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:V,status:"streaming",chunks:[]}};return M.set(V,he),p(he),he},We=(V,j)=>{A.lastId=j,V&&A.byCall.set(V,j)},de=new Set,J=new Map,le=new Set,ge=new Map,ue=V=>{if(!V)return!1;let j=V.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},G=(V,j)=>{var qe;let he=(qe=V.toolId)!=null?qe:V.id,Xe=Z(V);if(he){let Ne=String(he);return We(Xe,Ne),Ne}if(Xe){let Ne=A.byCall.get(Xe);if(Ne)return A.lastId=Ne,Ne}if(A.lastId&&!j)return A.lastId;if(!j)return null;let et=`tool-${d()}`;return We(Xe,et),et},ce=V=>{let j=P.get(V);if(j)return j;let he={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:V,status:"pending"}};return P.set(V,he),p(he),he},Be=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let j=Number(V);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let he=Date.parse(V);if(!Number.isNaN(he))return he}return Date.now()},ne=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},ee=new Map,ie=new Map,vt=new Map,Lt=new Map,gt=null,_e=(V,j,he)=>{var Pt;let Xe=vt.get(V);Xe||(Xe=[],vt.set(V,Xe));let et=0,qe=Xe.length;for(;et<qe;){let Gt=et+qe>>>1;Xe[Gt].seq<j?et=Gt+1:qe=Gt}((Pt=Xe[et])==null?void 0:Pt.seq)===j?Xe[et]={seq:j,text:he}:Xe.splice(et,0,{seq:j,text:he});let Ne="";for(let Gt=0;Gt<Xe.length;Gt++)Ne+=Xe[Gt].text;return Ne},be=(V,j)=>{let he=ne(j),Xe=ie.get(V.id),et=zy(Xe,he);V.rawContent=et;let qe=ee.get(V.id),Ne=z=>{var oe;let Ht=(oe=V.content)!=null?oe:"";z.trim()!==""&&(Ht.trim().length===0||z.startsWith(Ht)||z.trimStart().startsWith(Ht.trim()))&&(V.content=z)},Pt=()=>{var z;if(qe){let Ht=(z=qe.close)==null?void 0:z.call(qe);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(V.id),ie.delete(V.id),V.streaming=!1,p(V)};if(!qe){Ne(he),Pt();return}let Gt=ra(et);if(Gt!==null&&Gt.trim()!==""){Ne(Gt),Pt();return}let Jt=z=>{var we;let Ht=typeof z=="string"?z:(we=z==null?void 0:z.text)!=null?we:null;if(Ht!==null&&Ht.trim()!=="")return Ht;let oe=qe.getExtractedText();return oe!==null&&oe.trim()!==""?oe:he},Pr;try{Pr=qe.processChunk(et)}catch{Ne(he),Pt();return}if(Pr instanceof Promise){Pr.then(z=>{Ne(Jt(z)),Pt()}).catch(()=>{Ne(he),Pt()});return}Ne(Jt(Pr)),Pt()},Ze=[],Y=!1,pe,Me=()=>{Y||(Y=!0,queueMicrotask(()=>{Y=!1,pe()}))},Je=new Ii((V,j)=>{Ze.push({payloadType:V,payload:j}),Me()}),Ge=null,ke=new Map,je=(Cr=this.config.iterationDisplay)!=null?Cr:"separate";for(pe=()=>{var V,j,he,Xe,et,qe,Ne,Pt,Gt,Jt,Pr,z,Ht,oe,we,De,At,ar,sr,wr,Ft,ot,Dt,lt,Yt,so,Rr,ir,Ur,ko,yt,jr,Lo,zo,yo,ht,Nn,Po,On,qr,ma,cn,jo,pn,un,_n,Un,fn,Ct,Gr,Kr,Ir,Mt,io,lo,Xr,mn,Go,gn,Qr,Nt,Wr,co,hn,Ko,xn,Ro,Jr,xe,dt,tr,fr,Io,Za,Xo,qn,Wo,_,ga,Ho,Bo,Qo,Do,bo,ha,Xs,Yr,Zr,vo,Co,Vn,Jo,Mr,Fo,xa,$n,ya,Qs,ba,Js,va,mt,es,po,Vr,Ys,Zs,Ca,Yo,ts,yn,rs,os,ns,as,$r,wa,No,Oo,ss,ei,is,ls,zn,ti,ri,oi,ni,ai,bn,vn,si,ds,Cn,ii,cs,wn,ps;for(let Sa=0;Sa<Ze.length;Sa++){let Ve=Ze[Sa].payloadType,L=Ze[Sa].payload;if(Ve==="reason_start"){let U=(V=Ue(L,!0))!=null?V:`reason-${d()}`,I=Te(U);I.reasoning=(j=I.reasoning)!=null?j:{id:U,status:"streaming",chunks:[]},I.reasoning.startedAt=(Xe=I.reasoning.startedAt)!=null?Xe:Be((he=L.startedAt)!=null?he:L.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let U=(qe=(et=Ue(L,!1))!=null?et:Ue(L,!0))!=null?qe:`reason-${d()}`,I=Te(U);I.reasoning=(Ne=I.reasoning)!=null?Ne:{id:U,status:"streaming",chunks:[]},I.reasoning.startedAt=(Gt=I.reasoning.startedAt)!=null?Gt:Be((Pt=L.startedAt)!=null?Pt:L.timestamp);let X=(z=(Pr=(Jt=L.reasoningText)!=null?Jt:L.text)!=null?Pr:L.delta)!=null?z:"";if(X&&L.hidden!==!0){let re=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(re!==void 0){let K=_e(U,re,String(X));I.reasoning.chunks=[K]}else I.reasoning.chunks.push(String(X))}if(I.reasoning.status=L.done?"complete":"streaming",L.done){I.reasoning.completedAt=Be((Ht=L.completedAt)!=null?Ht:L.timestamp);let re=(oe=I.reasoning.startedAt)!=null?oe:Date.now();I.reasoning.durationMs=Math.max(0,((we=I.reasoning.completedAt)!=null?we:Date.now())-re)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(Ve==="reason_complete"){let U=(At=(De=Ue(L,!1))!=null?De:Ue(L,!0))!=null?At:`reason-${d()}`,I=M.get(U);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=Be((ar=L.completedAt)!=null?ar:L.timestamp);let re=(sr=I.reasoning.startedAt)!=null?sr:Date.now();I.reasoning.durationMs=Math.max(0,((wr=I.reasoning.completedAt)!=null?wr:Date.now())-re),I.streaming=!1,p(I)}let X=q(L);X&&b.byStep.delete(X)}else if(Ve==="tool_start"){let U=(Ft=G(L,!0))!=null?Ft:`tool-${d()}`,I=(ot=L.toolName)!=null?ot:L.name;if(ue(I)){de.add(U);continue}let X=ce(U),re=(Dt=X.toolCall)!=null?Dt:{id:U,status:"pending"};re.name=I!=null?I:re.name,re.status="running",L.args!==void 0?re.args=L.args:L.parameters!==void 0&&(re.args=L.parameters),re.startedAt=(Yt=re.startedAt)!=null?Yt:Be((lt=L.startedAt)!=null?lt:L.timestamp),re.completedAt=void 0,re.durationMs=void 0,X.toolCall=re,X.streaming=!0;let K=L.agentContext;(K||L.executionId)&&(X.agentMetadata={executionId:(so=K==null?void 0:K.executionId)!=null?so:L.executionId,iteration:(Rr=K==null?void 0:K.iteration)!=null?Rr:L.iteration}),p(X)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let U=(Ur=(ir=G(L,!1))!=null?ir:G(L,!0))!=null?Ur:`tool-${d()}`;if(de.has(U))continue;let I=ce(U),X=(ko=I.toolCall)!=null?ko:{id:U,status:"running"};X.startedAt=(jr=X.startedAt)!=null?jr:Be((yt=L.startedAt)!=null?yt:L.timestamp);let re=(yo=(zo=(Lo=L.text)!=null?Lo:L.delta)!=null?zo:L.message)!=null?yo:"";re&&(X.chunks=(ht=X.chunks)!=null?ht:[],X.chunks.push(String(re))),X.status="running",I.toolCall=X,I.streaming=!0;let K=L.agentContext;(K||L.executionId)&&(I.agentMetadata=(On=I.agentMetadata)!=null?On:{executionId:(Nn=K==null?void 0:K.executionId)!=null?Nn:L.executionId,iteration:(Po=K==null?void 0:K.iteration)!=null?Po:L.iteration}),p(I)}else if(Ve==="tool_complete"){let U=(ma=(qr=G(L,!1))!=null?qr:G(L,!0))!=null?ma:`tool-${d()}`;if(de.has(U)){de.delete(U);continue}let I=ce(U),X=(cn=I.toolCall)!=null?cn:{id:U,status:"running"};X.status="complete",L.result!==void 0&&(X.result=L.result),typeof L.duration=="number"&&(X.duration=L.duration),X.completedAt=Be((jo=L.completedAt)!=null?jo:L.timestamp);let re=(pn=L.duration)!=null?pn:L.executionTime;if(typeof re=="number")X.durationMs=re;else{let Oe=(un=X.startedAt)!=null?un:Date.now();X.durationMs=Math.max(0,((_n=X.completedAt)!=null?_n:Date.now())-Oe)}I.toolCall=X,I.streaming=!1;let K=L.agentContext;(K||L.executionId)&&(I.agentMetadata=(Ct=I.agentMetadata)!=null?Ct:{executionId:(Un=K==null?void 0:K.executionId)!=null?Un:L.executionId,iteration:(fn=K==null?void 0:K.iteration)!=null?fn:L.iteration}),p(I);let Ae=Z(L);Ae&&A.byCall.delete(Ae)}else if(Ve==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let U=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,I=(Gr=U!=null?U:L.toolId)!=null?Gr:`local-${d()}`,X=ce(I),re=L.toolName,K=ea(re),Ae=(Kr=X.toolCall)!=null?Kr:{id:I,status:"pending"};Ae.name=re,Ae.args=L.parameters,Ae.status=K?"running":"complete",Ae.chunks=(Ir=Ae.chunks)!=null?Ir:[],Ae.startedAt=(io=Ae.startedAt)!=null?io:Be((Mt=L.startedAt)!=null?Mt:L.timestamp),K?(Ae.completedAt=void 0,Ae.duration=void 0,Ae.durationMs=void 0):Ae.completedAt=(lo=Ae.completedAt)!=null?lo:Ae.startedAt,X.toolCall=Ae,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(mn=L.executionId)!=null?mn:(Xr=X.agentMetadata)==null?void 0:Xr.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},p(X)}else if(Ve==="text_start"){if((Go=L.toolContext)!=null&&Go.toolId)continue;let U=L.partId;if(U!==void 0&&T.current!==null&&U!==T.current){let I=m;I&&(I.streaming=!1,p(I),gt=I,m=null,E=!0)}U!==void 0&&(T.current=U)}else if(Ve==="text_end"){if((gn=L.toolContext)!=null&&gn.toolId)continue;let U=m;U&&(U.streaming=!1,p(U),gt=U,m=null,E=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let U=L.stepType,I=L.executionType;if(U==="tool"||I==="context")continue;let X=L.toolContext;if(X!=null&&X.toolId){let Oe=String((Nt=(Qr=L.id)!=null?Qr:X.stepId)!=null?Nt:`step-${d()}`),at=L.partId!==void 0&&L.partId!==null?String(L.partId):"",tt=`${X.toolId}::${Oe}`,Bt=w.get(tt);if(at!==""&&Bt!==void 0&&Bt!==""&&Bt!==at){let wt=y.get(H(X.toolId,Oe,Bt));wt&&wt.streaming!==!1&&(wt.streaming=!1,p(wt))}at!==""&&w.set(tt,at);let $t=k(X.toolId,Oe,at,X.executionId),lr=(Ko=(hn=(co=(Wr=L.text)!=null?Wr:L.delta)!=null?co:L.content)!=null?hn:L.chunk)!=null?Ko:"";lr&&($t.content+=String(lr),$t.streaming=!0,p($t)),L.isComplete&&($t.streaming=!1,p($t));continue}let re=L.partId;if(re!==void 0&&T.current!==null&&re!==T.current){let Oe=m;Oe&&(Oe.streaming=!1,p(Oe),gt=Oe,m=null,E=!0)}re!==void 0&&(T.current=re);let K=re!==void 0&&(xn=Lt.get(re))!=null?xn:Ce();re!==void 0&&(K.partId||(K.partId=re),Lt.set(re,K));let Ae=(dt=(xe=(Jr=(Ro=L.text)!=null?Ro:L.delta)!=null?Jr:L.content)!=null?xe:L.chunk)!=null?dt:"";if(Ae){let Oe=typeof L.seq=="number"?L.seq:void 0,at=re!=null?re:K.id,tt=Oe!==void 0?_e(at,Oe,String(Ae)):((tr=ie.get(K.id))!=null?tr:"")+Ae;K.rawContent=tt,ee.has(K.id)||ee.set(K.id,this.createStreamParser());let Bt=ee.get(K.id),$t=tt.trim().startsWith("{")||tt.trim().startsWith("[");if($t&&ie.set(K.id,tt),Bt.__isPlainTextParser===!0){K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K);continue}let wt=Bt.processChunk(tt);if(wt instanceof Promise)wt.then(Tt=>{var Hr;let br=typeof Tt=="string"?Tt:(Hr=Tt==null?void 0:Tt.text)!=null?Hr:null;if(br!==null&&br.trim()!=="")K.content=br,p(K);else if(!$t&&!tt.trim().startsWith("<")){let Sr=m,Zt=Sr&&Sr.id===K.id?Sr:K;Zt.id===K.id&&(Zt.content=Oe!==void 0?tt:Zt.content+Ae,ie.delete(Zt.id),ee.delete(Zt.id),Zt.rawContent=void 0,p(Zt))}}).catch(()=>{K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K)});else{let Tt=typeof wt=="string"?wt:(fr=wt==null?void 0:wt.text)!=null?fr:null;Tt!==null&&Tt.trim()!==""?(K.content=Tt,p(K)):!$t&&!tt.trim().startsWith("<")&&(K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K))}}if(L.isComplete){let Oe=(Za=(Io=L.result)==null?void 0:Io.response)!=null?Za:K.content;if(Oe){let at=ie.get(K.id),tt=at!=null?at:ne(Oe);K.rawContent=tt;let Bt=ee.get(K.id),$t=null,lr=!1;if(Bt&&($t=Bt.getExtractedText(),$t===null&&($t=ra(tt)),$t===null)){let wt=Bt.processChunk(tt);wt instanceof Promise?(lr=!0,wt.then(Tt=>{var Hr;let br=typeof Tt=="string"?Tt:(Hr=Tt==null?void 0:Tt.text)!=null?Hr:null;if(br!==null){let Sr=m;Sr&&Sr.id===K.id&&(Sr.content=br,Sr.streaming=!1,ee.delete(Sr.id),ie.delete(Sr.id),p(Sr))}})):$t=typeof wt=="string"?wt:(Xo=wt==null?void 0:wt.text)!=null?Xo:null}if(!lr){$t!==null&&$t.trim()!==""?K.content=$t:ie.has(K.id)||(K.content=ne(Oe));let wt=ee.get(K.id);if(wt){let Tt=(qn=wt.close)==null?void 0:qn.call(wt);Tt instanceof Promise&&Tt.catch(()=>{}),ee.delete(K.id)}ie.delete(K.id),K.streaming=!1,p(K)}}}}else if(Ve==="step_complete"){let U=L.stepType,I=L.executionType;if(U==="tool"||I==="context")continue;let X=L.toolContext;if(X!=null&&X.toolId){let Oe=String((_=(Wo=L.id)!=null?Wo:X.stepId)!=null?_:"");if(Oe){let at=W(X.toolId,Oe);for(let[tt,Bt]of y)tt.startsWith(at)&&Bt.streaming!==!1&&(Bt.streaming=!1,p(Bt));w.delete(`${X.toolId}::${Oe}`)}continue}let re=L.stopReason;if(E){if(m!==null){let tt=m;re&&(tt.stopReason=re),ee.delete(tt.id),ie.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,p(tt))}let Oe=(ga=L.result)==null?void 0:ga.response,at=gt;at&&(re&&(at.stopReason=re),Oe!=null?be(at,Oe):(ee.delete(at.id),ie.delete(at.id))),gt=null;continue}let K=(Ho=L.result)==null?void 0:Ho.response,Ae=Ce();if(re&&(Ae.stopReason=re),K!=null){let Oe=ee.get(Ae.id),at=!1,tt=!1;if(Oe){let Bt=Oe.getExtractedText(),$t=ie.get(Ae.id),lr=$t!=null?$t:ne(K);if(Ae.rawContent=lr,Bt!==null&&Bt.trim()!=="")Ae.content=Bt,at=!0;else{let wt=ra(lr);if(wt!==null)Ae.content=wt,at=!0;else{let Tt=Oe.processChunk(lr);if(Tt instanceof Promise)tt=!0,Tt.then(br=>{var Sr;let Hr=typeof br=="string"?br:(Sr=br==null?void 0:br.text)!=null?Sr:null;if(Hr!==null&&Hr.trim()!==""){let Zt=m;Zt&&Zt.id===Ae.id&&(Zt.content=Hr,Zt.streaming=!1,ee.delete(Zt.id),ie.delete(Zt.id),p(Zt))}else{let Zt=Oe.getExtractedText(),uo=m;uo&&uo.id===Ae.id&&(Zt!==null&&Zt.trim()!==""?uo.content=Zt:ie.has(uo.id)||(uo.content=ne(K)),uo.streaming=!1,ee.delete(uo.id),ie.delete(uo.id),p(uo))}});else{let br=typeof Tt=="string"?Tt:(Bo=Tt==null?void 0:Tt.text)!=null?Bo:null;if(br!==null&&br.trim()!=="")Ae.content=br,at=!0;else{let Hr=Oe.getExtractedText();Hr!==null&&Hr.trim()!==""&&(Ae.content=Hr,at=!0)}}}}}if(!tt){if(!Ae.rawContent){let Bt=ie.get(Ae.id);Ae.rawContent=Bt!=null?Bt:ne(K)}if(!at&&!ie.has(Ae.id)&&(Ae.content=ne(K)),Oe){let Bt=(Qo=Oe.close)==null?void 0:Qo.call(Oe);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Ae.id),ie.delete(Ae.id),Ae.streaming=!1,p(Ae)}}else ee.delete(Ae.id),ie.delete(Ae.id),Ae.streaming=!1,p(Ae)}else if(Ve==="flow_complete"){let U=(Do=L.result)==null?void 0:Do.response;if(E){if(m!==null){let I=m;ee.delete(I.id),ie.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}}else if(U!=null){let I=Ce(),X=ie.get(I.id),re=X!=null?X:ne(U);I.rawContent=re;let K=ne(U),Ae=ee.get(I.id);if(Ae){let tt=ra(re);if(tt!==null)K=tt;else{let Bt=Ae.processChunk(re);Bt instanceof Promise&&Bt.then(lr=>{var Tt;let wt=typeof lr=="string"?lr:(Tt=lr==null?void 0:lr.text)!=null?Tt:null;wt!==null&&(I.content=wt,I.streaming=!1,p(I))});let $t=Ae.getExtractedText();$t!==null&&(K=$t)}}ee.delete(I.id),ie.delete(I.id);let Oe=K!==I.content,at=I.streaming!==!1;Oe&&(I.content=K),I.streaming=!1,(Oe||at)&&p(I)}else if(m!==null){let I=m;ee.delete(I.id),ie.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}r({type:"status",status:"idle"})}else if(Ve==="agent_start")Ge={executionId:L.executionId,agentId:(bo=L.agentId)!=null?bo:"virtual",agentName:(ha=L.agentName)!=null?ha:"",status:"running",currentIteration:0,maxTurns:(Xs=L.maxTurns)!=null?Xs:1,startedAt:Be(L.startedAt)};else if(Ve==="agent_iteration_start"){if(Ge&&(Ge.currentIteration=L.iteration),je==="separate"&&L.iteration>1){let U=m;U&&(U.streaming=!1,p(U),ke.set(L.iteration-1,U),m=null)}}else if(Ve==="agent_turn_start")x=null;else if(Ve==="agent_turn_delta"){if(L.contentType==="text"){let U=Ce();U.content+=(Yr=L.delta)!=null?Yr:"",U.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:Ge==null?void 0:Ge.agentName},x=U,p(U)}else if(L.contentType==="thinking"){let U=(Zr=L.turnId)!=null?Zr:`agent-think-${L.iteration}`,I=Te(U);I.reasoning=(vo=I.reasoning)!=null?vo:{id:U,status:"streaming",chunks:[]},I.reasoning.chunks.push((Co=L.delta)!=null?Co:""),I.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},p(I)}else if(L.contentType==="tool_input"){let U=(Vn=L.toolCallId)!=null?Vn:A.lastId;if(U){let I=P.get(U);I!=null&&I.toolCall&&(I.toolCall.chunks=(Jo=I.toolCall.chunks)!=null?Jo:[],I.toolCall.chunks.push((Mr=L.delta)!=null?Mr:""),p(I))}}}else if(Ve==="agent_turn_complete"){let U=L.turnId;if(U){let re=M.get(U);if(re!=null&&re.reasoning){re.reasoning.status="complete",re.reasoning.completedAt=Be(L.completedAt);let K=(Fo=re.reasoning.startedAt)!=null?Fo:Date.now();re.reasoning.durationMs=Math.max(0,((xa=re.reasoning.completedAt)!=null?xa:Date.now())-K),re.streaming=!1,p(re)}}let I=L.stopReason,X=m!=null?m:x;if(I&&X!==null){let re=L.turnId;(!re||(($n=X.agentMetadata)==null?void 0:$n.turnId)===re)&&(X.stopReason=I,p(X))}}else if(Ve==="agent_tool_start"){m&&(m.streaming=!1,p(m),m=null);let U=(ya=L.toolCallId)!=null?ya:`agent-tool-${d()}`;We(Z(L),U);let I=ce(U),X=(Qs=I.toolCall)!=null?Qs:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};X.name=(Js=(ba=L.toolName)!=null?ba:L.name)!=null?Js:X.name,X.status="running",L.parameters!==void 0&&(X.args=L.parameters),X.startedAt=Be((va=L.startedAt)!=null?va:L.timestamp),I.toolCall=X,I.streaming=!0,I.agentMetadata={executionId:L.executionId,iteration:L.iteration},p(I)}else if(Ve==="agent_tool_delta"){let U=(mt=L.toolCallId)!=null?mt:A.lastId;if(U){let I=(es=P.get(U))!=null?es:ce(U);I.toolCall&&(I.toolCall.chunks=(po=I.toolCall.chunks)!=null?po:[],I.toolCall.chunks.push((Vr=L.delta)!=null?Vr:""),I.toolCall.status="running",I.streaming=!0,p(I))}}else if(Ve==="agent_tool_complete"){let U=(Ys=L.toolCallId)!=null?Ys:A.lastId;if(U){let I=(Zs=P.get(U))!=null?Zs:ce(U);if(I.toolCall){I.toolCall.status="complete",L.result!==void 0&&(I.toolCall.result=L.result),typeof L.executionTime=="number"&&(I.toolCall.durationMs=L.executionTime),I.toolCall.completedAt=Be((Ca=L.completedAt)!=null?Ca:L.timestamp),I.streaming=!1,p(I);let X=Z(L);X&&A.byCall.delete(X)}}}else if(Ve==="agent_media"){let U=Array.isArray(L.media)?L.media:[],I=[];for(let X of U){if(!X||typeof X!="object")continue;let re=X,K=typeof re.type=="string"?re.type:void 0,Ae=typeof re.mediaType=="string"?re.mediaType.toLowerCase():"",Oe=null,at="";if(K==="media"){let tt=typeof re.data=="string"?re.data:void 0;if(!tt)continue;at=Ae.length>0?Ae:"application/octet-stream",Oe=`data:${at};base64,${tt}`}else if(K==="image-url"){let tt=typeof re.url=="string"?re.url:void 0;if(!tt)continue;at=Ae,Oe=tt}else if(K==="file-url"){let tt=typeof re.url=="string"?re.url:void 0;if(!tt)continue;at=Ae,Oe=tt}else continue;if(Oe)if(K==="image-url"||at.startsWith("image/"))I.push({type:"image",image:Oe,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))I.push({type:"audio",audio:Oe,mimeType:at});else if(at.startsWith("video/"))I.push({type:"video",video:Oe,mimeType:at});else{let tt=at||"application/octet-stream";I.push({type:"file",data:Oe,mimeType:tt,filename:Vy(tt)})}}if(I.length>0){let X=d(),re=L.toolCallId,Ae={id:`agent-media-${typeof re=="string"&&re.length>0?`${re}-${X}`:String(X)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:X,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};p(Ae);let Oe=m;Oe&&(Oe.streaming=!1,p(Oe)),m=null,C.current=null}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let U=`agent-reflection-${L.executionId}-${L.iteration}`,I={id:U,role:"assistant",content:(Yo=L.reflection)!=null?Yo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:d(),reasoning:{id:U,status:"complete",chunks:[(ts=L.reflection)!=null?ts:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};p(I)}else if(Ve==="agent_complete"){Ge&&(Ge.status=L.success?"complete":"error",Ge.completedAt=Be(L.completedAt),Ge.stopReason=L.stopReason);let U=m;U&&(U.streaming=!1,p(U)),r({type:"status",status:"idle"})}else if(Ve==="agent_error"){let U=typeof L.error=="string"?L.error:(rs=(yn=L.error)==null?void 0:yn.message)!=null?rs:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):r({type:"error",error:new Error(U)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let U=(os=L.approvalId)!=null?os:`approval-${d()}`,I={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:"pending",agentId:(ns=Ge==null?void 0:Ge.agentId)!=null?ns:"virtual",executionId:($r=(as=L.executionId)!=null?as:Ge==null?void 0:Ge.executionId)!=null?$r:"",toolName:(wa=L.toolName)!=null?wa:"",toolType:L.toolType,description:(Oo=L.description)!=null?Oo:`Execute ${(No=L.toolName)!=null?No:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};p(I)}else if(Ve==="step_await"&&L.awaitReason==="approval_required"){let U=(ss=L.approvalId)!=null?ss:`approval-${d()}`,I={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:"pending",agentId:(ei=Ge==null?void 0:Ge.agentId)!=null?ei:"virtual",executionId:(ls=(is=L.executionId)!=null?is:Ge==null?void 0:Ge.executionId)!=null?ls:"",toolName:(zn=L.toolName)!=null?zn:"",toolType:L.toolType,description:(ri=L.description)!=null?ri:`Execute ${(ti=L.toolName)!=null?ti:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};p(I)}else if(Ve==="agent_approval_complete"){let U=L.approvalId;if(U){let X={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:(oi=L.decision)!=null?oi:"approved",agentId:(ni=Ge==null?void 0:Ge.agentId)!=null?ni:"virtual",executionId:(bn=(ai=L.executionId)!=null?ai:Ge==null?void 0:Ge.executionId)!=null?bn:"",toolName:(vn=L.toolName)!=null?vn:"",description:(si=L.description)!=null?si:"",resolvedAt:Date.now()}};p(X)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let U=L.artifactType,I=String(L.id),X=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:I,artifactType:U,title:X,component:typeof L.component=="string"?L.component:void 0}),ge.set(I,{markdown:"",title:X}),!le.has(I)){le.add(I);let re={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:X,artifactType:U,status:"streaming"}})};J.set(I,re),p(re)}}else if(Ve==="artifact_delta"){let U=String(L.id),I=typeof L.delta=="string"?L.delta:String((ds=L.delta)!=null?ds:"");r({type:"artifact_delta",id:U,artDelta:I});let X=ge.get(U);X&&(X.markdown+=I)}else if(Ve==="artifact_update"){let U=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:U,component:typeof L.component=="string"?L.component:void 0})}else if(Ve==="artifact_complete"){let U=String(L.id);r({type:"artifact_complete",id:U});let I=J.get(U);if(I){I.streaming=!1;try{let X=JSON.parse((Cn=I.rawContent)!=null?Cn:"{}");if(X.props){X.props.status="complete";let re=ge.get(U);re!=null&&re.markdown&&(X.props.markdown=re.markdown)}I.rawContent=JSON.stringify(X)}catch{}ge.delete(U),p(I),J.delete(U)}}}else if(Ve==="transcript_insert"){let U=L.message;if(!U||typeof U!="object")continue;let I=String((ii=U.id)!=null?ii:`msg-${d()}`),X=U.role,K={id:I,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:d()};if(p(K),K.rawContent)try{let Ae=JSON.parse(K.rawContent),Oe=(cs=Ae==null?void 0:Ae.props)==null?void 0:cs.artifactId;typeof Oe=="string"&&le.add(Oe)}catch{}m=null,C.current=null,ee.delete(I),ie.delete(I)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let U=null;if(L.error instanceof Error)U=L.error;else if(Ve==="dispatch_error"){let I=(wn=L.message)!=null?wn:L.error;I!=null&&I!==""&&(U=new Error(String(I)))}else if(Ve==="step_error"||Ve==="flow_error"){let I=L.error;typeof I=="string"&&I!==""?U=new Error(I):I!=null&&typeof I=="object"&&"message"in I&&(U=new Error(String((ps=I.message)!=null?ps:I)))}else Ve==="error"&&L.error!=null&&L.error!==""&&(U=new Error(String(L.error)));if(U){r({type:"error",error:U});let I=m;I&&I.streaming&&(I.streaming=!1,p(I)),r({type:"status",status:"idle"})}}}}}Ze.length=0};;){let{done:V,value:j}=await n.read();if(V)break;s+=a.decode(j,{stream:!0});let he=s.split(`
10
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ra=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Pi=()=>{var t;let e=Uy();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Ri=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,nn.parse)(r,nn.STR|nn.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?Mi(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=Mi(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Ng=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?Mi(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Mi(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,nn.parse)(a,nn.STR|nn.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},Ii=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Wi=class{constructor(t,r=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=r}push(t,r){var a,s,i;let o=(i=(a=r==null?void 0:r.seq)!=null?a:r==null?void 0:r.sequenceIndex)!=null?i:(s=r==null?void 0:r.agentContext)==null?void 0:s.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,r);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,r),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,r);return}let n=this.buffer.get(o);n!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${n.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(n.payloadType,n.payload)),this.buffer.set(o,{payloadType:t,payload:r,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((r,o)=>r[0]-o[0]);for(let[r,o]of t)this.buffer.delete(r),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Og="3.36.0";var oa=Og;var Vy="https://api.runtype.com/v1/dispatch",Hi="https://api.runtype.com";function $y(e){var a,s;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var nd=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function zy(e){switch(e){case"json":return Ri;case"regex-json":return Pi;case"xml":return Ii;default:return Li}}var _g=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function jy(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=_g(r);if(!_g(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ra(e);return ra(t)!==null&&s===null?t:e}var na=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;this.apiUrl=(r=t.apiUrl)!=null?r:Vy,this.headers={"Content-Type":"application/json","X-Persona-Version":oa,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:zy(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ha(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Hi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let t=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":oa},body:JSON.stringify(r)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let n=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(n.sessionId),{sessionId:n.sessionId,expiresAt:new Date(n.expiresAt),flow:n.flow,config:{welcomeMessage:n.config.welcomeMessage,placeholder:n.config.placeholder,theme:n.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Hi}/v1/client/feedback`}async sendFeedback(t){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":oa},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let d=await this.buildPayload(t.messages),u=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,g={sessionId:c.sessionId,messages:t.messages.filter(nd).map(y=>{var w,b,A;return{id:y.id,role:y.role,content:(A=(b=(w=y.contentParts)!=null?w:y.llmContent)!=null?b:y.rawContent)!=null?A:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},p=d.clientTools,m=!!(p&&p.length>0),x=m?vg(p):void 0,C=this.clientToolsFingerprintSessionId===c.sessionId,T=m&&C&&this.lastSentClientToolsFingerprint===x,E=!1,M=null,P;for(let y=0;;y++){let b={...g,...m&&(E||!T)&&p?{clientTools:p}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",b),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":oa},body:JSON.stringify(b),signal:o.signal}),P.status===409&&y===0&&m){let A=await P.json().catch(()=>null);if((A==null?void 0:A.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}M=A!=null?A:{error:"Chat request failed"}}break}if(!P.ok){let y=M!=null?M:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let b=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:b}),b}if(P.status===429){let b=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:b}),b}let w=new Error(y.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!P.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(P.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let d=c instanceof Error?c:new Error(String(c));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&r({type:"error",error:d}),d}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Hi}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var d,u;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((d=this.config.apiUrl)==null?void 0:d.replace(/\/+$/,""))||Hi}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var a,s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(nd).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,c)=>{let d=new Date(i.createdAt).getTime(),u=new Date(c.createdAt).getTime();return d-u}).map(i=>{var c,d,u;return{role:i.role,content:(u=(d=(c=i.contentParts)!=null?c:i.llmContent)!=null?d:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),o={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},n=[...Ms(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async c=>{try{let d=await c({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(i,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(i).length&&(o.context=i)}return o}async buildPayload(t){var a,s;let o={messages:t.slice().filter(nd).sort((i,c)=>{let d=new Date(i.createdAt).getTime(),u=new Date(c.createdAt).getTime();return d-u}).map(i=>{var c,d,u;return{role:i.role,content:(u=(d=(c=i.contentParts)!=null?c:i.llmContent)!=null?d:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},n=[...Ms(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async c=>{try{let d=await c({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(i,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(i).length&&(o.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...o},config:this.config});if(i&&typeof i=="object"){let c=i;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return o}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...u!==void 0&&{partId:u}};return o.current=g,n(g),g},d=u=>o.current?o.current:c(u);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let u=d(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,n(u)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var Cr,Wt,ur,Eo;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,d=()=>i+c++,u=V=>{let j=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,he=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,Xe=V.tools?V.tools.map(et=>({...et,chunks:et.chunks?[...et.chunks]:void 0})):void 0;return{...V,reasoning:j,toolCall:he,tools:Xe}},g=V=>{if(V.role!=="assistant"||V.variant)return!0;let j=Array.isArray(V.contentParts)&&V.contentParts.length>0,he=typeof V.rawContent=="string"&&V.rawContent.trim()!=="";return typeof V.content=="string"&&V.content.trim()!==""||j||he||!!V.stopReason},p=V=>{g(V)&&r({type:"message",message:u(V)})},m=null,x=null,C={current:null},T={current:null},E=!1,M=new Map,P=new Map,y=new Map,w=new Map,b={lastId:null,byStep:new Map},A={lastId:null,byCall:new Map},H=(V,j,he="")=>`${V}::${j}::${he}`,W=(V,j)=>`${V}::${j}::`,k=(V,j,he,Xe)=>{let et=H(V,j,he),qe=y.get(et);if(qe)return qe;let Ne=he?`-${he}`:"",Pt={id:`nested-${V}-${j}${Ne}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...he?{partId:he}:{},agentMetadata:{executionId:Xe,parentToolId:V,parentStepId:j}};return y.set(et,Pt),p(Pt),Pt},N=V=>{if(V==null)return null;try{return String(V)}catch{return null}},q=V=>{var j,he,Xe,et,qe;return N((qe=(et=(Xe=(he=(j=V.stepId)!=null?j:V.step_id)!=null?he:V.step)!=null?Xe:V.parentId)!=null?et:V.flowStepId)!=null?qe:V.flow_step_id)},Z=V=>{var j,he,Xe,et,qe,Ne,Pt;return N((Pt=(Ne=(qe=(et=(Xe=(he=(j=V.callId)!=null?j:V.call_id)!=null?he:V.requestId)!=null?Xe:V.request_id)!=null?et:V.toolCallId)!=null?qe:V.tool_call_id)!=null?Ne:V.stepId)!=null?Pt:V.step_id)},me=o,Ke=!1,Ce=()=>{if(m)return m;let V;return!Ke&&me?(V=me,Ke=!0):me&&T.current?V=`${me}_${T.current}`:V=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:V,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d()},p(m),m},Ie=(V,j)=>{b.lastId=j,V&&b.byStep.set(V,j)},Ue=(V,j)=>{var qe;let he=(qe=V.reasoningId)!=null?qe:V.id,Xe=q(V);if(he){let Ne=String(he);return Ie(Xe,Ne),Ne}if(Xe){let Ne=b.byStep.get(Xe);if(Ne)return b.lastId=Ne,Ne}if(b.lastId&&!j)return b.lastId;if(!j)return null;let et=`reason-${d()}`;return Ie(Xe,et),et},Te=V=>{let j=M.get(V);if(j)return j;let he={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:V,status:"streaming",chunks:[]}};return M.set(V,he),p(he),he},We=(V,j)=>{A.lastId=j,V&&A.byCall.set(V,j)},de=new Set,J=new Map,le=new Set,ge=new Map,ue=V=>{if(!V)return!1;let j=V.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},G=(V,j)=>{var qe;let he=(qe=V.toolId)!=null?qe:V.id,Xe=Z(V);if(he){let Ne=String(he);return We(Xe,Ne),Ne}if(Xe){let Ne=A.byCall.get(Xe);if(Ne)return A.lastId=Ne,Ne}if(A.lastId&&!j)return A.lastId;if(!j)return null;let et=`tool-${d()}`;return We(Xe,et),et},ce=V=>{let j=P.get(V);if(j)return j;let he={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:V,status:"pending"}};return P.set(V,he),p(he),he},Be=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let j=Number(V);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let he=Date.parse(V);if(!Number.isNaN(he))return he}return Date.now()},ne=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},ee=new Map,ie=new Map,vt=new Map,Lt=new Map,gt=null,_e=(V,j,he)=>{var Pt;let Xe=vt.get(V);Xe||(Xe=[],vt.set(V,Xe));let et=0,qe=Xe.length;for(;et<qe;){let Gt=et+qe>>>1;Xe[Gt].seq<j?et=Gt+1:qe=Gt}((Pt=Xe[et])==null?void 0:Pt.seq)===j?Xe[et]={seq:j,text:he}:Xe.splice(et,0,{seq:j,text:he});let Ne="";for(let Gt=0;Gt<Xe.length;Gt++)Ne+=Xe[Gt].text;return Ne},be=(V,j)=>{let he=ne(j),Xe=ie.get(V.id),et=jy(Xe,he);V.rawContent=et;let qe=ee.get(V.id),Ne=z=>{var oe;let Ht=(oe=V.content)!=null?oe:"";z.trim()!==""&&(Ht.trim().length===0||z.startsWith(Ht)||z.trimStart().startsWith(Ht.trim()))&&(V.content=z)},Pt=()=>{var z;if(qe){let Ht=(z=qe.close)==null?void 0:z.call(qe);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(V.id),ie.delete(V.id),V.streaming=!1,p(V)};if(!qe){Ne(he),Pt();return}let Gt=ra(et);if(Gt!==null&&Gt.trim()!==""){Ne(Gt),Pt();return}let Jt=z=>{var we;let Ht=typeof z=="string"?z:(we=z==null?void 0:z.text)!=null?we:null;if(Ht!==null&&Ht.trim()!=="")return Ht;let oe=qe.getExtractedText();return oe!==null&&oe.trim()!==""?oe:he},Pr;try{Pr=qe.processChunk(et)}catch{Ne(he),Pt();return}if(Pr instanceof Promise){Pr.then(z=>{Ne(Jt(z)),Pt()}).catch(()=>{Ne(he),Pt()});return}Ne(Jt(Pr)),Pt()},Ze=[],Y=!1,pe,Me=()=>{Y||(Y=!0,queueMicrotask(()=>{Y=!1,pe()}))},Je=new Wi((V,j)=>{Ze.push({payloadType:V,payload:j}),Me()}),Ge=null,ke=new Map,je=(Cr=this.config.iterationDisplay)!=null?Cr:"separate";for(pe=()=>{var V,j,he,Xe,et,qe,Ne,Pt,Gt,Jt,Pr,z,Ht,oe,we,De,At,ar,sr,wr,Ft,ot,Dt,lt,Yt,so,Rr,ir,Ur,ko,yt,jr,Lo,zo,yo,ht,Nn,Po,On,qr,ga,cn,jo,pn,un,_n,Un,fn,Ct,Gr,Kr,Ir,Mt,io,lo,Xr,mn,Go,gn,Qr,Nt,Wr,co,hn,Ko,xn,Ro,Jr,xe,dt,tr,fr,Io,es,Xo,qn,Wo,_,ha,Ho,Bo,Qo,Do,bo,xa,Qs,Yr,Zr,vo,Co,Vn,Jo,Mr,Fo,ya,$n,ba,Js,va,Ys,Ca,mt,ts,po,Vr,Zs,ei,wa,Yo,rs,yn,os,ns,as,ss,$r,Sa,No,Oo,is,ti,ls,ds,zn,ri,oi,ni,ai,si,bn,vn,ii,cs,Cn,li,ps,wn,us;for(let Aa=0;Aa<Ze.length;Aa++){let Ve=Ze[Aa].payloadType,L=Ze[Aa].payload;if(Ve==="reason_start"){let U=(V=Ue(L,!0))!=null?V:`reason-${d()}`,I=Te(U);I.reasoning=(j=I.reasoning)!=null?j:{id:U,status:"streaming",chunks:[]},I.reasoning.startedAt=(Xe=I.reasoning.startedAt)!=null?Xe:Be((he=L.startedAt)!=null?he:L.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let U=(qe=(et=Ue(L,!1))!=null?et:Ue(L,!0))!=null?qe:`reason-${d()}`,I=Te(U);I.reasoning=(Ne=I.reasoning)!=null?Ne:{id:U,status:"streaming",chunks:[]},I.reasoning.startedAt=(Gt=I.reasoning.startedAt)!=null?Gt:Be((Pt=L.startedAt)!=null?Pt:L.timestamp);let X=(z=(Pr=(Jt=L.reasoningText)!=null?Jt:L.text)!=null?Pr:L.delta)!=null?z:"";if(X&&L.hidden!==!0){let re=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(re!==void 0){let K=_e(U,re,String(X));I.reasoning.chunks=[K]}else I.reasoning.chunks.push(String(X))}if(I.reasoning.status=L.done?"complete":"streaming",L.done){I.reasoning.completedAt=Be((Ht=L.completedAt)!=null?Ht:L.timestamp);let re=(oe=I.reasoning.startedAt)!=null?oe:Date.now();I.reasoning.durationMs=Math.max(0,((we=I.reasoning.completedAt)!=null?we:Date.now())-re)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(Ve==="reason_complete"){let U=(At=(De=Ue(L,!1))!=null?De:Ue(L,!0))!=null?At:`reason-${d()}`,I=M.get(U);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=Be((ar=L.completedAt)!=null?ar:L.timestamp);let re=(sr=I.reasoning.startedAt)!=null?sr:Date.now();I.reasoning.durationMs=Math.max(0,((wr=I.reasoning.completedAt)!=null?wr:Date.now())-re),I.streaming=!1,p(I)}let X=q(L);X&&b.byStep.delete(X)}else if(Ve==="tool_start"){let U=(Ft=G(L,!0))!=null?Ft:`tool-${d()}`,I=(ot=L.toolName)!=null?ot:L.name;if(ue(I)){de.add(U);continue}let X=ce(U),re=(Dt=X.toolCall)!=null?Dt:{id:U,status:"pending"};re.name=I!=null?I:re.name,re.status="running",L.args!==void 0?re.args=L.args:L.parameters!==void 0&&(re.args=L.parameters),re.startedAt=(Yt=re.startedAt)!=null?Yt:Be((lt=L.startedAt)!=null?lt:L.timestamp),re.completedAt=void 0,re.durationMs=void 0,X.toolCall=re,X.streaming=!0;let K=L.agentContext;(K||L.executionId)&&(X.agentMetadata={executionId:(so=K==null?void 0:K.executionId)!=null?so:L.executionId,iteration:(Rr=K==null?void 0:K.iteration)!=null?Rr:L.iteration}),p(X)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let U=(Ur=(ir=G(L,!1))!=null?ir:G(L,!0))!=null?Ur:`tool-${d()}`;if(de.has(U))continue;let I=ce(U),X=(ko=I.toolCall)!=null?ko:{id:U,status:"running"};X.startedAt=(jr=X.startedAt)!=null?jr:Be((yt=L.startedAt)!=null?yt:L.timestamp);let re=(yo=(zo=(Lo=L.text)!=null?Lo:L.delta)!=null?zo:L.message)!=null?yo:"";re&&(X.chunks=(ht=X.chunks)!=null?ht:[],X.chunks.push(String(re))),X.status="running",I.toolCall=X,I.streaming=!0;let K=L.agentContext;(K||L.executionId)&&(I.agentMetadata=(On=I.agentMetadata)!=null?On:{executionId:(Nn=K==null?void 0:K.executionId)!=null?Nn:L.executionId,iteration:(Po=K==null?void 0:K.iteration)!=null?Po:L.iteration}),p(I)}else if(Ve==="tool_complete"){let U=(ga=(qr=G(L,!1))!=null?qr:G(L,!0))!=null?ga:`tool-${d()}`;if(de.has(U)){de.delete(U);continue}let I=ce(U),X=(cn=I.toolCall)!=null?cn:{id:U,status:"running"};X.status="complete",L.result!==void 0&&(X.result=L.result),typeof L.duration=="number"&&(X.duration=L.duration),X.completedAt=Be((jo=L.completedAt)!=null?jo:L.timestamp);let re=(pn=L.duration)!=null?pn:L.executionTime;if(typeof re=="number")X.durationMs=re;else{let Oe=(un=X.startedAt)!=null?un:Date.now();X.durationMs=Math.max(0,((_n=X.completedAt)!=null?_n:Date.now())-Oe)}I.toolCall=X,I.streaming=!1;let K=L.agentContext;(K||L.executionId)&&(I.agentMetadata=(Ct=I.agentMetadata)!=null?Ct:{executionId:(Un=K==null?void 0:K.executionId)!=null?Un:L.executionId,iteration:(fn=K==null?void 0:K.iteration)!=null?fn:L.iteration}),p(I);let Ae=Z(L);Ae&&A.byCall.delete(Ae)}else if(Ve==="step_await"&&L.awaitReason==="local_tool_required"&&L.toolName){let U=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,I=(Gr=U!=null?U:L.toolId)!=null?Gr:`local-${d()}`,X=ce(I),re=L.toolName,K=ea(re),Ae=(Kr=X.toolCall)!=null?Kr:{id:I,status:"pending"};Ae.name=re,Ae.args=L.parameters,Ae.status=K?"running":"complete",Ae.chunks=(Ir=Ae.chunks)!=null?Ir:[],Ae.startedAt=(io=Ae.startedAt)!=null?io:Be((Mt=L.startedAt)!=null?Mt:L.timestamp),K?(Ae.completedAt=void 0,Ae.duration=void 0,Ae.durationMs=void 0):Ae.completedAt=(lo=Ae.completedAt)!=null?lo:Ae.startedAt,X.toolCall=Ae,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(mn=L.executionId)!=null?mn:(Xr=X.agentMetadata)==null?void 0:Xr.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},p(X)}else if(Ve==="text_start"){if((Go=L.toolContext)!=null&&Go.toolId)continue;let U=L.partId;if(U!==void 0&&T.current!==null&&U!==T.current){let I=m;I&&(I.streaming=!1,p(I),gt=I,m=null,E=!0)}U!==void 0&&(T.current=U)}else if(Ve==="text_end"){if((gn=L.toolContext)!=null&&gn.toolId)continue;let U=m;U&&(U.streaming=!1,p(U),gt=U,m=null,E=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let U=L.stepType,I=L.executionType;if(U==="tool"||I==="context")continue;let X=L.toolContext;if(X!=null&&X.toolId){let Oe=String((Nt=(Qr=L.id)!=null?Qr:X.stepId)!=null?Nt:`step-${d()}`),at=L.partId!==void 0&&L.partId!==null?String(L.partId):"",tt=`${X.toolId}::${Oe}`,Bt=w.get(tt);if(at!==""&&Bt!==void 0&&Bt!==""&&Bt!==at){let wt=y.get(H(X.toolId,Oe,Bt));wt&&wt.streaming!==!1&&(wt.streaming=!1,p(wt))}at!==""&&w.set(tt,at);let $t=k(X.toolId,Oe,at,X.executionId),lr=(Ko=(hn=(co=(Wr=L.text)!=null?Wr:L.delta)!=null?co:L.content)!=null?hn:L.chunk)!=null?Ko:"";lr&&($t.content+=String(lr),$t.streaming=!0,p($t)),L.isComplete&&($t.streaming=!1,p($t));continue}let re=L.partId;if(re!==void 0&&T.current!==null&&re!==T.current){let Oe=m;Oe&&(Oe.streaming=!1,p(Oe),gt=Oe,m=null,E=!0)}re!==void 0&&(T.current=re);let K=re!==void 0&&(xn=Lt.get(re))!=null?xn:Ce();re!==void 0&&(K.partId||(K.partId=re),Lt.set(re,K));let Ae=(dt=(xe=(Jr=(Ro=L.text)!=null?Ro:L.delta)!=null?Jr:L.content)!=null?xe:L.chunk)!=null?dt:"";if(Ae){let Oe=typeof L.seq=="number"?L.seq:void 0,at=re!=null?re:K.id,tt=Oe!==void 0?_e(at,Oe,String(Ae)):((tr=ie.get(K.id))!=null?tr:"")+Ae;K.rawContent=tt,ee.has(K.id)||ee.set(K.id,this.createStreamParser());let Bt=ee.get(K.id),$t=tt.trim().startsWith("{")||tt.trim().startsWith("[");if($t&&ie.set(K.id,tt),Bt.__isPlainTextParser===!0){K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K);continue}let wt=Bt.processChunk(tt);if(wt instanceof Promise)wt.then(Tt=>{var Hr;let br=typeof Tt=="string"?Tt:(Hr=Tt==null?void 0:Tt.text)!=null?Hr:null;if(br!==null&&br.trim()!=="")K.content=br,p(K);else if(!$t&&!tt.trim().startsWith("<")){let Sr=m,Zt=Sr&&Sr.id===K.id?Sr:K;Zt.id===K.id&&(Zt.content=Oe!==void 0?tt:Zt.content+Ae,ie.delete(Zt.id),ee.delete(Zt.id),Zt.rawContent=void 0,p(Zt))}}).catch(()=>{K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K)});else{let Tt=typeof wt=="string"?wt:(fr=wt==null?void 0:wt.text)!=null?fr:null;Tt!==null&&Tt.trim()!==""?(K.content=Tt,p(K)):!$t&&!tt.trim().startsWith("<")&&(K.content=Oe!==void 0?tt:K.content+Ae,ie.delete(K.id),ee.delete(K.id),K.rawContent=void 0,p(K))}}if(L.isComplete){let Oe=(es=(Io=L.result)==null?void 0:Io.response)!=null?es:K.content;if(Oe){let at=ie.get(K.id),tt=at!=null?at:ne(Oe);K.rawContent=tt;let Bt=ee.get(K.id),$t=null,lr=!1;if(Bt&&($t=Bt.getExtractedText(),$t===null&&($t=ra(tt)),$t===null)){let wt=Bt.processChunk(tt);wt instanceof Promise?(lr=!0,wt.then(Tt=>{var Hr;let br=typeof Tt=="string"?Tt:(Hr=Tt==null?void 0:Tt.text)!=null?Hr:null;if(br!==null){let Sr=m;Sr&&Sr.id===K.id&&(Sr.content=br,Sr.streaming=!1,ee.delete(Sr.id),ie.delete(Sr.id),p(Sr))}})):$t=typeof wt=="string"?wt:(Xo=wt==null?void 0:wt.text)!=null?Xo:null}if(!lr){$t!==null&&$t.trim()!==""?K.content=$t:ie.has(K.id)||(K.content=ne(Oe));let wt=ee.get(K.id);if(wt){let Tt=(qn=wt.close)==null?void 0:qn.call(wt);Tt instanceof Promise&&Tt.catch(()=>{}),ee.delete(K.id)}ie.delete(K.id),K.streaming=!1,p(K)}}}}else if(Ve==="step_complete"){let U=L.stepType,I=L.executionType;if(U==="tool"||I==="context")continue;let X=L.toolContext;if(X!=null&&X.toolId){let Oe=String((_=(Wo=L.id)!=null?Wo:X.stepId)!=null?_:"");if(Oe){let at=W(X.toolId,Oe);for(let[tt,Bt]of y)tt.startsWith(at)&&Bt.streaming!==!1&&(Bt.streaming=!1,p(Bt));w.delete(`${X.toolId}::${Oe}`)}continue}let re=L.stopReason;if(E){if(m!==null){let tt=m;re&&(tt.stopReason=re),ee.delete(tt.id),ie.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,p(tt))}let Oe=(ha=L.result)==null?void 0:ha.response,at=gt;at&&(re&&(at.stopReason=re),Oe!=null?be(at,Oe):(ee.delete(at.id),ie.delete(at.id))),gt=null;continue}let K=(Ho=L.result)==null?void 0:Ho.response,Ae=Ce();if(re&&(Ae.stopReason=re),K!=null){let Oe=ee.get(Ae.id),at=!1,tt=!1;if(Oe){let Bt=Oe.getExtractedText(),$t=ie.get(Ae.id),lr=$t!=null?$t:ne(K);if(Ae.rawContent=lr,Bt!==null&&Bt.trim()!=="")Ae.content=Bt,at=!0;else{let wt=ra(lr);if(wt!==null)Ae.content=wt,at=!0;else{let Tt=Oe.processChunk(lr);if(Tt instanceof Promise)tt=!0,Tt.then(br=>{var Sr;let Hr=typeof br=="string"?br:(Sr=br==null?void 0:br.text)!=null?Sr:null;if(Hr!==null&&Hr.trim()!==""){let Zt=m;Zt&&Zt.id===Ae.id&&(Zt.content=Hr,Zt.streaming=!1,ee.delete(Zt.id),ie.delete(Zt.id),p(Zt))}else{let Zt=Oe.getExtractedText(),uo=m;uo&&uo.id===Ae.id&&(Zt!==null&&Zt.trim()!==""?uo.content=Zt:ie.has(uo.id)||(uo.content=ne(K)),uo.streaming=!1,ee.delete(uo.id),ie.delete(uo.id),p(uo))}});else{let br=typeof Tt=="string"?Tt:(Bo=Tt==null?void 0:Tt.text)!=null?Bo:null;if(br!==null&&br.trim()!=="")Ae.content=br,at=!0;else{let Hr=Oe.getExtractedText();Hr!==null&&Hr.trim()!==""&&(Ae.content=Hr,at=!0)}}}}}if(!tt){if(!Ae.rawContent){let Bt=ie.get(Ae.id);Ae.rawContent=Bt!=null?Bt:ne(K)}if(!at&&!ie.has(Ae.id)&&(Ae.content=ne(K)),Oe){let Bt=(Qo=Oe.close)==null?void 0:Qo.call(Oe);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Ae.id),ie.delete(Ae.id),Ae.streaming=!1,p(Ae)}}else ee.delete(Ae.id),ie.delete(Ae.id),Ae.streaming=!1,p(Ae)}else if(Ve==="flow_complete"){let U=(Do=L.result)==null?void 0:Do.response;if(E){if(m!==null){let I=m;ee.delete(I.id),ie.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}}else if(U!=null){let I=Ce(),X=ie.get(I.id),re=X!=null?X:ne(U);I.rawContent=re;let K=ne(U),Ae=ee.get(I.id);if(Ae){let tt=ra(re);if(tt!==null)K=tt;else{let Bt=Ae.processChunk(re);Bt instanceof Promise&&Bt.then(lr=>{var Tt;let wt=typeof lr=="string"?lr:(Tt=lr==null?void 0:lr.text)!=null?Tt:null;wt!==null&&(I.content=wt,I.streaming=!1,p(I))});let $t=Ae.getExtractedText();$t!==null&&(K=$t)}}ee.delete(I.id),ie.delete(I.id);let Oe=K!==I.content,at=I.streaming!==!1;Oe&&(I.content=K),I.streaming=!1,(Oe||at)&&p(I)}else if(m!==null){let I=m;ee.delete(I.id),ie.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}r({type:"status",status:"idle"})}else if(Ve==="agent_start")Ge={executionId:L.executionId,agentId:(bo=L.agentId)!=null?bo:"virtual",agentName:(xa=L.agentName)!=null?xa:"",status:"running",currentIteration:0,maxTurns:(Qs=L.maxTurns)!=null?Qs:1,startedAt:Be(L.startedAt)};else if(Ve==="agent_iteration_start"){if(Ge&&(Ge.currentIteration=L.iteration),je==="separate"&&L.iteration>1){let U=m;U&&(U.streaming=!1,p(U),ke.set(L.iteration-1,U),m=null)}}else if(Ve==="agent_turn_start")x=null;else if(Ve==="agent_turn_delta"){if(L.contentType==="text"){let U=Ce();U.content+=(Yr=L.delta)!=null?Yr:"",U.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId,agentName:Ge==null?void 0:Ge.agentName},x=U,p(U)}else if(L.contentType==="thinking"){let U=(Zr=L.turnId)!=null?Zr:`agent-think-${L.iteration}`,I=Te(U);I.reasoning=(vo=I.reasoning)!=null?vo:{id:U,status:"streaming",chunks:[]},I.reasoning.chunks.push((Co=L.delta)!=null?Co:""),I.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:L.turnId},p(I)}else if(L.contentType==="tool_input"){let U=(Vn=L.toolCallId)!=null?Vn:A.lastId;if(U){let I=P.get(U);I!=null&&I.toolCall&&(I.toolCall.chunks=(Jo=I.toolCall.chunks)!=null?Jo:[],I.toolCall.chunks.push((Mr=L.delta)!=null?Mr:""),p(I))}}}else if(Ve==="agent_turn_complete"){let U=L.turnId;if(U){let re=M.get(U);if(re!=null&&re.reasoning){re.reasoning.status="complete",re.reasoning.completedAt=Be(L.completedAt);let K=(Fo=re.reasoning.startedAt)!=null?Fo:Date.now();re.reasoning.durationMs=Math.max(0,((ya=re.reasoning.completedAt)!=null?ya:Date.now())-K),re.streaming=!1,p(re)}}let I=L.stopReason,X=m!=null?m:x;if(I&&X!==null){let re=L.turnId;(!re||(($n=X.agentMetadata)==null?void 0:$n.turnId)===re)&&(X.stopReason=I,p(X))}}else if(Ve==="agent_tool_start"){m&&(m.streaming=!1,p(m),m=null);let U=(ba=L.toolCallId)!=null?ba:`agent-tool-${d()}`;We(Z(L),U);let I=ce(U),X=(Js=I.toolCall)!=null?Js:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};X.name=(Ys=(va=L.toolName)!=null?va:L.name)!=null?Ys:X.name,X.status="running",L.parameters!==void 0&&(X.args=L.parameters),X.startedAt=Be((Ca=L.startedAt)!=null?Ca:L.timestamp),I.toolCall=X,I.streaming=!0,I.agentMetadata={executionId:L.executionId,iteration:L.iteration},p(I)}else if(Ve==="agent_tool_delta"){let U=(mt=L.toolCallId)!=null?mt:A.lastId;if(U){let I=(ts=P.get(U))!=null?ts:ce(U);I.toolCall&&(I.toolCall.chunks=(po=I.toolCall.chunks)!=null?po:[],I.toolCall.chunks.push((Vr=L.delta)!=null?Vr:""),I.toolCall.status="running",I.streaming=!0,p(I))}}else if(Ve==="agent_tool_complete"){let U=(Zs=L.toolCallId)!=null?Zs:A.lastId;if(U){let I=(ei=P.get(U))!=null?ei:ce(U);if(I.toolCall){I.toolCall.status="complete",L.result!==void 0&&(I.toolCall.result=L.result),typeof L.executionTime=="number"&&(I.toolCall.durationMs=L.executionTime),I.toolCall.completedAt=Be((wa=L.completedAt)!=null?wa:L.timestamp),I.streaming=!1,p(I);let X=Z(L);X&&A.byCall.delete(X)}}}else if(Ve==="agent_media"){let U=Array.isArray(L.media)?L.media:[],I=[];for(let X of U){if(!X||typeof X!="object")continue;let re=X,K=typeof re.type=="string"?re.type:void 0,Ae=typeof re.mediaType=="string"?re.mediaType.toLowerCase():"",Oe=null,at="";if(K==="media"){let tt=typeof re.data=="string"?re.data:void 0;if(!tt)continue;at=Ae.length>0?Ae:"application/octet-stream",Oe=`data:${at};base64,${tt}`}else if(K==="image-url"){let tt=typeof re.url=="string"?re.url:void 0;if(!tt)continue;at=Ae,Oe=tt}else if(K==="file-url"){let tt=typeof re.url=="string"?re.url:void 0;if(!tt)continue;at=Ae,Oe=tt}else continue;if(Oe)if(K==="image-url"||at.startsWith("image/"))I.push({type:"image",image:Oe,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))I.push({type:"audio",audio:Oe,mimeType:at});else if(at.startsWith("video/"))I.push({type:"video",video:Oe,mimeType:at});else{let tt=at||"application/octet-stream";I.push({type:"file",data:Oe,mimeType:tt,filename:$y(tt)})}}if(I.length>0){let X=d(),re=L.toolCallId,Ae={id:`agent-media-${typeof re=="string"&&re.length>0?`${re}-${X}`:String(X)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:X,agentMetadata:{executionId:L.executionId,iteration:L.iteration}};p(Ae);let Oe=m;Oe&&(Oe.streaming=!1,p(Oe)),m=null,C.current=null}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let U=`agent-reflection-${L.executionId}-${L.iteration}`,I={id:U,role:"assistant",content:(Yo=L.reflection)!=null?Yo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:d(),reasoning:{id:U,status:"complete",chunks:[(rs=L.reflection)!=null?rs:""]},agentMetadata:{executionId:L.executionId,iteration:L.iteration}};p(I)}else if(Ve==="agent_complete"){Ge&&(Ge.status=L.success?"complete":"error",Ge.completedAt=Be(L.completedAt),Ge.stopReason=L.stopReason);let U=m;U&&(U.streaming=!1,p(U)),r({type:"status",status:"idle"})}else if(Ve==="agent_error"){let U=typeof L.error=="string"?L.error:(os=(yn=L.error)==null?void 0:yn.message)!=null?os:"Agent execution error";L.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):r({type:"error",error:new Error(U)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let U=(ns=L.approvalId)!=null?ns:`approval-${d()}`,I={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:"pending",agentId:(as=Ge==null?void 0:Ge.agentId)!=null?as:"virtual",executionId:($r=(ss=L.executionId)!=null?ss:Ge==null?void 0:Ge.executionId)!=null?$r:"",toolName:(Sa=L.toolName)!=null?Sa:"",toolType:L.toolType,description:(Oo=L.description)!=null?Oo:`Execute ${(No=L.toolName)!=null?No:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};p(I)}else if(Ve==="step_await"&&L.awaitReason==="approval_required"){let U=(is=L.approvalId)!=null?is:`approval-${d()}`,I={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:"pending",agentId:(ti=Ge==null?void 0:Ge.agentId)!=null?ti:"virtual",executionId:(ds=(ls=L.executionId)!=null?ls:Ge==null?void 0:Ge.executionId)!=null?ds:"",toolName:(zn=L.toolName)!=null?zn:"",toolType:L.toolType,description:(oi=L.description)!=null?oi:`Execute ${(ri=L.toolName)!=null?ri:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};p(I)}else if(Ve==="agent_approval_complete"){let U=L.approvalId;if(U){let X={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:U,status:(ni=L.decision)!=null?ni:"approved",agentId:(ai=Ge==null?void 0:Ge.agentId)!=null?ai:"virtual",executionId:(bn=(si=L.executionId)!=null?si:Ge==null?void 0:Ge.executionId)!=null?bn:"",toolName:(vn=L.toolName)!=null?vn:"",description:(ii=L.description)!=null?ii:"",resolvedAt:Date.now()}};p(X)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let U=L.artifactType,I=String(L.id),X=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:I,artifactType:U,title:X,component:typeof L.component=="string"?L.component:void 0}),ge.set(I,{markdown:"",title:X}),!le.has(I)){le.add(I);let re={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:X,artifactType:U,status:"streaming"}})};J.set(I,re),p(re)}}else if(Ve==="artifact_delta"){let U=String(L.id),I=typeof L.delta=="string"?L.delta:String((cs=L.delta)!=null?cs:"");r({type:"artifact_delta",id:U,artDelta:I});let X=ge.get(U);X&&(X.markdown+=I)}else if(Ve==="artifact_update"){let U=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:U,component:typeof L.component=="string"?L.component:void 0})}else if(Ve==="artifact_complete"){let U=String(L.id);r({type:"artifact_complete",id:U});let I=J.get(U);if(I){I.streaming=!1;try{let X=JSON.parse((Cn=I.rawContent)!=null?Cn:"{}");if(X.props){X.props.status="complete";let re=ge.get(U);re!=null&&re.markdown&&(X.props.markdown=re.markdown)}I.rawContent=JSON.stringify(X)}catch{}ge.delete(U),p(I),J.delete(U)}}}else if(Ve==="transcript_insert"){let U=L.message;if(!U||typeof U!="object")continue;let I=String((li=U.id)!=null?li:`msg-${d()}`),X=U.role,K={id:I,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:d()};if(p(K),K.rawContent)try{let Ae=JSON.parse(K.rawContent),Oe=(ps=Ae==null?void 0:Ae.props)==null?void 0:ps.artifactId;typeof Oe=="string"&&le.add(Oe)}catch{}m=null,C.current=null,ee.delete(I),ie.delete(I)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let U=null;if(L.error instanceof Error)U=L.error;else if(Ve==="dispatch_error"){let I=(wn=L.message)!=null?wn:L.error;I!=null&&I!==""&&(U=new Error(String(I)))}else if(Ve==="step_error"||Ve==="flow_error"){let I=L.error;typeof I=="string"&&I!==""?U=new Error(I):I!=null&&typeof I=="object"&&"message"in I&&(U=new Error(String((us=I.message)!=null?us:I)))}else Ve==="error"&&L.error!=null&&L.error!==""&&(U=new Error(String(L.error)));if(U){r({type:"error",error:U});let I=m;I&&I.streaming&&(I.streaming=!1,p(I)),r({type:"status",status:"idle"})}}}}}Ze.length=0};;){let{done:V,value:j}=await n.read();if(V)break;s+=a.decode(j,{stream:!0});let he=s.split(`
11
11
 
12
12
  `);s=(Wt=he.pop())!=null?Wt:"";for(let Xe of he){let et=Xe.split(`
13
- `),qe="message",Ne="";for(let Jt of et)Jt.startsWith("event:")?qe=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(Ne+=Jt.replace("data:","").trim());if(!Ne)continue;let Pt;try{Pt=JSON.parse(Ne)}catch(Jt){r({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let Gt=qe!=="message"?qe:(ur=Pt.type)!=null?ur:"message";if((Eo=this.onSSEEvent)==null||Eo.call(this,Gt,Pt),this.parseSSEEvent){C.current=m;let Jt=await this.handleCustomSSEEvent(Pt,r,C,p,d,T);if(C.current&&C.current!==m&&(m=C.current),Jt)continue}Je.push(Gt,Pt),pe()}}Je.flushPending(),pe(),Je.destroy()}};function Og(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Na(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function na(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Hi="[Image]";function _g(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ug(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function qg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Vg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Es(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 zg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function jg(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Gg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],jy=["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=[...Gg,...jy];function Gy(e){return Gg.includes(e)||e.startsWith("image/")}function Bi(e){return Gy(e.type)}async function Kg(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 Xg(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 Ky(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Qg(e,t){let r=Ky(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 Di=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 Jg=16e3,Xy=24e3,Qy=4096,Jy=1380533830;function Yy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Jy?new Uint8Array(e,44):new Uint8Array(e)}function Zy(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var ks=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let d=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Jg,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){d.getTracks().forEach(C=>C.stop());return}this.mediaStream=d;let u=window.AudioContext||window.webkitAudioContext,g=new u({sampleRate:Jg});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let p=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new Di(Xy);if(n!==this.callGeneration){p.destroy(),d.getTracks().forEach(C=>C.stop()),g.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${Zy(o)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(m,["runtype.bearer",r]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(g,d,x,n))},x.onmessage=C=>this.handleMessage(C,n),x.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=C=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(C.code!==1e3){let T=C.code?` (code ${C.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(d){throw this.cleanup(),this.emitError(d),this.emitStatus("error"),d}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(Qy,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),d=new Int16Array(c.length);for(let u=0;u<c.length;u++){let g=Math.max(-1,Math.min(1,c[u]));d[u]=g<0?g*32768:g*32767}o.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,r){if(r!==this.callGeneration||!this.playback)return;let o=Yy(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 aa=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(c=>c[0]).map(c=>c.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(c=>c({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Rn(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ks(e.runtype);case"browser":if(!aa.isSupported())throw new Error("Browser speech recognition not supported");return new aa(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 Fi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Rn({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Rn({type:"runtype",runtype:e.runtype});if(aa.isSupported())return Rn({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ls(e){try{return Fi(e),!0}catch{return!1}}function Oa(e){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(a=>a.name===o);if(n)return n}return(r=e.find(o=>o.lang.startsWith("en")))!=null?r:e[0]}var In=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,r){var s;if(!e.isSupported()){(s=r.onError)==null||s.call(r,new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let i=a.find(c=>c.name===t.voice);i&&(n.voice=i)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):Oa(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var d,u;let c=i.error;c==="canceled"||c==="interrupted"?(d=r.onEnd)==null||d.call(r):(u=r.onError)==null||u.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var sa=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 nd(e){if(!e)return"";let t=eb(e);return Yg(t!==null?t:e)}function eb(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 Yg(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,`
13
+ `),qe="message",Ne="";for(let Jt of et)Jt.startsWith("event:")?qe=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(Ne+=Jt.replace("data:","").trim());if(!Ne)continue;let Pt;try{Pt=JSON.parse(Ne)}catch(Jt){r({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let Gt=qe!=="message"?qe:(ur=Pt.type)!=null?ur:"message";if((Eo=this.onSSEEvent)==null||Eo.call(this,Gt,Pt),this.parseSSEEvent){C.current=m;let Jt=await this.handleCustomSSEEvent(Pt,r,C,p,d,T);if(C.current&&C.current!==m&&(m=C.current),Jt)continue}Je.push(Gt,Pt),pe()}}Je.flushPending(),pe(),Je.destroy()}};function Ug(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Oa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function aa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Bi="[Image]";function qg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Vg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function $g(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function zg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ks(e){return{type:"text",text:e}}function jg(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function Gg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Kg(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Xg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Gy=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],an=[...Xg,...Gy];function Ky(e){return Xg.includes(e)||e.startsWith("image/")}function Di(e){return Ky(e.type)}async function Qg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;Di(e)?t({type:"image",image:n,mimeType:e.type,alt:e.name}):t({type:"file",data:n,mimeType:e.type,filename:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Jg(e,t=an,r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Xy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Yg(e,t){let r=Xy(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}var Fi=class{constructor(t=24e3,r={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var n;this.sampleRate=t;let o=Math.max(0,(n=r.prebufferMs)!=null?n:0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let o=r.AudioContext||r.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let n=new Uint8Array(this.remainder.length+t.length);n.set(this.remainder),n.set(t,this.remainder.length),r=n,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let o=this.pcmToFloat32(r);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let r of t)this.scheduleSamples(r)}scheduleSamples(t){if(t.length===0)return;let r=this.ensureContext(),o=r.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let n=r.createBufferSource();n.buffer=o,n.connect(r.destination);let a=r.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),n.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(n),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of s)i()}n.onended=()=>{let s=this.activeSources.indexOf(n);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),o=new Float32Array(r),n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<r;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var Zg=16e3,Qy=24e3,Jy=4096,Yy=1380533830;function Zy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Yy?new Uint8Array(e,44):new Uint8Array(e)}function eb(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Ls=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let d=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Zg,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){d.getTracks().forEach(C=>C.stop());return}this.mediaStream=d;let u=window.AudioContext||window.webkitAudioContext,g=new u({sampleRate:Zg});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let p=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new Fi(Qy);if(n!==this.callGeneration){p.destroy(),d.getTracks().forEach(C=>C.stop()),g.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${eb(o)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(m,["runtype.bearer",r]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(g,d,x,n))},x.onmessage=C=>this.handleMessage(C,n),x.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=C=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(C.code!==1e3){let T=C.code?` (code ${C.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(d){throw this.cleanup(),this.emitError(d),this.emitStatus("error"),d}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(Jy,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),d=new Int16Array(c.length);for(let u=0;u<c.length;u++){let g=Math.max(-1,Math.min(1,c[u]));d[u]=g<0?g*32768:g*32767}o.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,r){if(r!==this.callGeneration||!this.playback)return;let o=Zy(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(r=>r(t))}emitError(t){this.errorCallbacks.forEach(r=>r(t))}emitTranscript(t,r,o){this.transcriptCallbacks.forEach(n=>n(t,r,o))}emitMetrics(t){this.metricsCallbacks.forEach(r=>r(t))}};var sa=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(c=>c[0]).map(c=>c.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(c=>c({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Rn(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ls(e.runtype);case"browser":if(!sa.isSupported())throw new Error("Browser speech recognition not supported");return new sa(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let r=typeof t=="function"?t():t;if(!r||typeof r.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return r}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ni(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Rn({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Rn({type:"runtype",runtype:e.runtype});if(sa.isSupported())return Rn({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ps(e){try{return Ni(e),!0}catch{return!1}}function _a(e){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(a=>a.name===o);if(n)return n}return(r=e.find(o=>o.lang.startsWith("en")))!=null?r:e[0]}var In=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,r){var s;if(!e.isSupported()){(s=r.onError)==null||s.call(r,new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let i=a.find(c=>c.name===t.voice);i&&(n.voice=i)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):_a(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var d,u;let c=i.error;c==="canceled"||c==="interrupted"?(d=r.onEnd)==null||d.call(r):(u=r.onError)==null||u.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var ia=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,r;return(r=(t=this.engine)==null?void 0:t.supportsPause)!=null?r:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,r){var o,n;if(this.activeId===t){if(this.state==="playing"){(o=this.engine)!=null&&o.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(n=this.engine)==null||n.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,r)}async play(t,r){var n;let o=++this.generation;(n=this.engine)==null||n.stop(),this.set(t,"loading");try{if(!this.engine){let a=await this.resolveEngine();if(o!==this.generation)return;if(!a){this.set(null,"idle");return}this.engine=a}this.engine.speak(r,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,r;this.stop(),(r=(t=this.engine)==null?void 0:t.destroy)==null||r.call(t),this.engine=null,this.listeners.clear()}set(t,r){this.activeId=r==="idle"?null:t,this.state=r;for(let o of this.listeners)o(this.activeId,this.state)}};function ad(e){if(!e)return"";let t=tb(e);return eh(t!==null?t:e)}function tb(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function eh(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
14
14
  `),t=t.replace(/\n{2,}/g,`
15
- `),t.trim()}var ad=null,Zg=e=>{ad=e},sd=()=>ad?ad():import("./runtype-tts-entry");var tb=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function rb(e,t){return tb.some(r=>e[r]!==t[r])}function eh(e,t){let r=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(r);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${o}
15
+ `),t.trim()}var sd=null,th=e=>{sd=e},id=()=>sd?sd():import("./runtype-tts-entry");var rb=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function ob(e,t){return rb.some(r=>e[r]!==t[r])}function rh(e,t){let r=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(r);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${o}
16
16
 
17
- _Details: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]}),th=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,rh=e=>ea(e)||e===Mo,_a=class{constructor(t={},r){this.config=t;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new sa(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,d,u,g;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall,m=!!(p!=null&&p.name)&&(ea(p.name)||p.name===Mo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((d=this.agentExecution)==null?void 0:d.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new oa(t),this.wireDefaultWebMcpConfirm();for(let a of(n=t.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var n,a,s,i,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let r=(n=t.host)!=null?n:this.config.apiUrl,o=(c=t.agentId)!=null?c:(i=(s=(a=this.config.voiceRecognition)==null?void 0:a.provider)==null?void 0:s.runtype)==null?void 0:i.agentId;!r||!o||!this.config.clientToken||sd().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ls((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=In.isSupported()?new In({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(o=t.host)!=null?o:this.config.apiUrl,d=(i=t.agentId)!=null?i:(s=(a=(n=this.config.voiceRecognition)==null?void 0:n.provider)==null?void 0:a.runtype)==null?void 0:s.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(c&&d&&u)return sd().then(({RuntypeSpeechEngine:p,FallbackSpeechEngine:m})=>{let x=new p({host:c,agentId:d,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&r?new m(x,r,{onFallback:C=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${C.message}`)}):x});if(g&&r)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),r}return r}setupVoice(t){var r,o;try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Rn(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,c,d)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:c,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,d;(d=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||d.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,d;this.voiceStatus=i,this.voiceActive=i==="listening",(d=(c=this.callbacks).onVoiceStatusChanged)==null||d.call(c,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,o,n,a,s,i,c,d,u,g;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:(a=(n=t.runtype)==null?void 0:n.clientToken)!=null?a:this.config.clientToken,host:(i=(s=t.runtype)==null?void 0:s.host)!=null?i:this.config.apiUrl,voiceId:(c=t.runtype)==null?void 0:c.voiceId,createPlaybackEngine:(d=t.runtype)==null?void 0:d.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((u=t.browser)==null?void 0:u.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(r=(t=this.callbacks).onError)==null||r.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r={...this.config,...t};if(!rb(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 oa(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:d=!1,voiceProcessing:u,rawContent:g}=t,m={id:s!=null?s:r==="user"?Na():r==="assistant"?na():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:d,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:d,sequence:u,streaming:g=!1,voiceProcessing:p,rawContent:m}=o,C={id:c!=null?c:n==="user"?Na():n==="assistant"?na():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:d!=null?d:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};r.push(C)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,d={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var d,u,g,p,m;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(d=this.abortController)==null||d.abort(),this.abortWebMcpResolves();let n=Na(),a=na(),s={id:n,role:"user",content:o||Hi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let T=eh(x,this.config.errorMessage);if(T){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,x):(m=(p=this.callbacks).onError)==null||m.call(p,new Error(String(x))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort();let t=na();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let g=eh(d,this.config.errorMessage);if(g){let p={id:t,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(p)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,d):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(d))))}}async connectStream(t,r){var n,a,s;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(n=this.abortController)==null||n.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var u,g,p,m,x;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(C=>C.id===n),i={id:n,role:"assistant",content:"",createdAt:(u=s==null?void 0:s.createdAt)!=null?u:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,d=c&&typeof c=="object"?c.onDecision:void 0;try{let C;if(d?C=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):C=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),C){let T=null;if(C instanceof Response){if(!C.ok){let E=await C.json().catch(()=>null);throw new Error((p=E==null?void 0:E.error)!=null?p:`Approval request failed: ${C.status}`)}T=C.body}else C instanceof ReadableStream&&(T=C);T?await this.connectStream(T,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(C){let T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(x=(m=this.callbacks).onError)==null||x.call(m,C instanceof Error?C:new Error(String(C)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var u,g,p,m,x,C,T,E,M,P,y,w;let o=this.messages.find(b=>b.id===t.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let n=(g=t.agentMetadata)==null?void 0:g.executionId,a=(p=t.toolCall)==null?void 0:p.name;if(!n||!a){(x=(m=this.callbacks).onError)==null||x.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let b=(C=t.toolCall)==null?void 0:C.args,A=Array.isArray(b==null?void 0:b.questions)?b.questions:[];if(A.length===1){let H=typeof((T=A[0])==null?void 0:T.question)=="string"?A[0].question:"";H&&(s={[H]:r})}}this.markAskUserQuestionResolved(t,s),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(M=t.toolCall)==null?void 0:M.args,d=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(d.length===0){let b=typeof r=="string"?r:Object.entries(r).map(([A,H])=>`${A}: ${Array.isArray(H)?H.join(", "):H}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:b,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let b=s!=null?s:{};d.forEach((A,H)=>{let W=typeof(A==null?void 0:A.question)=="string"?A.question:"";if(!W)return;let k=b[W],N=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${H}`,role:"assistant",content:W,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${H}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let b=await this.client.resumeFlow(n,{[a]:r});if(!b.ok){let A=await b.json().catch(()=>null);throw new Error((P=A==null?void 0:A.error)!=null?P:`Resume failed: ${b.status}`)}b.body?await this.connectStream(b.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(b){let A=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,A||(w=(y=this.callbacks).onError)==null||w.call(y,b instanceof Error?b:new Error(String(b)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==Mo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,d,u,g;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async p=>{var w,b,A,H,W,k,N;let m=(w=p.toolCall)==null?void 0:w.name,x=(b=p.toolCall)==null?void 0:b.id;if(!m||!x)return null;let C=`${t}:${x}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(C),o.push(C);let T=this.markWebMcpToolRunning(p),E=(H=(A=p.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?H:m;if(m===Mo)return{dedupeKey:C,resumeKey:E,output:Yl(),toolMessage:p,startedAt:T,completedAt:Date.now()};let M=new AbortController;this.webMcpResolveControllers.add(M),n.push(M);let P=this.client.executeWebMcpToolCall(m,(W=p.toolCall)==null?void 0:W.args,M.signal),y;if(!P)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await P}catch(q){let Z=q instanceof Error&&(q.name==="AbortError"||q.message.includes("aborted")||q.message.includes("abort"));return Z||(N=(k=this.callbacks).onError)==null||N.call(k,q instanceof Error?q:new Error(String(q))),this.markWebMcpToolComplete(p,Ps(Z?"Aborted by cancel()":th(q)),T),this.webMcpInflightKeys.delete(C),null}return M.signal.aborted?(this.markWebMcpToolComplete(p,Ps("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:E,output:y,toolMessage:p,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=s.filter(x=>x!==null),i.length===0)return;let p={};for(let x of i)p[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,p,{signal:a.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((c=x==null?void 0:x.error)!=null?c:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((d=x.toolMessage.toolCall)==null?void 0:d.name)===Mo?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,p instanceof Error?p:new Error(String(p)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,Ps("Aborted by cancel()"),x.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of n)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,C,T,E,M,P,y,w,b,A,H,W;let r=(x=t.agentMetadata)==null?void 0:x.executionId,o=(C=t.toolCall)==null?void 0:C.name,n=(T=t.toolCall)==null?void 0:T.id;if(!r){(M=(E=this.callbacks).onError)==null||M.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let k=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);try{await this.resumeWithToolOutput(r,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(k)}catch(N){(y=(P=this.callbacks).onError)==null||y.call(P,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(k)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let d=o===Mo,u=(w=t.toolCall)==null?void 0:w.args,g=d?null:this.client.executeWebMcpToolCall(o,u,c),p="execute",m=s;try{let k;if(d?k=Yl():g?k=await g:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),c.aborted){this.markWebMcpToolComplete(t,Ps("Aborted by cancel()"),s);return}let N=(A=(b=t.agentMetadata)==null?void 0:b.webMcpToolCallId)!=null?A:o;p="resume",await this.resumeWithToolOutput(r,N,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,k,s,m,d?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(k){let N=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(p==="execute"||N||c.aborted)&&this.markWebMcpToolComplete(t,Ps(N||c.aborted?"Aborted by cancel()":th(k)),s),N||(W=(H=this.callbacks).onError)==null||W.call(H,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,o,n){var s,i;let a=await this.client.resumeFlow(t,{[r]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let c=await a.json().catch(()=>null);throw new Error((s=c==null?void 0:c.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var n;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}let o={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(n=t.props)!=null?n:{}};return this.artifacts.set(r,o),this.selectedArtifactId=r,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let n=nd(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Oa(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=nd(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var u,g,p,m,x,C,T,E,M,P,y,w,b,A,H;if(a!==o)return n;let s={...n,...r};if(((u=n.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=n.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(p=s.agentMetadata)!=null?p:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let W=n.approval,k=r.approval;s.approval={...W,...k,executionId:k.executionId||W.executionId,toolName:k.toolName||W.toolName,description:k.description||W.description,toolType:(m=k.toolType)!=null?m:W.toolType,reason:(x=k.reason)!=null?x:W.reason,parameters:(C=k.parameters)!=null?C:W.parameters}}let i=(T=r.toolCall)==null?void 0:T.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,d=(M=r.toolCall)==null?void 0:M.id;if(i&&rh(i)&&c&&d&&((P=r.agentMetadata)==null?void 0:P.awaitingLocalTool)===!0){let W=`${c}:${d}`,k=this.webMcpInflightKeys.has(W),N=this.webMcpResolvedKeys.has(W),q=(y=n.toolCall)==null?void 0:y.name,Z=((w=n.agentMetadata)==null?void 0:w.executionId)===c&&((b=n.toolCall)==null?void 0:b.id)===d&&q!==void 0&&rh(q)&&((A=n.toolCall)==null?void 0:A.status)==="complete";(k||N||Z)&&(s.agentMetadata={...(H=s.agentMetadata)!=null?H:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,o)=>{var c,d;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(d=o.sequence)!=null?d:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var id=[["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 ld=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var dd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var cd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var pd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var ud=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var fd=[["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 md=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var gd=[["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 hd=[["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 xd=[["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 yd=[["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 bd=[["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 vd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Cd=[["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 wd=[["path",{d:"M20 6 9 17l-5-5"}]];var Sd=[["path",{d:"m6 9 6 6 6-6"}]];var Ad=[["path",{d:"m15 18-6-6 6-6"}]];var Md=[["path",{d:"m9 18 6-6-6-6"}]];var Td=[["path",{d:"m18 15-6-6-6 6"}]];var Ni=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var Oi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Ed=[["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 kd=[["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 Ld=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Pd=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var Rd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Id=[["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 Wd=[["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 _i=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Ui=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Hd=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Bd=[["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 Dd=[["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 Fd=[["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 Nd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Od=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var _d=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var Ud=[["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 qd=[["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 Vd=[["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 $d=[["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 zd=[["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 qi=[["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 jd=[["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 Gd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var Kd=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Xd=[["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 Qd=[["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 Jd=[["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 Vi=[["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 Yd=[["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 Zd=[["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 ec=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var tc=[["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 rc=[["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 $i=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var oc=[["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 nc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var ac=[["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 sc=[["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 ic=[["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 lc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var dc=[["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 cc=[["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 pc=[["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 uc=[["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 fc=[["path",{d:"M5 12h14"}]];var mc=[["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 gc=[["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 hc=[["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 xc=[["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 yc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var bc=[["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 vc=[["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 Cc=[["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 wc=[["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 Ac=[["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 Mc=[["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 Tc=[["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 Ec=[["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 kc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Lc=[["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 Pc=[["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 Rc=[["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 Ic=[["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 Wc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var zi=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Hc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Bc=[["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 Dc=[["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 Fc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var ji=[["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 Nc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Oc=[["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 _c=[["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 Uc=[["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 qc=[["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 Vc=[["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 $c=[["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 zc=[["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 jc=[["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 Gc=[["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 Gi=[["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 Kc=[["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 Xc=[["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 Qc=[["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 Jc=[["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 Yc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var Zc=[["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 ep=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var tp=[["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 ob={activity:id,"arrow-down":ld,"arrow-up":ud,"arrow-up-right":pd,bot:xd,"chevron-down":Sd,"chevron-up":Td,"chevron-right":Md,"chevron-left":Ad,check:wd,clipboard:kd,"clipboard-copy":Ed,copy:Pd,file:_d,"file-code":Fd,"file-spreadsheet":Nd,"file-text":Od,"image-plus":Yd,loader:oc,"loader-circle":$i,mic:pc,paperclip:xc,"refresh-cw":Mc,search:kc,send:Lc,"shield-alert":Ic,"shield-check":Wc,"shield-x":zi,square:Nc,"thumbs-down":Vc,"thumbs-up":$c,upload:Xc,"volume-2":Jc,x:ep,user:Qc,mail:ac,phone:Cc,calendar:vd,clock:Ld,building:yd,"map-pin":sc,lock:nc,key:tc,"credit-card":Rd,"at-sign":fd,hash:Kd,globe:Gd,link:rc,"circle-check":Ni,"circle-x":Oi,"triangle-alert":Gi,info:ec,ban:md,shield:Hc,"arrow-left":dd,"arrow-right":cd,"external-link":Bd,ellipsis:Ui,"ellipsis-vertical":_i,menu:lc,house:Vi,plus:Sc,minus:fc,pencil:bc,trash:Gc,"trash-2":jc,save:Ec,download:Wd,share:Rc,funnel:qi,settings:Pc,"rotate-cw":Tc,maximize:ic,minimize:uc,"shopping-cart":Dc,"shopping-bag":Bc,package:hc,truck:Kc,tag:qc,gift:jd,receipt:Ac,wallet:Zc,store:_c,"dollar-sign":Id,percent:vc,play:wc,pause:yc,"volume-x":Yc,camera:Cd,image:Zd,film:qd,headphones:Xd,"message-circle":dc,"message-square":cc,bell:gd,heart:Qd,star:Oc,eye:Dd,"eye-off":Hd,bookmark:hd,"calendar-days":bd,history:Jd,timer:zc,folder:zd,"folder-open":$d,files:Ud,sparkles:ji,zap:tp,sun:Uc,moon:gc,flag:Vd,monitor:mc,smartphone:Fc},ve=(e,t=24,r="currentColor",o=2)=>{let n=ob[e];return n?nb(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 nb(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([d,u])=>{d!=="stroke"&&c.setAttribute(d,String(u))}),n.appendChild(c)}),n}var Ki={allowedTypes:an,maxFileSize:10*1024*1024,maxFiles:4};function ab(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function sb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var ia=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ki.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ki.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Ki.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:Ki.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,o,n,a,s,i,c;if(t.length){for(let d of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,d,"count");continue}let u=Xg(d,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(n=u.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,d,g);continue}try{let g=await Kg(d),p=Bi(d)?URL.createObjectURL(d):null,m={id:ab(),file:d,previewUrl:p,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=Bi(t.file),o=S("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",r&&t.previewUrl){let s=S("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=S("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=sb(t.file.type),c=ve(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let d=S("span");d.textContent=Qg(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",s.appendChild(d),o.appendChild(s)}let n=S("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=ve("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var oh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Rs(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];oh(a)&&oh(n)?r[o]=Rs(a,n):r[o]=n}return r}var oo="min(440px, calc(100vw - 24px))",Xi="440px",ib={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:oo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},_t={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:ib,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 nh(e,t){if(!(!e&&!t))return e?t?Rs(e,t):e:t}function Qi(e){var t,r,o,n,a,s,i,c,d,u,g,p,m,x,C,T,E,M,P,y,w;return e?{..._t,...e,theme:nh(_t.theme,e.theme),darkTheme:nh(_t.darkTheme,e.darkTheme),launcher:{..._t.launcher,...e.launcher,dock:{...(t=_t.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=_t.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{..._t.copy,...e.copy},sendButton:{..._t.sendButton,...e.sendButton},statusIndicator:{..._t.statusIndicator,...e.statusIndicator},voiceRecognition:{..._t.voiceRecognition,...e.voiceRecognition},features:(()=>{var de,J,le,ge,ue,G,ce,Be,ne,ee;let b=(de=_t.features)==null?void 0:de.artifacts,A=(J=e.features)==null?void 0:J.artifacts,H=(le=_t.features)==null?void 0:le.scrollToBottom,W=(ge=e.features)==null?void 0:ge.scrollToBottom,k=(ue=_t.features)==null?void 0:ue.scrollBehavior,N=(G=e.features)==null?void 0:G.scrollBehavior,q=(ce=_t.features)==null?void 0:ce.streamAnimation,Z=(Be=e.features)==null?void 0:Be.streamAnimation,me=(ne=_t.features)==null?void 0:ne.askUserQuestion,Ke=(ee=e.features)==null?void 0:ee.askUserQuestion,Ce=b===void 0&&A===void 0?void 0:{...b,...A,layout:{...b==null?void 0:b.layout,...A==null?void 0:A.layout}},Ie=H===void 0&&W===void 0?void 0:{...H,...W},Ue=k===void 0&&N===void 0?void 0:{...k,...N},Te=q===void 0&&Z===void 0?void 0:{...q,...Z},We=me===void 0&&Ke===void 0?void 0:{...me,...Ke,styles:{...me==null?void 0:me.styles,...Ke==null?void 0:Ke.styles}};return{..._t.features,...e.features,...Ie!==void 0?{scrollToBottom:Ie}:{},...Ue!==void 0?{scrollBehavior:Ue}:{},...Ce!==void 0?{artifacts:Ce}:{},...Te!==void 0?{streamAnimation:Te}:{},...We!==void 0?{askUserQuestion:We}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:_t.suggestionChips,suggestionChipsConfig:{..._t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{..._t.layout,...e.layout,header:{...(s=_t.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=_t.layout)==null?void 0:c.messages,...(d=e.layout)==null?void 0:d.messages,avatar:{...(g=(u=_t.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(p=e.layout)==null?void 0:p.messages)==null?void 0:m.avatar},timestamp:{...(C=(x=_t.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(E=(T=e.layout)==null?void 0:T.messages)==null?void 0:E.timestamp}},slots:{...(M=_t.layout)==null?void 0:M.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{..._t.markdown,...e.markdown,options:{...(y=_t.markdown)==null?void 0:y.options,...(w=e.markdown)==null?void 0:w.options}},messageActions:{..._t.messageActions,...e.messageActions}}:_t}var rp={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"}},op={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},np={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:oo,maxWidth:Xi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Ua(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Ua(e,o):o}function Ji(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let c=Ua(e,s);c!==void 0&&(t[i]={path:i,value:c,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function ap(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 ah(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]=ah(a,n):r[o]=n}return r}function lb(e,t){return t?ah(e,t):e}function qa(e,t={}){var n,a,s,i,c,d,u,g,p,m,x,C,T;let r={palette:rp,semantic:op,components:np},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(d=e==null?void 0:e.palette)==null?void 0:d.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...r.semantic.colors.interactive,...(p=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:p.interactive},feedback:{...r.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...r.semantic.typography,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:lb(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=ap(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(M=>M.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Yi(e){var C,T,E,M,P,y,w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de,J,le,ge,ue,G,ce,Be,ne,ee,ie,vt,Lt,gt,_e,be,Ze,Y,pe,Me,Je,Ge,ke,je,Cr,Wt,ur,Eo,V,j,he,Xe,et,qe,Ne,Pt,Gt,Jt,Pr,z,Ht,oe,we,De,At,ar,sr,wr,Ft,ot,Dt,lt,Yt,so,Rr,ir,Ur,ko,yt,jr,Lo,zo,yo,ht,Nn,Po,On,qr,ma,cn,jo,pn,un,_n,Un,fn,Ct,Gr,Kr,Ir,Mt,io,lo,Xr,mn,Go,gn,Qr,Nt,Wr,co,hn,Ko,xn,Ro,Jr;let t=Ji(e),r={};for(let[xe,dt]of Object.entries(t)){let tr=xe.replace(/\./g,"-");r[`--persona-${tr}`]=dt.value}r["--persona-primary"]=(C=r["--persona-semantic-colors-primary"])!=null?C:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(T=r["--persona-semantic-colors-secondary"])!=null?T:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(E=r["--persona-semantic-colors-accent"])!=null?E:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(M=r["--persona-semantic-colors-surface"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(P=r["--persona-semantic-colors-background"])!=null?P:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(w=r["--persona-semantic-colors-text"])!=null?w:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(b=r["--persona-semantic-colors-text-muted"])!=null?b:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(A=r["--persona-semantic-colors-text-inverse"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(H=r["--persona-semantic-colors-border"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(W=r["--persona-semantic-colors-divider"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(k=r["--persona-components-voice-recording-indicator"])!=null?k:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(N=r["--persona-components-voice-recording-background"])!=null?N:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(q=r["--persona-components-voice-processing-icon"])!=null?q:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Z=r["--persona-components-voice-speaking-icon"])!=null?Z:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Ke=r["--persona-components-approval-requested-border"])!=null?Ke:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(Ce=r["--persona-components-approval-requested-text"])!=null?Ce:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Ie=r["--persona-components-approval-requested-shadow"])!=null?Ie:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-approval-approve-bg"]=(Ue=r["--persona-components-approval-approve-background"])!=null?Ue:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Te=r["--persona-components-approval-deny-background"])!=null?Te:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(We=r["--persona-components-attachment-image-background"])!=null?We:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(de=r["--persona-components-attachment-image-border"])!=null?de:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(J=r["--persona-semantic-typography-fontFamily"])!=null?J:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(le=r["--persona-semantic-typography-fontSize"])!=null?le:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(ge=r["--persona-semantic-typography-fontWeight"])!=null?ge:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(ue=r["--persona-semantic-typography-lineHeight"])!=null?ue:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(G=r["--persona-palette-radius-sm"])!=null?G:"0.125rem",r["--persona-radius-md"]=(ce=r["--persona-palette-radius-md"])!=null?ce:"0.375rem",r["--persona-radius-lg"]=(Be=r["--persona-palette-radius-lg"])!=null?Be:"0.5rem",r["--persona-radius-xl"]=(ne=r["--persona-palette-radius-xl"])!=null?ne:"0.75rem",r["--persona-radius-full"]=(ee=r["--persona-palette-radius-full"])!=null?ee:"9999px",r["--persona-launcher-radius"]=(vt=(ie=r["--persona-components-launcher-borderRadius"])!=null?ie:r["--persona-palette-radius-full"])!=null?vt:"9999px",r["--persona-launcher-bg"]=(Lt=r["--persona-components-launcher-background"])!=null?Lt:r["--persona-primary"],r["--persona-launcher-fg"]=(gt=r["--persona-components-launcher-foreground"])!=null?gt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(_e=r["--persona-components-launcher-border"])!=null?_e:r["--persona-border"],r["--persona-button-primary-bg"]=(be=r["--persona-components-button-primary-background"])!=null?be:r["--persona-primary"],r["--persona-button-primary-fg"]=(Ze=r["--persona-components-button-primary-foreground"])!=null?Ze:r["--persona-text-inverse"],r["--persona-button-radius"]=(pe=(Y=r["--persona-components-button-primary-borderRadius"])!=null?Y:r["--persona-palette-radius-full"])!=null?pe:"9999px",r["--persona-panel-radius"]=(Je=(Me=r["--persona-components-panel-borderRadius"])!=null?Me:r["--persona-radius-xl"])!=null?Je:"0.75rem",r["--persona-panel-border"]=(Ge=r["--persona-components-panel-border"])!=null?Ge:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(je=(ke=r["--persona-components-panel-shadow"])!=null?ke:r["--persona-palette-shadows-xl"])!=null?je:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(Cr=r["--persona-components-launcher-shadow"])!=null?Cr:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(ur=(Wt=r["--persona-components-input-borderRadius"])!=null?Wt:r["--persona-radius-lg"])!=null?ur:"0.5rem",r["--persona-message-user-radius"]=(V=(Eo=r["--persona-components-message-user-borderRadius"])!=null?Eo:r["--persona-radius-lg"])!=null?V:"0.5rem",r["--persona-message-assistant-radius"]=(he=(j=r["--persona-components-message-assistant-borderRadius"])!=null?j:r["--persona-radius-lg"])!=null?he:"0.5rem",r["--persona-header-bg"]=(Xe=r["--persona-components-header-background"])!=null?Xe:r["--persona-surface"],r["--persona-header-border"]=(et=r["--persona-components-header-border"])!=null?et:r["--persona-divider"],r["--persona-header-icon-bg"]=(qe=r["--persona-components-header-iconBackground"])!=null?qe:r["--persona-primary"],r["--persona-header-icon-fg"]=(Ne=r["--persona-components-header-iconForeground"])!=null?Ne:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Pt=r["--persona-components-header-titleForeground"])!=null?Pt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Gt=r["--persona-components-header-subtitleForeground"])!=null?Gt:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(Jt=r["--persona-components-header-actionIconForeground"])!=null?Jt:r["--persona-muted"];let o=(Pr=e.components)==null?void 0:Pr.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(z=e.components)==null?void 0:z.introCard;r["--persona-intro-card-bg"]=(Ht=r["--persona-components-introCard-background"])!=null?Ht:r["--persona-surface"],r["--persona-intro-card-radius"]=(oe=r["--persona-components-introCard-borderRadius"])!=null?oe:"1rem",r["--persona-intro-card-padding"]=(we=r["--persona-components-introCard-padding"])!=null?we:"1.5rem",r["--persona-intro-card-shadow"]=(At=(De=n==null?void 0:n.shadow)!=null?De:r["--persona-components-introCard-shadow"])!=null?At:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(ar=r["--persona-components-input-background"])!=null?ar:r["--persona-surface"],r["--persona-input-placeholder"]=(sr=r["--persona-components-input-placeholder"])!=null?sr:r["--persona-text-muted"],r["--persona-message-user-bg"]=(wr=r["--persona-components-message-user-background"])!=null?wr:r["--persona-accent"],r["--persona-message-user-text"]=(Ft=r["--persona-components-message-user-text"])!=null?Ft:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(ot=r["--persona-components-message-user-shadow"])!=null?ot:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Dt=r["--persona-components-message-assistant-background"])!=null?Dt:r["--persona-surface"],r["--persona-message-assistant-text"]=(lt=r["--persona-components-message-assistant-text"])!=null?lt:r["--persona-text"],r["--persona-message-assistant-border"]=(Yt=r["--persona-components-message-assistant-border"])!=null?Yt:r["--persona-border"],r["--persona-message-assistant-shadow"]=(so=r["--persona-components-message-assistant-shadow"])!=null?so:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(ir=(Rr=r["--persona-components-scrollToBottom-background"])!=null?Rr:r["--persona-button-primary-bg"])!=null?ir:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(ko=(Ur=r["--persona-components-scrollToBottom-foreground"])!=null?Ur:r["--persona-button-primary-fg"])!=null?ko:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(yt=r["--persona-components-scrollToBottom-border"])!=null?yt:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(jr=r["--persona-components-scrollToBottom-size"])!=null?jr:"40px",r["--persona-scroll-to-bottom-radius"]=(yo=(zo=(Lo=r["--persona-components-scrollToBottom-borderRadius"])!=null?Lo:r["--persona-button-radius"])!=null?zo:r["--persona-radius-full"])!=null?yo:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Nn=(ht=r["--persona-components-scrollToBottom-shadow"])!=null?ht:r["--persona-palette-shadows-sm"])!=null?Nn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Po=r["--persona-components-scrollToBottom-padding"])!=null?Po:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(On=r["--persona-components-scrollToBottom-gap"])!=null?On:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(ma=(qr=r["--persona-components-scrollToBottom-fontSize"])!=null?qr:r["--persona-palette-typography-fontSize-sm"])!=null?ma:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(cn=r["--persona-components-scrollToBottom-iconSize"])!=null?cn:"14px",r["--persona-tool-bubble-shadow"]=(jo=r["--persona-components-toolBubble-shadow"])!=null?jo:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(pn=r["--persona-components-reasoningBubble-shadow"])!=null?pn:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(un=r["--persona-components-composer-shadow"])!=null?un:"none",r["--persona-md-inline-code-bg"]=(_n=r["--persona-components-markdown-inlineCode-background"])!=null?_n:r["--persona-container"],r["--persona-md-inline-code-color"]=(Un=r["--persona-components-markdown-inlineCode-foreground"])!=null?Un:r["--persona-text"],r["--persona-md-link-color"]=(Ct=(fn=r["--persona-components-markdown-link-foreground"])!=null?fn:r["--persona-accent"])!=null?Ct:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let d=r["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(r["--persona-md-prose-font-family"]=d),r["--persona-md-code-block-bg"]=(Gr=r["--persona-components-markdown-codeBlock-background"])!=null?Gr:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Kr=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Kr:r["--persona-border"],r["--persona-md-code-block-text-color"]=(Ir=r["--persona-components-markdown-codeBlock-textColor"])!=null?Ir:"inherit",r["--persona-md-table-header-bg"]=(Mt=r["--persona-components-markdown-table-headerBackground"])!=null?Mt:r["--persona-container"],r["--persona-md-table-border-color"]=(io=r["--persona-components-markdown-table-borderColor"])!=null?io:r["--persona-border"],r["--persona-md-hr-color"]=(lo=r["--persona-components-markdown-hr-color"])!=null?lo:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(Xr=r["--persona-components-markdown-blockquote-borderColor"])!=null?Xr:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(mn=r["--persona-components-markdown-blockquote-background"])!=null?mn:"transparent",r["--persona-md-blockquote-text-color"]=(Go=r["--persona-components-markdown-blockquote-textColor"])!=null?Go:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(gn=r["--persona-components-collapsibleWidget-container"])!=null?gn:r["--persona-surface"],r["--cw-surface"]=(Qr=r["--persona-components-collapsibleWidget-surface"])!=null?Qr:r["--persona-surface"],r["--cw-border"]=(Nt=r["--persona-components-collapsibleWidget-border"])!=null?Nt:r["--persona-border"],r["--persona-message-border"]=(Wr=r["--persona-components-message-border"])!=null?Wr:r["--persona-border"];let u=e.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(r["--persona-icon-btn-bg"]=g.background),g.border&&(r["--persona-icon-btn-border"]=g.border),g.color&&(r["--persona-icon-btn-color"]=g.color),g.padding&&(r["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(r["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(r["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(r["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(r["--persona-icon-btn-active-border"]=g.activeBorder));let p=u==null?void 0:u.labelButton;p&&(p.background&&(r["--persona-label-btn-bg"]=p.background),p.border&&(r["--persona-label-btn-border"]=p.border),p.color&&(r["--persona-label-btn-color"]=p.color),p.padding&&(r["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(r["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(r["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(r["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(r["--persona-label-btn-gap"]=p.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(r["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(r["--persona-toggle-group-radius"]=m.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let xe=x.toolbar;xe.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,r["--persona-dropdown-bg"]=(co=r["--persona-dropdown-bg"])!=null?co:xe.copyMenuBackground),xe.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,r["--persona-dropdown-border"]=(hn=r["--persona-dropdown-border"])!=null?hn:xe.copyMenuBorder),xe.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,r["--persona-dropdown-shadow"]=(Ko=r["--persona-dropdown-shadow"])!=null?Ko:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(xn=r["--persona-dropdown-radius"])!=null?xn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Ro=r["--persona-dropdown-item-hover-bg"])!=null?Ro:xe.copyMenuItemHoverBackground),xe.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(x!=null&&x.tab){let xe=x.tab;xe.background&&(r["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(r["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(r["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(r["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(r["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(r["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(r["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(x!=null&&x.pane){let xe=x.pane;if(xe.toolbarBackground){let dt=(Jr=Ua(e,xe.toolbarBackground))!=null?Jr:xe.toolbarBackground;r["--persona-artifact-toolbar-bg"]=dt}}return r}var sh={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 db={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"}}},ih=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Is=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},cb=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Is()},sp=e=>cb(e),pb=e=>qa(e),ub=e=>{var r;let t=qa(void 0,{validate:!1});return qa({...e,palette:{...t.palette,colors:{...db.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Va=e=>{let t=sp(e),r=ih(e==null?void 0:e.theme),o=ih(e==null?void 0:e.darkTheme);return t==="dark"?ub(Rs(r!=null?r:{},o!=null?o:{})):pb(r)},fb=e=>Yi(e),Wn=(e,t)=>{let r=Va(t),o=fb(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},Zi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Is())});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(Is());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 lh=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:p=>p.getAttribute("im-preserve")==="true",shouldReAppend:p=>p.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(p,m,x={}){p=u(p);let C=g(m),T=d(p,C,x),E=n(T,()=>i(T,p,C,M=>M.morphStyle==="innerHTML"?(a(M,p,C),Array.from(p.childNodes)):o(M,p,C)));return T.pantry.remove(),E}function o(p,m,x){let C=g(m);return a(p,C,x,m,m.nextSibling),Array.from(C.childNodes)}function n(p,m){var P;if(!p.config.restoreFocus)return m();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return m();let{id:C,selectionStart:T,selectionEnd:E}=x,M=m();return C&&C!==((P=document.activeElement)==null?void 0:P.getAttribute("id"))&&(x=p.target.querySelector(`[id="${C}"]`),x==null||x.focus()),x&&!x.selectionEnd&&E&&x.setSelectionRange(T,E),M}let a=(function(){function p(y,w,b,A=null,H=null){w instanceof HTMLTemplateElement&&b instanceof HTMLTemplateElement&&(w=w.content,b=b.content),A||(A=w.firstChild);for(let W of b.childNodes){if(A&&A!=H){let N=x(y,W,A,H);if(N){N!==A&&T(y,A,N),s(N,W,y),A=N.nextSibling;continue}}if(W instanceof Element){let N=W.getAttribute("id");if(y.persistentIds.has(N)){let q=E(w,N,A,y);s(q,W,y),A=q.nextSibling;continue}}let k=m(w,W,A,y);k&&(A=k.nextSibling)}for(;A&&A!=H;){let W=A;A=A.nextSibling,C(y,W)}}function m(y,w,b,A){if(A.callbacks.beforeNodeAdded(w)===!1)return null;if(A.idMap.has(w)){let H=document.createElement(w.tagName);return y.insertBefore(H,b),s(H,w,A),A.callbacks.afterNodeAdded(H),H}else{let H=document.importNode(w,!0);return y.insertBefore(H,b),A.callbacks.afterNodeAdded(H),H}}let x=(function(){function y(A,H,W,k){let N=null,q=H.nextSibling,Z=0,me=W;for(;me&&me!=k;){if(b(me,H)){if(w(A,me,H))return me;N===null&&(A.idMap.has(me)||(N=me))}if(N===null&&q&&b(me,q)&&(Z++,q=q.nextSibling,Z>=2&&(N=void 0)),A.activeElementAndParents.includes(me))break;me=me.nextSibling}return N||null}function w(A,H,W){let k=A.idMap.get(H),N=A.idMap.get(W);if(!N||!k)return!1;for(let q of k)if(N.has(q))return!0;return!1}function b(A,H){var N,q,Z;let W=A,k=H;return W.nodeType===k.nodeType&&W.tagName===k.tagName&&(!((N=W.getAttribute)!=null&&N.call(W,"id"))||((q=W.getAttribute)==null?void 0:q.call(W,"id"))===((Z=k.getAttribute)==null?void 0:Z.call(k,"id")))}return y})();function C(y,w){var b;if(y.idMap.has(w))P(y.pantry,w,null);else{if(y.callbacks.beforeNodeRemoved(w)===!1)return;(b=w.parentNode)==null||b.removeChild(w),y.callbacks.afterNodeRemoved(w)}}function T(y,w,b){let A=w;for(;A&&A!==b;){let H=A;A=A.nextSibling,C(y,H)}return A}function E(y,w,b,A){var W,k;let H=((k=(W=A.target).getAttribute)==null?void 0:k.call(W,"id"))===w&&A.target||A.target.querySelector(`[id="${w}"]`)||A.pantry.querySelector(`[id="${w}"]`);return M(H,A),P(y,H,b),H}function M(y,w){let b=y.getAttribute("id");for(;y=y.parentNode;){let A=w.idMap.get(y);A&&(A.delete(b),A.size||w.idMap.delete(y))}}function P(y,w,b){if(y.moveBefore)try{y.moveBefore(w,b)}catch{y.insertBefore(w,b)}else y.insertBefore(w,b)}return p})(),s=(function(){function p(M,P,y){return y.ignoreActive&&M===document.activeElement?null:(y.callbacks.beforeNodeMorphed(M,P)===!1||(M instanceof HTMLHeadElement&&y.head.ignore||(M instanceof HTMLHeadElement&&y.head.style!=="morph"?c(M,P,y):(m(M,P,y),E(M,y)||a(y,M,P))),y.callbacks.afterNodeMorphed(M,P)),M)}function m(M,P,y){let w=P.nodeType;if(w===1){let b=M,A=P,H=b.attributes,W=A.attributes;for(let k of W)T(k.name,b,"update",y)||b.getAttribute(k.name)!==k.value&&b.setAttribute(k.name,k.value);for(let k=H.length-1;0<=k;k--){let N=H[k];if(N&&!A.hasAttribute(N.name)){if(T(N.name,b,"remove",y))continue;b.removeAttribute(N.name)}}E(b,y)||x(b,A,y)}(w===8||w===3)&&M.nodeValue!==P.nodeValue&&(M.nodeValue=P.nodeValue)}function x(M,P,y){if(M instanceof HTMLInputElement&&P instanceof HTMLInputElement&&P.type!=="file"){let w=P.value,b=M.value;C(M,P,"checked",y),C(M,P,"disabled",y),P.hasAttribute("value")?b!==w&&(T("value",M,"update",y)||(M.setAttribute("value",w),M.value=w)):T("value",M,"remove",y)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&P instanceof HTMLOptionElement)C(M,P,"selected",y);else if(M instanceof HTMLTextAreaElement&&P instanceof HTMLTextAreaElement){let w=P.value,b=M.value;if(T("value",M,"update",y))return;w!==b&&(M.value=w),M.firstChild&&M.firstChild.nodeValue!==w&&(M.firstChild.nodeValue=w)}}function C(M,P,y,w){let b=P[y],A=M[y];if(b!==A){let H=T(y,M,"update",w);H||(M[y]=P[y]),b?H||M.setAttribute(y,""):T(y,M,"remove",w)||M.removeAttribute(y)}}function T(M,P,y,w){return M==="value"&&w.ignoreActiveValue&&P===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(M,P,y)===!1}function E(M,P){return!!P.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return p})();function i(p,m,x,C){if(p.head.block){let T=m.querySelector("head"),E=x.querySelector("head");if(T&&E){let M=c(T,E,p);return Promise.all(M).then(()=>{let P=Object.assign(p,{head:{block:!1,ignore:!0}});return C(P)})}}return C(p)}function c(p,m,x){let C=[],T=[],E=[],M=[],P=new Map;for(let w of m.children)P.set(w.outerHTML,w);for(let w of p.children){let b=P.has(w.outerHTML),A=x.head.shouldReAppend(w),H=x.head.shouldPreserve(w);b||H?A?T.push(w):(P.delete(w.outerHTML),E.push(w)):x.head.style==="append"?A&&(T.push(w),M.push(w)):x.head.shouldRemove(w)!==!1&&T.push(w)}M.push(...P.values());let y=[];for(let w of M){let b=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(b)!==!1){if("href"in b&&b.href||"src"in b&&b.src){let A,H=new Promise(function(W){A=W});b.addEventListener("load",function(){A()}),y.push(H)}p.appendChild(b),x.callbacks.afterNodeAdded(b),C.push(b)}}for(let w of T)x.callbacks.beforeNodeRemoved(w)!==!1&&(p.removeChild(w),x.callbacks.afterNodeRemoved(w));return x.head.afterHeadMorphed(p,{added:C,kept:E,removed:T}),y}let d=(function(){function p(y,w,b){let{persistentIds:A,idMap:H}=M(y,w),W=m(b),k=W.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(k))throw`Do not understand how to morph style ${k}`;return{target:y,newContent:w,config:W,morphStyle:k,ignoreActive:W.ignoreActive,ignoreActiveValue:W.ignoreActiveValue,restoreFocus:W.restoreFocus,idMap:H,persistentIds:A,pantry:x(),activeElementAndParents:C(y),callbacks:W.callbacks,head:W.head}}function m(y){let w=Object.assign({},t);return Object.assign(w,y),w.callbacks=Object.assign({},t.callbacks,y.callbacks),w.head=Object.assign({},t.head,y.head),w}function x(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function C(y){let w=[],b=document.activeElement;if((b==null?void 0:b.tagName)!=="BODY"&&y.contains(b))for(;b&&(w.push(b),b!==y);)b=b.parentElement;return w}function T(y){var b;let w=Array.from(y.querySelectorAll("[id]"));return(b=y.getAttribute)!=null&&b.call(y,"id")&&w.push(y),w}function E(y,w,b,A){for(let H of A){let W=H.getAttribute("id");if(w.has(W)){let k=H;for(;k;){let N=y.get(k);if(N==null&&(N=new Set,y.set(k,N)),N.add(W),k===b)break;k=k.parentElement}}}}function M(y,w){let b=T(y),A=T(w),H=P(b,A),W=new Map;E(W,H,y,b);let k=w.__idiomorphRoot||w;return E(W,H,k,A),{persistentIds:H,idMap:W}}function P(y,w){let b=new Set,A=new Map;for(let{id:W,tagName:k}of y)A.has(W)?b.add(W):A.set(W,k);let H=new Set;for(let{id:W,tagName:k}of w)H.has(W)?b.add(W):A.get(W)===k&&H.add(W);for(let W of b)H.delete(W);return H}return p})(),{normalizeElement:u,normalizeParent:g}=(function(){let p=new WeakSet;function m(E){return E instanceof Document?E.documentElement:E}function x(E){if(E==null)return document.createElement("div");if(typeof E=="string")return x(T(E));if(p.has(E))return E;if(E instanceof Node){if(E.parentNode)return new C(E);{let M=document.createElement("div");return M.append(E),M}}else{let M=document.createElement("div");for(let P of[...E])M.append(P);return M}}class C{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],P=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;P&&P!=this.nextSibling;)M.push(P),P=P.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((P,y)=>{if(y instanceof Element){y.matches(M)&&P.push(y);let w=y.querySelectorAll(M);for(let b=0;b<w.length;b++)P.push(w[b])}return P},[])}insertBefore(M,P){return this.realParentNode.insertBefore(M,P)}moveBefore(M,P){return this.realParentNode.moveBefore(M,P)}get __idiomorphRoot(){return this.originalNode}}function T(E){let M=new DOMParser,P=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(P.match(/<\/html>/)||P.match(/<\/head>/)||P.match(/<\/body>/)){let y=M.parseFromString(E,"text/html");if(P.match(/<\/html>/))return p.add(y),y;{let w=y.firstChild;return w&&p.add(w),w}}else{let w=M.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return p.add(w),w}}return{normalizeElement:m,normalizeParent:x}})();return{morph:r,defaults:t}})();var el=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;lh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",d=(i=a.textContent)!=null?i:"";if(c!==d)return}return!1}}}}})};var tl={index:-1,draft:""};function dh(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:{...tl}}}function ch(e,t){var r,o,n,a,s,i,c,d,u,g,p,m,x,C,T,E,M,P,y,w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de,J,le;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(u=(d=e.llmContent)==null?void 0:d.length)!=null?u:0,(p=(g=e.approval)==null?void 0:g.status)!=null?p:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(T=(C=e.toolCall)==null?void 0:C.name)!=null?T:"",(P=(M=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:M.length)!=null?P:0,(A=(b=(w=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:w[e.toolCall.chunks.length-1])==null?void 0:b.slice(-32))!=null?A:"",typeof((H=e.toolCall)==null?void 0:H.args)=="string"?e.toolCall.args.length:(W=e.toolCall)!=null&&W.args?JSON.stringify(e.toolCall.args).length:0,(q=(N=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:N.length)!=null?q:0,(Ce=(Ke=(me=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:Ke.length)!=null?Ce:0,(We=(Te=(Ue=(Ie=e.reasoning)==null?void 0:Ie.chunks)==null?void 0:Ue[e.reasoning.chunks.length-1])==null?void 0:Te.slice(-32))!=null?We:"",(J=(de=e.contentParts)==null?void 0:de.length)!=null?J:0,(le=e.stopReason)!=null?le:"",t].join("\0")}function ph(){return new Map}function uh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function fh(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function mh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function rl(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function sn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function la(e,t){return sn(e)-e.scrollTop<=t}function ol(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,u=r-o;return s||Math.abs(u)<a?{action:"none",delta:u,nextLastScrollTop:r}:!t&&n&&(!d||u>0)?{action:"resume",delta:u,nextLastScrollTop:r}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:u,nextLastScrollTop:r}:{action:"none",delta:u,nextLastScrollTop:r}}function nl(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 gh(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function hh(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 xh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var kr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Lr=1e5,Hn=Lr+1;var Ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},mb=["pre","code","a","script","style"],al=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}},bh=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Hs=new Map;for(let e of bh)Hs.set(e.name,e);var da=e=>{Hs.set(e.name,e)},dp=e=>{bh.some(t=>t.name===e)||Hs.delete(e)},cp=()=>Array.from(Hs.keys()),Bs=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Hs.get(e))!=null?o:null},sl=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
18
- `);return a<0?"":e.slice(0,a)}return e},gb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},hb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},ip=/\s/,xb=(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},yb=(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(ip.test(a[i])){let d=i;for(;d<a.length&&ip.test(a[d]);)d+=1;s.appendChild(o.createTextNode(a.slice(i,d))),i=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let u=i;for(;u<a.length&&!ip.test(a[u]);)d.appendChild(gb(o,a[u],t,r.value)),r.value+=1,u+=1;s.appendChild(d),i=u}n.replaceChild(s,e)},bb=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let d of i)d&&(/^\s+$/.test(d)?s.appendChild(o.createTextNode(d)):(s.appendChild(hb(o,d,t,r.value)),r.value+=1));n.replaceChild(s,e)},Ds=(e,t,r,o)=>{var g,p;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((g=o==null?void 0:o.skipTags)!=null?g:mb).map(m=>m.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)xb(c,a)||i.push(c),c=s.nextNode();let d={value:(p=o==null?void 0:o.startIndex)!=null?p:0},u=t==="char"?yb:bb;for(let m of i)u(m,r,d);return n.innerHTML},il=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Fs=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},yh=new WeakMap,vb=(e,t)=>{var a;if(!e.styles)return;let r=yh.get(t);if(r||(r=new Set,yh.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)},lp=new WeakMap,Cb=(e,t)=>{if(!e.onAttach)return;let r=lp.get(t);if(r||(r=new Map,lp.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},vh=e=>{let t=lp.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},pp=(e,t)=>{vb(e,t),Cb(e,t)};function up(e,t=Lr){let r=e.style.position,o=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=o,e.style.isolation=n}}var Ns=0,Bn=null;function fp(e=document){var r;if(Ns++,Ns===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Bn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Ns=Math.max(0,Ns-1),Ns===0&&Bn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Bn.originalOverflow,n.style.position=Bn.originalPosition,n.style.top=Bn.originalTop,n.style.width=Bn.originalWidth,a.scrollTo(0,Bn.scrollY),Bn=null}}}var Os={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},pr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Dn=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},no=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Os.side,width:(n=t==null?void 0:t.width)!=null?n:Os.width,animate:(a=t==null?void 0:t.animate)!=null?a:Os.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:Os.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Os.maxHeight}};var To={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var wb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ll=(e,t={})=>{var T,E,M,P,y,w;let{showClose:r=!0,wrapperClassName:o=wb,buttonSize:n,iconSize:a="28px"}=t,s=(T=e==null?void 0:e.launcher)!=null?T:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=S("div",o),d=(M=s.closeButtonTooltipText)!=null?M:"Close chat",u=(P=s.closeButtonShowTooltip)!=null?P:!0,g=(y=s.closeButtonIconName)!=null?y:"x",p=(w=s.closeButtonIconText)!=null?w:"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=kt("button",{className:bs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||_r.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),C=ve(g,a,"currentColor",1);if(C?(C.style.display="block",x.appendChild(C)):x.textContent=p,c.appendChild(x),u&&d){let b=null,A=()=>{if(b)return;let W=x.ownerDocument,k=W.body;if(!k)return;b=Vo(W,"div","persona-clear-chat-tooltip"),b.textContent=d;let N=Vo(W,"div");N.className="persona-clear-chat-tooltip-arrow",b.appendChild(N);let q=x.getBoundingClientRect();b.style.position="fixed",b.style.zIndex=String(Hn),b.style.left=`${q.left+q.width/2}px`,b.style.top=`${q.top-8}px`,b.style.transform="translate(-50%, -100%)",k.appendChild(b)},H=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};c.addEventListener("mouseenter",A),c.addEventListener("mouseleave",H),x.addEventListener("focus",A),x.addEventListener("blur",H),c._cleanupTooltip=()=>{H(),c.removeEventListener("mouseenter",A),c.removeEventListener("mouseleave",H),x.removeEventListener("focus",A),x.removeEventListener("blur",H)}}return{button:x,wrapper:c}},Sb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",dl=(e,t={})=>{var b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue;let{wrapperClassName:r=Sb,buttonSize:o,iconSize:n="20px"}=t,s=(A=((b=e==null?void 0:e.launcher)!=null?b:{}).clearChat)!=null?A:{},i=(H=o!=null?o:s.size)!=null?H:"32px",c=(W=s.iconName)!=null?W:"refresh-cw",d=(k=s.iconColor)!=null?k:"",u=(N=s.backgroundColor)!=null?N:"",g=(q=s.borderWidth)!=null?q:"",p=(Z=s.borderColor)!=null?Z:"",m=(me=s.borderRadius)!=null?me:"",x=(Ke=s.paddingX)!=null?Ke:"",C=(Ce=s.paddingY)!=null?Ce:"",T=(Ie=s.tooltipText)!=null?Ie:"Clear chat",E=(Ue=s.showTooltip)!=null?Ue:!0,M=S("div",r),P=!!(g||p),y=kt("button",{className:bs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!P&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:d||_r.actionIconColor,backgroundColor:u||void 0,border:P?`${g||"0px"} solid ${p||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),w=ve(c,n,"currentColor",1);if(w&&(w.style.display="block",y.appendChild(w)),M.appendChild(y),E&&T){let Te=null,We=()=>{if(Te)return;let J=y.ownerDocument,le=J.body;if(!le)return;Te=Vo(J,"div","persona-clear-chat-tooltip"),Te.textContent=T;let ge=Vo(J,"div");ge.className="persona-clear-chat-tooltip-arrow",Te.appendChild(ge);let ue=y.getBoundingClientRect();Te.style.position="fixed",Te.style.zIndex=String(Hn),Te.style.left=`${ue.left+ue.width/2}px`,Te.style.top=`${ue.top-8}px`,Te.style.transform="translate(-50%, -100%)",le.appendChild(Te)},de=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};M.addEventListener("mouseenter",We),M.addEventListener("mouseleave",de),y.addEventListener("focus",We),y.addEventListener("blur",de),M._cleanupTooltip=()=>{de(),M.removeEventListener("mouseenter",We),M.removeEventListener("mouseleave",de),y.removeEventListener("focus",We),y.removeEventListener("blur",de)}}return{button:y,wrapper:M}};var _r={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ln=e=>{var w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We;let{config:t,showClose:r=!0}=e,o=kt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),n=(w=t==null?void 0:t.launcher)!=null?w:{},a=(b=n.headerIconSize)!=null?b:"48px",s=(A=n.closeButtonPlacement)!=null?A:"inline",i=(H=n.headerIconHidden)!=null?H:!1,c=n.headerIconName,d=kt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(c){let de=parseFloat(a)||24,J=ve(c,de*.6,"currentColor",1);J?d.replaceChildren(J):d.textContent=(k=(W=t==null?void 0:t.launcher)==null?void 0:W.agentIconText)!=null?k:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let de=S("img");de.src=t.launcher.iconUrl,de.alt="",de.className="persona-rounded-xl persona-object-cover",de.style.height=a,de.style.width=a,d.replaceChildren(de)}else d.textContent=(Z=(q=t==null?void 0:t.launcher)==null?void 0:q.agentIconText)!=null?Z:"\u{1F4AC}";let u=S("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=kt("span",{className:"persona-text-base persona-font-semibold",text:(Ke=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?Ke:"Chat Assistant",style:{color:_r.titleColor}}),p=kt("span",{className:"persona-text-xs",text:(Ie=(Ce=t==null?void 0:t.launcher)==null?void 0:Ce.subtitle)!=null?Ie:"Here to help you get answers fast",style:{color:_r.subtitleColor}});u.append(g,p),i?o.append(u):o.append(d,u);let m=(Ue=n.clearChat)!=null?Ue:{},x=(Te=m.enabled)!=null?Te:!0,C=(We=m.placement)!=null?We:"inline",T=null,E=null;if(x){let J=dl(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=J.button,E=J.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let M=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:y}=ll(t,{showClose:r,wrapperClassName:M});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:d,headerTitle:g,headerSubtitle:p,closeButton:P,closeButtonWrapper:y,clearChatButton:T,clearChatButtonWrapper:E}},ca=(e,t,r)=>{var s,i,c,d;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(d=(c=o.clearChat)==null?void 0:c.placement)!=null?d:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Fn(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=S("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Hn)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of t){if(m.dividerBefore){let T=document.createElement("hr");s.appendChild(T)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let T=ve(m.icon,16,"currentColor",1.5);T&&x.appendChild(T)}let C=document.createElement("span");C.textContent=m.label,x.appendChild(C),x.addEventListener("click",T=>{T.stopPropagation(),u(),r(m.id)}),s.appendChild(x)}let i=null;function c(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function d(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!s.contains(x.target)&&!o.contains(x.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){s.classList.add("persona-hidden"),i==null||i(),i=null}function g(){s.classList.contains("persona-hidden")?d():u()}function p(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:u,toggle:g,destroy:p}}function yr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=S("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let d=ve(t,o!=null?o:16,"currentColor",n!=null?n:2);if(d&&c.appendChild(d),s&&c.addEventListener("click",s),i)for(let[u,g]of Object.entries(i))c.setAttribute(u,g);return c}function _s(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let u=S("button",d);if(u.type="button",u.setAttribute("aria-label",r),t){let p=ve(t,a!=null?a:14,"currentColor",2);p&&u.appendChild(p)}let g=S("span");if(g.textContent=r,u.appendChild(g),i&&u.addEventListener("click",i),c)for(let[p,m]of Object.entries(c))u.setAttribute(p,m);return u}function Ch(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=S("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===s?"true":"false")}for(let u of t){let g;u.icon?g=yr({icon:u.icon,label:u.label,onClick:()=>{s=u.id,c(),o(u.id)}}):(g=S("button","persona-icon-btn"),g.type="button",g.setAttribute("aria-label",u.label),g.title=u.label,g.textContent=u.label,g.addEventListener("click",()=>{s=u.id,c(),o(u.id)})),g.setAttribute("aria-pressed",u.id===s?"true":"false"),i.push({id:u.id,btn:g}),a.appendChild(g)}function d(u){s=u,c()}return{element:a,setSelected:d}}function cl(e){var m,x;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,d=S("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let u=S("span","persona-combo-btn-label");u.textContent=t,d.appendChild(u);let g=ve(r,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",d.appendChild(g)),c&&(d.style.borderRadius=(m=c.borderRadius)!=null?m:"10px",d.style.padding=(x=c.padding)!=null?x:"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{var C,T;d.style.backgroundColor=(C=c.background)!=null?C:"",d.style.borderColor=(T=c.border)!=null?T:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let p=Fn({items:o,onSelect:C=>{d.setAttribute("aria-expanded","false"),n(C)},anchor:d,position:a,portal:s});return s||d.appendChild(p.element),d.addEventListener("click",C=>{C.stopPropagation();let T=!p.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",T?"false":"true"),p.toggle()}),d.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),d.click())}),{element:d,setLabel:C=>{u.textContent=C,d.setAttribute("aria-label",C)},open:()=>{d.setAttribute("aria-expanded","true"),p.show()},close:()=>{d.setAttribute("aria-expanded","false"),p.hide()},toggle:()=>{let C=!p.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",C?"false":"true"),p.toggle()},destroy:()=>{p.destroy(),d.remove()}}}var mp=e=>{var o;let t=ln({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(r){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>r()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function Ab(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=S("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let c=ve(s.icon,14,"currentColor",2);c&&i.appendChild(c)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let c=S("div","persona-relative");c.appendChild(i);let d=Fn({items:s.menuItems,onSelect:u=>r==null?void 0:r(u),anchor:c,position:"bottom-left"});c.appendChild(d.element),i.addEventListener("click",u=>{u.stopPropagation(),d.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var gp=e=>{var M,P,y,w,b,A,H,W,k;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(M=t==null?void 0:t.launcher)!=null?M:{},i=S("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=n==null?void 0:n.titleMenu,d,u;if(c)d=cl({label:(P=s.title)!=null?P:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,d.style.color=_r.titleColor,u=(y=d.querySelector(".persona-combo-btn-label"))!=null?y:d;else{if(d=S("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=S("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=_r.titleColor,u.textContent=(w=s.title)!=null?w:"Chat Assistant",d.appendChild(u),Ab(d,n==null?void 0:n.trailingActions,(b=n==null?void 0:n.onAction)!=null?b:a),n!=null&&n.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let q=n.onTitleClick;d.addEventListener("click",Z=>{Z.target.closest("button")||q()}),d.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),q())})}let N=n==null?void 0:n.titleRowHover;N&&(d.style.borderRadius=(A=N.borderRadius)!=null?A:"10px",d.style.padding=(H=N.padding)!=null?H:"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{var q,Z;d.style.backgroundColor=(q=N.background)!=null?q:"",d.style.borderColor=(Z=N.border)!=null?Z:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let g=(W=s.closeButtonSize)!=null?W:"32px",p=S("div",""),m=S("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none",m.style.color=s.closeButtonColor||_r.actionIconColor;let x=(k=s.closeButtonIconName)!=null?k:"x",C=ve(x,"28px","currentColor",1);C?m.appendChild(C):m.textContent="\xD7",o&&m.addEventListener("click",o),p.appendChild(m),i.appendChild(p);let T=S("div");T.style.display="none";let E=S("span");return E.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:E,closeButton:m,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},pl={default:mp,minimal:gp},hp=e=>{var t;return(t=pl[e])!=null?t:pl.default},$a=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let d=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=S("div");u.style.display="none";let g=S("span"),p=S("span"),m=S("button");m.style.display="none";let x=S("div");return x.style.display="none",{header:d,iconHolder:u,headerTitle:g,headerSubtitle:p,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=hp(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 ul=e=>{var s,i;let t=S("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,o=20;t.style.maxHeight=`${r*o}px`,t.style.overflowY="auto";let n=()=>{let c=parseFloat(t.style.maxHeight);return Number.isFinite(c)&&c>0?c:r*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let c=Math.min(t.scrollHeight,n());t.style.height=`${c}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:a}},fl=e=>{var w,b,A,H,W,k,N,q,Z,me,Ke,Ce;let t=(w=e==null?void 0:e.sendButton)!=null?w:{},r=(b=t.useIcon)!=null?b:!1,o=(A=t.iconText)!=null?A:"\u2191",n=t.iconName,a=(H=t.stopIconName)!=null?H:"square",s=(W=t.tooltipText)!=null?W:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",c=(q=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?q:"Send",d=(me=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?me:"Stop",u=(Ke=t.showTooltip)!=null?Ke:!1,g=(Ce=t.size)!=null?Ce:"40px",p=t.backgroundColor,m=t.textColor,x=S("div","persona-send-button-wrapper"),C=kt("button",{className:bs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!p&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?g:void 0,height:r?g:void 0,minWidth:r?g:void 0,minHeight:r?g:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:r&&p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=null,E=null;if(r){let Ie=parseFloat(g)||24,Ue=(m==null?void 0:m.trim())||"currentColor";n?(T=ve(n,Ie,Ue,2),T?C.appendChild(T):C.textContent=o):C.textContent=o,E=ve(a,Ie,Ue,2)}else C.textContent=c;let M=null;u&&s&&(M=S("div","persona-send-button-tooltip"),M.textContent=s,x.appendChild(M)),C.setAttribute("aria-label",s),x.appendChild(C);let P="send";return{button:C,wrapper:x,setMode:Ie=>{if(Ie===P)return;P=Ie;let Ue=Ie==="stop"?i:s;if(C.setAttribute("aria-label",Ue),M&&(M.textContent=Ue),r){if(T&&E){let Te=Ie==="stop"?E:T;C.replaceChildren(Te)}}else C.textContent=Ie==="stop"?d:c}}},ml=e=>{var M,P,y,w,b,A,H,W,k,N,q,Z;let t=(M=e==null?void 0:e.voiceRecognition)!=null?M:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(o||n))return null;let s=(w=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?w:"40px",i=(b=t.iconName)!=null?b:"mic",c=(A=t.iconSize)!=null?A:s,d=parseFloat(c)||24,u=(W=t.backgroundColor)!=null?W:(H=e==null?void 0:e.sendButton)==null?void 0:H.backgroundColor,g=(N=t.iconColor)!=null?N:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor,p=S("div","persona-send-button-wrapper"),m=kt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ve(i,d,g||"currentColor",1.5);C?m.appendChild(C):m.textContent="\u{1F3A4}",p.appendChild(m);let T=(q=t.tooltipText)!=null?q:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&T){let me=S("div","persona-send-button-tooltip");me.textContent=T,p.appendChild(me)}return{button:m,wrapper:p}},gl=e=>{var x,C,T,E,M,P,y,w;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(T=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?T:"40px",o=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=S("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:an).join(","),n.multiple=((M=t.maxFiles)!=null?M:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(P=t.buttonIconName)!=null?P:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),d=S("div","persona-send-button-wrapper"),u=kt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let g=ve(a,c,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",b=>{b.preventDefault(),n.click()}),d.appendChild(u);let p=(w=t.buttonTooltipText)!=null?w:"Attach file",m=S("div","persona-send-button-tooltip");return m.textContent=p,d.appendChild(m),{button:u,wrapper:d,input:n,previewsContainer:o}},hl=e=>{var s,i,c;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=S("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let d=S("a");d.href=t.idleLink,d.target="_blank",d.rel="noopener noreferrer",d.textContent=a,d.style.color="inherit",d.style.textDecoration="none",o.appendChild(d)}else o.textContent=a;return o},xl=()=>kt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var za=e=>{var x,C,T,E,M,P;let{config:t}=e,r=kt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=xl(),n=kt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=ul(t);s();let i=fl(t),c=ml(t),d=gl(t),u=hl(t);d&&(d.previewsContainer.style.gap="8px",n.append(d.previewsContainer,d.input)),n.append(a);let g=kt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),p=S("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=S("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&p.append(d.wrapper),c&&m.append(c.wrapper),m.append(i.wrapper),g.append(p,m),n.append(g),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),r.append(o,n,u),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,statusText:u,attachmentButton:(T=d==null?void 0:d.button)!=null?T:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(M=d==null?void 0:d.input)!=null?M:null,attachmentPreviewsContainer:(P=d==null?void 0:d.previewsContainer)!=null?P:null,actionsRow:g,leftActions:p,rightActions:m,setSendButtonMode:i.setMode}};var wh=()=>{let e=kt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=S("span","persona-pill-peek__icon"),r=ve("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=S("span","persona-pill-peek__text"),n=S("span","persona-pill-peek__caret"),a=ve("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Sh=e=>{var x,C,T,E,M,P;let{config:t}=e,r=kt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=xl();o.style.display="none";let n=hl(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=ul(t);a.style.maxHeight="100px",s();let i=fl(t),c=ml(t),d=gl(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let u=kt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=S("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&g.append(d.wrapper);let p=S("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&p.append(c.wrapper),p.append(i.wrapper),u.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),d&&u.append(d.input),u.append(g,a,p),d&&r.append(d.previewsContainer),r.append(u,o,n);let m=u;return{footer:r,suggestions:o,composerForm:u,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,statusText:n,attachmentButton:(T=d==null?void 0:d.button)!=null?T:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(M=d==null?void 0:d.input)!=null?M:null,attachmentPreviewsContainer:(P=d==null?void 0:d.previewsContainer)!=null?P:null,actionsRow:m,leftActions:g,rightActions:p,setSendButtonMode:i.setMode}};var Ah=e=>{var u,g,p,m,x,C,T,E,M,P,y,w,b,A,H,W,k;let t=(g=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?g:!0,r=pr(e);if(Dn(e)){let N=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.composerBar)!=null?m:{},q=S("div","persona-widget-wrapper persona-fixed persona-transition");q.setAttribute("data-persona-composer-bar",""),q.dataset.state="collapsed",q.dataset.expandedSize=(x=N.expandedSize)!=null?x:"anchored",q.style.zIndex=String((T=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?T:Lr);let Z=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",q.appendChild(Z);let me=S("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=N.expandedSize)!=null?E:"anchored",me.style.zIndex=String((P=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?P:Lr),{wrapper:q,panel:Z,pillRoot:me}}if(r){let N=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),q=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(q),{wrapper:N,panel:q}}if(!t){let N=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),q=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?w:"100%";return N.style.width=Z,q.style.width="100%",N.appendChild(q),{wrapper:N,panel:q}}let n=(b=e==null?void 0:e.launcher)!=null?b:{},a=n.position&&To[n.position]?To[n.position]:To["bottom-right"],s=S("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((H=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?H:Lr);let i=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(k=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?k:e==null?void 0:e.launcherWidth,d=c!=null?c:oo;return i.style.width=d,i.style.maxWidth=d,s.appendChild(i),{wrapper:s,panel:i}},Mb=(e,t)=>{var y,w,b,A,H,W,k,N,q;let r=S("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=ll(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(b=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:w.enabled)!=null?b:!0,s=null,i=null;if(a){let Z=dl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=kt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=kt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let u=kt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(H=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?H:"Hello \u{1F44B}"}),g=kt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),p=kt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,g),m=S("div","persona-flex persona-flex-col persona-gap-3"),x=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((q=e==null?void 0:e.copy)==null?void 0:q.showWelcomeCard)!==!1||(p.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(p,m);let T=kt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=Sh({config:e}),{root:M,textNode:P}=wh();return r.append(c,n,d,T),i&&r.appendChild(i),{container:r,body:d,messagesWrapper:m,composerOverlay:T,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:u,introSubtitle:g,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("span"),header:c,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:M,peekTextNode:P}},Mh=(e,t=!0)=>{var T,E,M,P,y,w,b,A,H;if(Dn(e))return Mb(e,t);let r=kt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=(T=e==null?void 0:e.layout)==null?void 0:T.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?$a(e,o,{showClose:t}):ln({config:e,showClose:t}),s=kt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let i=kt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(P=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?P:"Hello \u{1F44B}"}),c=kt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(w=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?w:"Ask anything about your account or products."}),d=kt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:pr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),u=S("div","persona-flex persona-flex-col persona-gap-3"),g=(b=e==null?void 0:e.layout)==null?void 0:b.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((A=e==null?void 0:e.copy)==null?void 0:A.showWelcomeCard)!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,u);let m=za({config:e}),x=((H=e==null?void 0:e.layout)==null?void 0:H.showFooter)!==!1;n?ca(r,a,e):(a.header.style.display="none",ca(r,a,e)),r.append(s);let C=kt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return x||(m.footer.style.display="none"),r.append(m.footer),r.append(C),{container:r,body:s,messagesWrapper:u,composerOverlay:C,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:c,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var xp=(e,t)=>{let r=S("button");r.type="button",r.innerHTML=`
17
+ _Details: ${r.message}_`:o}var Rs=e=>({isError:!0,content:[{type:"text",text:e}]}),oh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,nh=e=>ea(e)||e===Mo,Ua=class{constructor(t={},r){this.config=t;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new ia(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,d,u,g;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall,m=!!(p!=null&&p.name)&&(ea(p.name)||p.name===Mo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((d=this.agentExecution)==null?void 0:d.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new na(t),this.wireDefaultWebMcpConfirm();for(let a of(n=t.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var n,a,s,i,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let r=(n=t.host)!=null?n:this.config.apiUrl,o=(c=t.agentId)!=null?c:(i=(s=(a=this.config.voiceRecognition)==null?void 0:a.provider)==null?void 0:s.runtype)==null?void 0:i.agentId;!r||!o||!this.config.clientToken||id().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ps((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=In.isSupported()?new In({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(o=t.host)!=null?o:this.config.apiUrl,d=(i=t.agentId)!=null?i:(s=(a=(n=this.config.voiceRecognition)==null?void 0:n.provider)==null?void 0:a.runtype)==null?void 0:s.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(c&&d&&u)return id().then(({RuntypeSpeechEngine:p,FallbackSpeechEngine:m})=>{let x=new p({host:c,agentId:d,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&r?new m(x,r,{onFallback:C=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${C.message}`)}):x});if(g&&r)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),r}return r}setupVoice(t){var r,o;try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Rn(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,c,d)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:c,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,d;(d=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||d.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,d;this.voiceStatus=i,this.voiceActive=i==="listening",(d=(c=this.callbacks).onVoiceStatusChanged)==null||d.call(c,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,o,n,a,s,i,c,d,u,g;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:(a=(n=t.runtype)==null?void 0:n.clientToken)!=null?a:this.config.clientToken,host:(i=(s=t.runtype)==null?void 0:s.host)!=null?i:this.config.apiUrl,voiceId:(c=t.runtype)==null?void 0:c.voiceId,createPlaybackEngine:(d=t.runtype)==null?void 0:d.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((u=t.browser)==null?void 0:u.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(r=(t=this.callbacks).onError)==null||r.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r={...this.config,...t};if(!ob(this.config,r)){this.config=r,this.client.updateConfig(r);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=r,this.client=new na(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:d=!1,voiceProcessing:u,rawContent:g}=t,m={id:s!=null?s:r==="user"?Oa():r==="assistant"?aa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:d,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:d,sequence:u,streaming:g=!1,voiceProcessing:p,rawContent:m}=o,C={id:c!=null?c:n==="user"?Oa():n==="assistant"?aa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:d!=null?d:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};r.push(C)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,d={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var d,u,g,p,m;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(d=this.abortController)==null||d.abort(),this.abortWebMcpResolves();let n=Oa(),a=aa(),s={id:n,role:"user",content:o||Bi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let T=rh(x,this.config.errorMessage);if(T){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,x):(m=(p=this.callbacks).onError)==null||m.call(p,new Error(String(x))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort();let t=aa();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let g=rh(d,this.config.errorMessage);if(g){let p={id:t,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(p)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,d):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(d))))}}async connectStream(t,r){var n,a,s;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(n=this.abortController)==null||n.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var u,g,p,m,x;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(C=>C.id===n),i={id:n,role:"assistant",content:"",createdAt:(u=s==null?void 0:s.createdAt)!=null?u:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,d=c&&typeof c=="object"?c.onDecision:void 0;try{let C;if(d?C=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):C=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),C){let T=null;if(C instanceof Response){if(!C.ok){let E=await C.json().catch(()=>null);throw new Error((p=E==null?void 0:E.error)!=null?p:`Approval request failed: ${C.status}`)}T=C.body}else C instanceof ReadableStream&&(T=C);T?await this.connectStream(T,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(C){let T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(x=(m=this.callbacks).onError)==null||x.call(m,C instanceof Error?C:new Error(String(C)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var u,g,p,m,x,C,T,E,M,P,y,w;let o=this.messages.find(b=>b.id===t.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let n=(g=t.agentMetadata)==null?void 0:g.executionId,a=(p=t.toolCall)==null?void 0:p.name;if(!n||!a){(x=(m=this.callbacks).onError)==null||x.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let b=(C=t.toolCall)==null?void 0:C.args,A=Array.isArray(b==null?void 0:b.questions)?b.questions:[];if(A.length===1){let H=typeof((T=A[0])==null?void 0:T.question)=="string"?A[0].question:"";H&&(s={[H]:r})}}this.markAskUserQuestionResolved(t,s),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(M=t.toolCall)==null?void 0:M.args,d=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(d.length===0){let b=typeof r=="string"?r:Object.entries(r).map(([A,H])=>`${A}: ${Array.isArray(H)?H.join(", "):H}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:b,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let b=s!=null?s:{};d.forEach((A,H)=>{let W=typeof(A==null?void 0:A.question)=="string"?A.question:"";if(!W)return;let k=b[W],N=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${H}`,role:"assistant",content:W,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${H}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let b=await this.client.resumeFlow(n,{[a]:r});if(!b.ok){let A=await b.json().catch(()=>null);throw new Error((P=A==null?void 0:A.error)!=null?P:`Resume failed: ${b.status}`)}b.body?await this.connectStream(b.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(b){let A=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,A||(w=(y=this.callbacks).onError)==null||w.call(y,b instanceof Error?b:new Error(String(b)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==Mo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,d,u,g;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async p=>{var w,b,A,H,W,k,N;let m=(w=p.toolCall)==null?void 0:w.name,x=(b=p.toolCall)==null?void 0:b.id;if(!m||!x)return null;let C=`${t}:${x}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(C),o.push(C);let T=this.markWebMcpToolRunning(p),E=(H=(A=p.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?H:m;if(m===Mo)return{dedupeKey:C,resumeKey:E,output:Zl(),toolMessage:p,startedAt:T,completedAt:Date.now()};let M=new AbortController;this.webMcpResolveControllers.add(M),n.push(M);let P=this.client.executeWebMcpToolCall(m,(W=p.toolCall)==null?void 0:W.args,M.signal),y;if(!P)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await P}catch(q){let Z=q instanceof Error&&(q.name==="AbortError"||q.message.includes("aborted")||q.message.includes("abort"));return Z||(N=(k=this.callbacks).onError)==null||N.call(k,q instanceof Error?q:new Error(String(q))),this.markWebMcpToolComplete(p,Rs(Z?"Aborted by cancel()":oh(q)),T),this.webMcpInflightKeys.delete(C),null}return M.signal.aborted?(this.markWebMcpToolComplete(p,Rs("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:E,output:y,toolMessage:p,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=s.filter(x=>x!==null),i.length===0)return;let p={};for(let x of i)p[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,p,{signal:a.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((c=x==null?void 0:x.error)!=null?c:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((d=x.toolMessage.toolCall)==null?void 0:d.name)===Mo?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,p instanceof Error?p:new Error(String(p)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,Rs("Aborted by cancel()"),x.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of n)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,C,T,E,M,P,y,w,b,A,H,W;let r=(x=t.agentMetadata)==null?void 0:x.executionId,o=(C=t.toolCall)==null?void 0:C.name,n=(T=t.toolCall)==null?void 0:T.id;if(!r){(M=(E=this.callbacks).onError)==null||M.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let k=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);try{await this.resumeWithToolOutput(r,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(k)}catch(N){(y=(P=this.callbacks).onError)==null||y.call(P,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(k)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let d=o===Mo,u=(w=t.toolCall)==null?void 0:w.args,g=d?null:this.client.executeWebMcpToolCall(o,u,c),p="execute",m=s;try{let k;if(d?k=Zl():g?k=await g:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),c.aborted){this.markWebMcpToolComplete(t,Rs("Aborted by cancel()"),s);return}let N=(A=(b=t.agentMetadata)==null?void 0:b.webMcpToolCallId)!=null?A:o;p="resume",await this.resumeWithToolOutput(r,N,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,k,s,m,d?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(k){let N=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(p==="execute"||N||c.aborted)&&this.markWebMcpToolComplete(t,Rs(N||c.aborted?"Aborted by cancel()":oh(k)),s),N||(W=(H=this.callbacks).onError)==null||W.call(H,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,o,n){var s,i;let a=await this.client.resumeFlow(t,{[r]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let c=await a.json().catch(()=>null);throw new Error((s=c==null?void 0:c.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var n;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}let o={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(n=t.props)!=null?n:{}};return this.artifacts.set(r,o),this.selectedArtifactId=r,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let n=ad(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return _a(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=ad(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var u,g,p,m,x,C,T,E,M,P,y,w,b,A,H;if(a!==o)return n;let s={...n,...r};if(((u=n.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=n.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(p=s.agentMetadata)!=null?p:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let W=n.approval,k=r.approval;s.approval={...W,...k,executionId:k.executionId||W.executionId,toolName:k.toolName||W.toolName,description:k.description||W.description,toolType:(m=k.toolType)!=null?m:W.toolType,reason:(x=k.reason)!=null?x:W.reason,parameters:(C=k.parameters)!=null?C:W.parameters}}let i=(T=r.toolCall)==null?void 0:T.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,d=(M=r.toolCall)==null?void 0:M.id;if(i&&nh(i)&&c&&d&&((P=r.agentMetadata)==null?void 0:P.awaitingLocalTool)===!0){let W=`${c}:${d}`,k=this.webMcpInflightKeys.has(W),N=this.webMcpResolvedKeys.has(W),q=(y=n.toolCall)==null?void 0:y.name,Z=((w=n.agentMetadata)==null?void 0:w.executionId)===c&&((b=n.toolCall)==null?void 0:b.id)===d&&q!==void 0&&nh(q)&&((A=n.toolCall)==null?void 0:A.status)==="complete";(k||N||Z)&&(s.agentMetadata={...(H=s.agentMetadata)!=null?H:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,o)=>{var c,d;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(d=o.sequence)!=null?d:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var ld=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var dd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var cd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var pd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var ud=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var fd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var md=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var gd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var hd=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var xd=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var yd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var bd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var vd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Cd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var wd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var Sd=[["path",{d:"M20 6 9 17l-5-5"}]];var Ad=[["path",{d:"m6 9 6 6 6-6"}]];var Md=[["path",{d:"m15 18-6-6 6-6"}]];var Td=[["path",{d:"m9 18 6-6-6-6"}]];var Ed=[["path",{d:"m18 15-6-6-6 6"}]];var Oi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var _i=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var kd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var Ld=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var Pd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Rd=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var Id=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Wd=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var Hd=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Ui=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var qi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Bd=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Dd=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var Fd=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Nd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var Od=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var _d=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Ud=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var qd=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Vd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var $d=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var zd=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var jd=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var Vi=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Gd=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Kd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var Xd=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Qd=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Jd=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Yd=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var $i=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Zd=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var ec=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var tc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var rc=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var oc=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var zi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var nc=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var ac=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var sc=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var ic=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var lc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var dc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var cc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var pc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var uc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var fc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var mc=[["path",{d:"M5 12h14"}]];var gc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var hc=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var xc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var yc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var bc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var vc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Cc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var wc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Sc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var Ac=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Mc=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var Tc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Ec=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var kc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var Lc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Pc=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Rc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Ic=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var Wc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Hc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var ji=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Bc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Dc=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var Fc=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var Nc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Gi=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var Oc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var _c=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Uc=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var qc=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Vc=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var $c=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var zc=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var jc=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var Gc=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Kc=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Ki=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var Xc=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Qc=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Jc=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Yc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Zc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var ep=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var tp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var rp=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var nb={activity:ld,"arrow-down":dd,"arrow-up":fd,"arrow-up-right":ud,bot:yd,"chevron-down":Ad,"chevron-up":Ed,"chevron-right":Td,"chevron-left":Md,check:Sd,clipboard:Ld,"clipboard-copy":kd,copy:Rd,file:Ud,"file-code":Nd,"file-spreadsheet":Od,"file-text":_d,"image-plus":Zd,loader:nc,"loader-circle":zi,mic:uc,paperclip:yc,"refresh-cw":Tc,search:Lc,send:Pc,"shield-alert":Wc,"shield-check":Hc,"shield-x":ji,square:Oc,"thumbs-down":$c,"thumbs-up":zc,upload:Qc,"volume-2":Yc,x:tp,user:Jc,mail:sc,phone:wc,calendar:Cd,clock:Pd,building:bd,"map-pin":ic,lock:ac,key:rc,"credit-card":Id,"at-sign":md,hash:Xd,globe:Kd,link:oc,"circle-check":Oi,"circle-x":_i,"triangle-alert":Ki,info:tc,ban:gd,shield:Bc,"arrow-left":cd,"arrow-right":pd,"external-link":Dd,ellipsis:qi,"ellipsis-vertical":Ui,menu:dc,house:$i,plus:Ac,minus:mc,pencil:vc,trash:Kc,"trash-2":Gc,save:kc,download:Hd,share:Ic,funnel:Vi,settings:Rc,"rotate-cw":Ec,maximize:lc,minimize:fc,"shopping-cart":Fc,"shopping-bag":Dc,package:xc,truck:Xc,tag:Vc,gift:Gd,receipt:Mc,wallet:ep,store:Uc,"dollar-sign":Wd,percent:Cc,play:Sc,pause:bc,"volume-x":Zc,camera:wd,image:ec,film:Vd,headphones:Qd,"message-circle":cc,"message-square":pc,bell:hd,heart:Jd,star:_c,eye:Fd,"eye-off":Bd,bookmark:xd,"calendar-days":vd,history:Yd,timer:jc,folder:jd,"folder-open":zd,files:qd,sparkles:Gi,zap:rp,sun:qc,moon:hc,flag:$d,monitor:gc,smartphone:Nc},ve=(e,t=24,r="currentColor",o=2)=>{let n=nb[e];return n?ab(n,t,r,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function ab(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([d,u])=>{d!=="stroke"&&c.setAttribute(d,String(u))}),n.appendChild(c)}),n}var Xi={allowedTypes:an,maxFileSize:10*1024*1024,maxFiles:4};function sb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ib(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var la=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Xi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Xi.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Xi.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Xi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,o,n,a,s,i,c;if(t.length){for(let d of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,d,"count");continue}let u=Jg(d,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(n=u.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,d,g);continue}try{let g=await Qg(d),p=Di(d)?URL.createObjectURL(d):null,m={id:sb(),file:d,previewUrl:p,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=Di(t.file),o=S("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",r&&t.previewUrl){let s=S("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=S("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=ib(t.file.type),c=ve(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let d=S("span");d.textContent=Yg(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",s.appendChild(d),o.appendChild(s)}let n=S("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=ve("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var ah=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Is(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];ah(a)&&ah(n)?r[o]=Is(a,n):r[o]=n}return r}var oo="min(440px, calc(100vw - 24px))",Qi="440px",lb={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:oo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},_t={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:lb,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function sh(e,t){if(!(!e&&!t))return e?t?Is(e,t):e:t}function Ji(e){var t,r,o,n,a,s,i,c,d,u,g,p,m,x,C,T,E,M,P,y,w;return e?{..._t,...e,theme:sh(_t.theme,e.theme),darkTheme:sh(_t.darkTheme,e.darkTheme),launcher:{..._t.launcher,...e.launcher,dock:{...(t=_t.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=_t.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{..._t.copy,...e.copy},sendButton:{..._t.sendButton,...e.sendButton},statusIndicator:{..._t.statusIndicator,...e.statusIndicator},voiceRecognition:{..._t.voiceRecognition,...e.voiceRecognition},features:(()=>{var de,J,le,ge,ue,G,ce,Be,ne,ee;let b=(de=_t.features)==null?void 0:de.artifacts,A=(J=e.features)==null?void 0:J.artifacts,H=(le=_t.features)==null?void 0:le.scrollToBottom,W=(ge=e.features)==null?void 0:ge.scrollToBottom,k=(ue=_t.features)==null?void 0:ue.scrollBehavior,N=(G=e.features)==null?void 0:G.scrollBehavior,q=(ce=_t.features)==null?void 0:ce.streamAnimation,Z=(Be=e.features)==null?void 0:Be.streamAnimation,me=(ne=_t.features)==null?void 0:ne.askUserQuestion,Ke=(ee=e.features)==null?void 0:ee.askUserQuestion,Ce=b===void 0&&A===void 0?void 0:{...b,...A,layout:{...b==null?void 0:b.layout,...A==null?void 0:A.layout}},Ie=H===void 0&&W===void 0?void 0:{...H,...W},Ue=k===void 0&&N===void 0?void 0:{...k,...N},Te=q===void 0&&Z===void 0?void 0:{...q,...Z},We=me===void 0&&Ke===void 0?void 0:{...me,...Ke,styles:{...me==null?void 0:me.styles,...Ke==null?void 0:Ke.styles}};return{..._t.features,...e.features,...Ie!==void 0?{scrollToBottom:Ie}:{},...Ue!==void 0?{scrollBehavior:Ue}:{},...Ce!==void 0?{artifacts:Ce}:{},...Te!==void 0?{streamAnimation:Te}:{},...We!==void 0?{askUserQuestion:We}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:_t.suggestionChips,suggestionChipsConfig:{..._t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{..._t.layout,...e.layout,header:{...(s=_t.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=_t.layout)==null?void 0:c.messages,...(d=e.layout)==null?void 0:d.messages,avatar:{...(g=(u=_t.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(p=e.layout)==null?void 0:p.messages)==null?void 0:m.avatar},timestamp:{...(C=(x=_t.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(E=(T=e.layout)==null?void 0:T.messages)==null?void 0:E.timestamp}},slots:{...(M=_t.layout)==null?void 0:M.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{..._t.markdown,...e.markdown,options:{...(y=_t.markdown)==null?void 0:y.options,...(w=e.markdown)==null?void 0:w.options}},messageActions:{..._t.messageActions,...e.messageActions}}:_t}var op={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},np={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},ap={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:oo,maxWidth:Qi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function qa(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?qa(e,o):o}function Yi(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let c=qa(e,s);c!==void 0&&(t[i]={path:i,value:c,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function sp(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:r}}function ih(e,t){let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?r[o]=ih(a,n):r[o]=n}return r}function db(e,t){return t?ih(e,t):e}function Va(e,t={}){var n,a,s,i,c,d,u,g,p,m,x,C,T;let r={palette:op,semantic:np,components:ap},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(d=e==null?void 0:e.palette)==null?void 0:d.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...r.semantic.colors.interactive,...(p=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:p.interactive},feedback:{...r.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...r.semantic.typography,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:db(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=sp(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(M=>M.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Zi(e){var C,T,E,M,P,y,w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de,J,le,ge,ue,G,ce,Be,ne,ee,ie,vt,Lt,gt,_e,be,Ze,Y,pe,Me,Je,Ge,ke,je,Cr,Wt,ur,Eo,V,j,he,Xe,et,qe,Ne,Pt,Gt,Jt,Pr,z,Ht,oe,we,De,At,ar,sr,wr,Ft,ot,Dt,lt,Yt,so,Rr,ir,Ur,ko,yt,jr,Lo,zo,yo,ht,Nn,Po,On,qr,ga,cn,jo,pn,un,_n,Un,fn,Ct,Gr,Kr,Ir,Mt,io,lo,Xr,mn,Go,gn,Qr,Nt,Wr,co,hn,Ko,xn,Ro,Jr;let t=Yi(e),r={};for(let[xe,dt]of Object.entries(t)){let tr=xe.replace(/\./g,"-");r[`--persona-${tr}`]=dt.value}r["--persona-primary"]=(C=r["--persona-semantic-colors-primary"])!=null?C:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(T=r["--persona-semantic-colors-secondary"])!=null?T:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(E=r["--persona-semantic-colors-accent"])!=null?E:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(M=r["--persona-semantic-colors-surface"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(P=r["--persona-semantic-colors-background"])!=null?P:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(w=r["--persona-semantic-colors-text"])!=null?w:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(b=r["--persona-semantic-colors-text-muted"])!=null?b:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(A=r["--persona-semantic-colors-text-inverse"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(H=r["--persona-semantic-colors-border"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(W=r["--persona-semantic-colors-divider"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(k=r["--persona-components-voice-recording-indicator"])!=null?k:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(N=r["--persona-components-voice-recording-background"])!=null?N:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(q=r["--persona-components-voice-processing-icon"])!=null?q:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Z=r["--persona-components-voice-speaking-icon"])!=null?Z:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-palette-colors-warning-50"],r["--persona-approval-border"]=(Ke=r["--persona-components-approval-requested-border"])!=null?Ke:r["--persona-palette-colors-warning-200"],r["--persona-approval-text"]=(Ce=r["--persona-components-approval-requested-text"])!=null?Ce:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Ie=r["--persona-components-approval-requested-shadow"])!=null?Ie:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-approval-approve-bg"]=(Ue=r["--persona-components-approval-approve-background"])!=null?Ue:r["--persona-palette-colors-success-500"],r["--persona-approval-deny-bg"]=(Te=r["--persona-components-approval-deny-background"])!=null?Te:r["--persona-palette-colors-error-500"],r["--persona-attachment-image-bg"]=(We=r["--persona-components-attachment-image-background"])!=null?We:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(de=r["--persona-components-attachment-image-border"])!=null?de:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(J=r["--persona-semantic-typography-fontFamily"])!=null?J:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(le=r["--persona-semantic-typography-fontSize"])!=null?le:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(ge=r["--persona-semantic-typography-fontWeight"])!=null?ge:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(ue=r["--persona-semantic-typography-lineHeight"])!=null?ue:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(G=r["--persona-palette-radius-sm"])!=null?G:"0.125rem",r["--persona-radius-md"]=(ce=r["--persona-palette-radius-md"])!=null?ce:"0.375rem",r["--persona-radius-lg"]=(Be=r["--persona-palette-radius-lg"])!=null?Be:"0.5rem",r["--persona-radius-xl"]=(ne=r["--persona-palette-radius-xl"])!=null?ne:"0.75rem",r["--persona-radius-full"]=(ee=r["--persona-palette-radius-full"])!=null?ee:"9999px",r["--persona-launcher-radius"]=(vt=(ie=r["--persona-components-launcher-borderRadius"])!=null?ie:r["--persona-palette-radius-full"])!=null?vt:"9999px",r["--persona-launcher-bg"]=(Lt=r["--persona-components-launcher-background"])!=null?Lt:r["--persona-primary"],r["--persona-launcher-fg"]=(gt=r["--persona-components-launcher-foreground"])!=null?gt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(_e=r["--persona-components-launcher-border"])!=null?_e:r["--persona-border"],r["--persona-button-primary-bg"]=(be=r["--persona-components-button-primary-background"])!=null?be:r["--persona-primary"],r["--persona-button-primary-fg"]=(Ze=r["--persona-components-button-primary-foreground"])!=null?Ze:r["--persona-text-inverse"],r["--persona-button-radius"]=(pe=(Y=r["--persona-components-button-primary-borderRadius"])!=null?Y:r["--persona-palette-radius-full"])!=null?pe:"9999px",r["--persona-panel-radius"]=(Je=(Me=r["--persona-components-panel-borderRadius"])!=null?Me:r["--persona-radius-xl"])!=null?Je:"0.75rem",r["--persona-panel-border"]=(Ge=r["--persona-components-panel-border"])!=null?Ge:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(je=(ke=r["--persona-components-panel-shadow"])!=null?ke:r["--persona-palette-shadows-xl"])!=null?je:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(Cr=r["--persona-components-launcher-shadow"])!=null?Cr:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(ur=(Wt=r["--persona-components-input-borderRadius"])!=null?Wt:r["--persona-radius-lg"])!=null?ur:"0.5rem",r["--persona-message-user-radius"]=(V=(Eo=r["--persona-components-message-user-borderRadius"])!=null?Eo:r["--persona-radius-lg"])!=null?V:"0.5rem",r["--persona-message-assistant-radius"]=(he=(j=r["--persona-components-message-assistant-borderRadius"])!=null?j:r["--persona-radius-lg"])!=null?he:"0.5rem",r["--persona-header-bg"]=(Xe=r["--persona-components-header-background"])!=null?Xe:r["--persona-surface"],r["--persona-header-border"]=(et=r["--persona-components-header-border"])!=null?et:r["--persona-divider"],r["--persona-header-icon-bg"]=(qe=r["--persona-components-header-iconBackground"])!=null?qe:r["--persona-primary"],r["--persona-header-icon-fg"]=(Ne=r["--persona-components-header-iconForeground"])!=null?Ne:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Pt=r["--persona-components-header-titleForeground"])!=null?Pt:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Gt=r["--persona-components-header-subtitleForeground"])!=null?Gt:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(Jt=r["--persona-components-header-actionIconForeground"])!=null?Jt:r["--persona-muted"];let o=(Pr=e.components)==null?void 0:Pr.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(z=e.components)==null?void 0:z.introCard;r["--persona-intro-card-bg"]=(Ht=r["--persona-components-introCard-background"])!=null?Ht:r["--persona-surface"],r["--persona-intro-card-radius"]=(oe=r["--persona-components-introCard-borderRadius"])!=null?oe:"1rem",r["--persona-intro-card-padding"]=(we=r["--persona-components-introCard-padding"])!=null?we:"1.5rem",r["--persona-intro-card-shadow"]=(At=(De=n==null?void 0:n.shadow)!=null?De:r["--persona-components-introCard-shadow"])!=null?At:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(ar=r["--persona-components-input-background"])!=null?ar:r["--persona-surface"],r["--persona-input-placeholder"]=(sr=r["--persona-components-input-placeholder"])!=null?sr:r["--persona-text-muted"],r["--persona-message-user-bg"]=(wr=r["--persona-components-message-user-background"])!=null?wr:r["--persona-accent"],r["--persona-message-user-text"]=(Ft=r["--persona-components-message-user-text"])!=null?Ft:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(ot=r["--persona-components-message-user-shadow"])!=null?ot:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Dt=r["--persona-components-message-assistant-background"])!=null?Dt:r["--persona-surface"],r["--persona-message-assistant-text"]=(lt=r["--persona-components-message-assistant-text"])!=null?lt:r["--persona-text"],r["--persona-message-assistant-border"]=(Yt=r["--persona-components-message-assistant-border"])!=null?Yt:r["--persona-border"],r["--persona-message-assistant-shadow"]=(so=r["--persona-components-message-assistant-shadow"])!=null?so:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(ir=(Rr=r["--persona-components-scrollToBottom-background"])!=null?Rr:r["--persona-button-primary-bg"])!=null?ir:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(ko=(Ur=r["--persona-components-scrollToBottom-foreground"])!=null?Ur:r["--persona-button-primary-fg"])!=null?ko:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(yt=r["--persona-components-scrollToBottom-border"])!=null?yt:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(jr=r["--persona-components-scrollToBottom-size"])!=null?jr:"40px",r["--persona-scroll-to-bottom-radius"]=(yo=(zo=(Lo=r["--persona-components-scrollToBottom-borderRadius"])!=null?Lo:r["--persona-button-radius"])!=null?zo:r["--persona-radius-full"])!=null?yo:"9999px",r["--persona-scroll-to-bottom-shadow"]=(Nn=(ht=r["--persona-components-scrollToBottom-shadow"])!=null?ht:r["--persona-palette-shadows-sm"])!=null?Nn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Po=r["--persona-components-scrollToBottom-padding"])!=null?Po:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(On=r["--persona-components-scrollToBottom-gap"])!=null?On:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(ga=(qr=r["--persona-components-scrollToBottom-fontSize"])!=null?qr:r["--persona-palette-typography-fontSize-sm"])!=null?ga:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(cn=r["--persona-components-scrollToBottom-iconSize"])!=null?cn:"14px",r["--persona-tool-bubble-shadow"]=(jo=r["--persona-components-toolBubble-shadow"])!=null?jo:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(pn=r["--persona-components-reasoningBubble-shadow"])!=null?pn:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(un=r["--persona-components-composer-shadow"])!=null?un:"none",r["--persona-md-inline-code-bg"]=(_n=r["--persona-components-markdown-inlineCode-background"])!=null?_n:r["--persona-container"],r["--persona-md-inline-code-color"]=(Un=r["--persona-components-markdown-inlineCode-foreground"])!=null?Un:r["--persona-text"],r["--persona-md-link-color"]=(Ct=(fn=r["--persona-components-markdown-link-foreground"])!=null?fn:r["--persona-accent"])!=null?Ct:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let d=r["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(r["--persona-md-prose-font-family"]=d),r["--persona-md-code-block-bg"]=(Gr=r["--persona-components-markdown-codeBlock-background"])!=null?Gr:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Kr=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Kr:r["--persona-border"],r["--persona-md-code-block-text-color"]=(Ir=r["--persona-components-markdown-codeBlock-textColor"])!=null?Ir:"inherit",r["--persona-md-table-header-bg"]=(Mt=r["--persona-components-markdown-table-headerBackground"])!=null?Mt:r["--persona-container"],r["--persona-md-table-border-color"]=(io=r["--persona-components-markdown-table-borderColor"])!=null?io:r["--persona-border"],r["--persona-md-hr-color"]=(lo=r["--persona-components-markdown-hr-color"])!=null?lo:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(Xr=r["--persona-components-markdown-blockquote-borderColor"])!=null?Xr:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(mn=r["--persona-components-markdown-blockquote-background"])!=null?mn:"transparent",r["--persona-md-blockquote-text-color"]=(Go=r["--persona-components-markdown-blockquote-textColor"])!=null?Go:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(gn=r["--persona-components-collapsibleWidget-container"])!=null?gn:r["--persona-surface"],r["--cw-surface"]=(Qr=r["--persona-components-collapsibleWidget-surface"])!=null?Qr:r["--persona-surface"],r["--cw-border"]=(Nt=r["--persona-components-collapsibleWidget-border"])!=null?Nt:r["--persona-border"],r["--persona-message-border"]=(Wr=r["--persona-components-message-border"])!=null?Wr:r["--persona-border"];let u=e.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(r["--persona-icon-btn-bg"]=g.background),g.border&&(r["--persona-icon-btn-border"]=g.border),g.color&&(r["--persona-icon-btn-color"]=g.color),g.padding&&(r["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(r["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(r["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(r["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(r["--persona-icon-btn-active-border"]=g.activeBorder));let p=u==null?void 0:u.labelButton;p&&(p.background&&(r["--persona-label-btn-bg"]=p.background),p.border&&(r["--persona-label-btn-border"]=p.border),p.color&&(r["--persona-label-btn-color"]=p.color),p.padding&&(r["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(r["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(r["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(r["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(r["--persona-label-btn-gap"]=p.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(r["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(r["--persona-toggle-group-radius"]=m.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let xe=x.toolbar;xe.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,r["--persona-dropdown-bg"]=(co=r["--persona-dropdown-bg"])!=null?co:xe.copyMenuBackground),xe.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,r["--persona-dropdown-border"]=(hn=r["--persona-dropdown-border"])!=null?hn:xe.copyMenuBorder),xe.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,r["--persona-dropdown-shadow"]=(Ko=r["--persona-dropdown-shadow"])!=null?Ko:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(xn=r["--persona-dropdown-radius"])!=null?xn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Ro=r["--persona-dropdown-item-hover-bg"])!=null?Ro:xe.copyMenuItemHoverBackground),xe.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(x!=null&&x.tab){let xe=x.tab;xe.background&&(r["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(r["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(r["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(r["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(r["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(r["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(r["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(x!=null&&x.pane){let xe=x.pane;if(xe.toolbarBackground){let dt=(Jr=qa(e,xe.toolbarBackground))!=null?Jr:xe.toolbarBackground;r["--persona-artifact-toolbar-bg"]=dt}}return r}var lh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var cb={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},dh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ws=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},pb=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Ws()},ip=e=>pb(e),ub=e=>Va(e),fb=e=>{var r;let t=Va(void 0,{validate:!1});return Va({...e,palette:{...t.palette,colors:{...cb.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},$a=e=>{let t=ip(e),r=dh(e==null?void 0:e.theme),o=dh(e==null?void 0:e.darkTheme);return t==="dark"?fb(Is(r!=null?r:{},o!=null?o:{})):ub(r)},mb=e=>Zi(e),Wn=(e,t)=>{let r=$a(t),o=mb(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},el=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Ws())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ws());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(r=>r())}};var ch=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:p=>p.getAttribute("im-preserve")==="true",shouldReAppend:p=>p.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(p,m,x={}){p=u(p);let C=g(m),T=d(p,C,x),E=n(T,()=>i(T,p,C,M=>M.morphStyle==="innerHTML"?(a(M,p,C),Array.from(p.childNodes)):o(M,p,C)));return T.pantry.remove(),E}function o(p,m,x){let C=g(m);return a(p,C,x,m,m.nextSibling),Array.from(C.childNodes)}function n(p,m){var P;if(!p.config.restoreFocus)return m();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return m();let{id:C,selectionStart:T,selectionEnd:E}=x,M=m();return C&&C!==((P=document.activeElement)==null?void 0:P.getAttribute("id"))&&(x=p.target.querySelector(`[id="${C}"]`),x==null||x.focus()),x&&!x.selectionEnd&&E&&x.setSelectionRange(T,E),M}let a=(function(){function p(y,w,b,A=null,H=null){w instanceof HTMLTemplateElement&&b instanceof HTMLTemplateElement&&(w=w.content,b=b.content),A||(A=w.firstChild);for(let W of b.childNodes){if(A&&A!=H){let N=x(y,W,A,H);if(N){N!==A&&T(y,A,N),s(N,W,y),A=N.nextSibling;continue}}if(W instanceof Element){let N=W.getAttribute("id");if(y.persistentIds.has(N)){let q=E(w,N,A,y);s(q,W,y),A=q.nextSibling;continue}}let k=m(w,W,A,y);k&&(A=k.nextSibling)}for(;A&&A!=H;){let W=A;A=A.nextSibling,C(y,W)}}function m(y,w,b,A){if(A.callbacks.beforeNodeAdded(w)===!1)return null;if(A.idMap.has(w)){let H=document.createElement(w.tagName);return y.insertBefore(H,b),s(H,w,A),A.callbacks.afterNodeAdded(H),H}else{let H=document.importNode(w,!0);return y.insertBefore(H,b),A.callbacks.afterNodeAdded(H),H}}let x=(function(){function y(A,H,W,k){let N=null,q=H.nextSibling,Z=0,me=W;for(;me&&me!=k;){if(b(me,H)){if(w(A,me,H))return me;N===null&&(A.idMap.has(me)||(N=me))}if(N===null&&q&&b(me,q)&&(Z++,q=q.nextSibling,Z>=2&&(N=void 0)),A.activeElementAndParents.includes(me))break;me=me.nextSibling}return N||null}function w(A,H,W){let k=A.idMap.get(H),N=A.idMap.get(W);if(!N||!k)return!1;for(let q of k)if(N.has(q))return!0;return!1}function b(A,H){var N,q,Z;let W=A,k=H;return W.nodeType===k.nodeType&&W.tagName===k.tagName&&(!((N=W.getAttribute)!=null&&N.call(W,"id"))||((q=W.getAttribute)==null?void 0:q.call(W,"id"))===((Z=k.getAttribute)==null?void 0:Z.call(k,"id")))}return y})();function C(y,w){var b;if(y.idMap.has(w))P(y.pantry,w,null);else{if(y.callbacks.beforeNodeRemoved(w)===!1)return;(b=w.parentNode)==null||b.removeChild(w),y.callbacks.afterNodeRemoved(w)}}function T(y,w,b){let A=w;for(;A&&A!==b;){let H=A;A=A.nextSibling,C(y,H)}return A}function E(y,w,b,A){var W,k;let H=((k=(W=A.target).getAttribute)==null?void 0:k.call(W,"id"))===w&&A.target||A.target.querySelector(`[id="${w}"]`)||A.pantry.querySelector(`[id="${w}"]`);return M(H,A),P(y,H,b),H}function M(y,w){let b=y.getAttribute("id");for(;y=y.parentNode;){let A=w.idMap.get(y);A&&(A.delete(b),A.size||w.idMap.delete(y))}}function P(y,w,b){if(y.moveBefore)try{y.moveBefore(w,b)}catch{y.insertBefore(w,b)}else y.insertBefore(w,b)}return p})(),s=(function(){function p(M,P,y){return y.ignoreActive&&M===document.activeElement?null:(y.callbacks.beforeNodeMorphed(M,P)===!1||(M instanceof HTMLHeadElement&&y.head.ignore||(M instanceof HTMLHeadElement&&y.head.style!=="morph"?c(M,P,y):(m(M,P,y),E(M,y)||a(y,M,P))),y.callbacks.afterNodeMorphed(M,P)),M)}function m(M,P,y){let w=P.nodeType;if(w===1){let b=M,A=P,H=b.attributes,W=A.attributes;for(let k of W)T(k.name,b,"update",y)||b.getAttribute(k.name)!==k.value&&b.setAttribute(k.name,k.value);for(let k=H.length-1;0<=k;k--){let N=H[k];if(N&&!A.hasAttribute(N.name)){if(T(N.name,b,"remove",y))continue;b.removeAttribute(N.name)}}E(b,y)||x(b,A,y)}(w===8||w===3)&&M.nodeValue!==P.nodeValue&&(M.nodeValue=P.nodeValue)}function x(M,P,y){if(M instanceof HTMLInputElement&&P instanceof HTMLInputElement&&P.type!=="file"){let w=P.value,b=M.value;C(M,P,"checked",y),C(M,P,"disabled",y),P.hasAttribute("value")?b!==w&&(T("value",M,"update",y)||(M.setAttribute("value",w),M.value=w)):T("value",M,"remove",y)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&P instanceof HTMLOptionElement)C(M,P,"selected",y);else if(M instanceof HTMLTextAreaElement&&P instanceof HTMLTextAreaElement){let w=P.value,b=M.value;if(T("value",M,"update",y))return;w!==b&&(M.value=w),M.firstChild&&M.firstChild.nodeValue!==w&&(M.firstChild.nodeValue=w)}}function C(M,P,y,w){let b=P[y],A=M[y];if(b!==A){let H=T(y,M,"update",w);H||(M[y]=P[y]),b?H||M.setAttribute(y,""):T(y,M,"remove",w)||M.removeAttribute(y)}}function T(M,P,y,w){return M==="value"&&w.ignoreActiveValue&&P===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(M,P,y)===!1}function E(M,P){return!!P.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return p})();function i(p,m,x,C){if(p.head.block){let T=m.querySelector("head"),E=x.querySelector("head");if(T&&E){let M=c(T,E,p);return Promise.all(M).then(()=>{let P=Object.assign(p,{head:{block:!1,ignore:!0}});return C(P)})}}return C(p)}function c(p,m,x){let C=[],T=[],E=[],M=[],P=new Map;for(let w of m.children)P.set(w.outerHTML,w);for(let w of p.children){let b=P.has(w.outerHTML),A=x.head.shouldReAppend(w),H=x.head.shouldPreserve(w);b||H?A?T.push(w):(P.delete(w.outerHTML),E.push(w)):x.head.style==="append"?A&&(T.push(w),M.push(w)):x.head.shouldRemove(w)!==!1&&T.push(w)}M.push(...P.values());let y=[];for(let w of M){let b=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(b)!==!1){if("href"in b&&b.href||"src"in b&&b.src){let A,H=new Promise(function(W){A=W});b.addEventListener("load",function(){A()}),y.push(H)}p.appendChild(b),x.callbacks.afterNodeAdded(b),C.push(b)}}for(let w of T)x.callbacks.beforeNodeRemoved(w)!==!1&&(p.removeChild(w),x.callbacks.afterNodeRemoved(w));return x.head.afterHeadMorphed(p,{added:C,kept:E,removed:T}),y}let d=(function(){function p(y,w,b){let{persistentIds:A,idMap:H}=M(y,w),W=m(b),k=W.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(k))throw`Do not understand how to morph style ${k}`;return{target:y,newContent:w,config:W,morphStyle:k,ignoreActive:W.ignoreActive,ignoreActiveValue:W.ignoreActiveValue,restoreFocus:W.restoreFocus,idMap:H,persistentIds:A,pantry:x(),activeElementAndParents:C(y),callbacks:W.callbacks,head:W.head}}function m(y){let w=Object.assign({},t);return Object.assign(w,y),w.callbacks=Object.assign({},t.callbacks,y.callbacks),w.head=Object.assign({},t.head,y.head),w}function x(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function C(y){let w=[],b=document.activeElement;if((b==null?void 0:b.tagName)!=="BODY"&&y.contains(b))for(;b&&(w.push(b),b!==y);)b=b.parentElement;return w}function T(y){var b;let w=Array.from(y.querySelectorAll("[id]"));return(b=y.getAttribute)!=null&&b.call(y,"id")&&w.push(y),w}function E(y,w,b,A){for(let H of A){let W=H.getAttribute("id");if(w.has(W)){let k=H;for(;k;){let N=y.get(k);if(N==null&&(N=new Set,y.set(k,N)),N.add(W),k===b)break;k=k.parentElement}}}}function M(y,w){let b=T(y),A=T(w),H=P(b,A),W=new Map;E(W,H,y,b);let k=w.__idiomorphRoot||w;return E(W,H,k,A),{persistentIds:H,idMap:W}}function P(y,w){let b=new Set,A=new Map;for(let{id:W,tagName:k}of y)A.has(W)?b.add(W):A.set(W,k);let H=new Set;for(let{id:W,tagName:k}of w)H.has(W)?b.add(W):A.get(W)===k&&H.add(W);for(let W of b)H.delete(W);return H}return p})(),{normalizeElement:u,normalizeParent:g}=(function(){let p=new WeakSet;function m(E){return E instanceof Document?E.documentElement:E}function x(E){if(E==null)return document.createElement("div");if(typeof E=="string")return x(T(E));if(p.has(E))return E;if(E instanceof Node){if(E.parentNode)return new C(E);{let M=document.createElement("div");return M.append(E),M}}else{let M=document.createElement("div");for(let P of[...E])M.append(P);return M}}class C{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],P=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;P&&P!=this.nextSibling;)M.push(P),P=P.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((P,y)=>{if(y instanceof Element){y.matches(M)&&P.push(y);let w=y.querySelectorAll(M);for(let b=0;b<w.length;b++)P.push(w[b])}return P},[])}insertBefore(M,P){return this.realParentNode.insertBefore(M,P)}moveBefore(M,P){return this.realParentNode.moveBefore(M,P)}get __idiomorphRoot(){return this.originalNode}}function T(E){let M=new DOMParser,P=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(P.match(/<\/html>/)||P.match(/<\/head>/)||P.match(/<\/body>/)){let y=M.parseFromString(E,"text/html");if(P.match(/<\/html>/))return p.add(y),y;{let w=y.firstChild;return w&&p.add(w),w}}else{let w=M.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return p.add(w),w}}return{normalizeElement:m,normalizeParent:x}})();return{morph:r,defaults:t}})();var tl=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;ch.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",d=(i=a.textContent)!=null?i:"";if(c!==d)return}return!1}}}}})};var rl={index:-1,draft:""};function ph(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...rl}}}function uh(e,t){var r,o,n,a,s,i,c,d,u,g,p,m,x,C,T,E,M,P,y,w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de,J,le;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(u=(d=e.llmContent)==null?void 0:d.length)!=null?u:0,(p=(g=e.approval)==null?void 0:g.status)!=null?p:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(T=(C=e.toolCall)==null?void 0:C.name)!=null?T:"",(P=(M=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:M.length)!=null?P:0,(A=(b=(w=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:w[e.toolCall.chunks.length-1])==null?void 0:b.slice(-32))!=null?A:"",typeof((H=e.toolCall)==null?void 0:H.args)=="string"?e.toolCall.args.length:(W=e.toolCall)!=null&&W.args?JSON.stringify(e.toolCall.args).length:0,(q=(N=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:N.length)!=null?q:0,(Ce=(Ke=(me=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:Ke.length)!=null?Ce:0,(We=(Te=(Ue=(Ie=e.reasoning)==null?void 0:Ie.chunks)==null?void 0:Ue[e.reasoning.chunks.length-1])==null?void 0:Te.slice(-32))!=null?We:"",(J=(de=e.contentParts)==null?void 0:de.length)!=null?J:0,(le=e.stopReason)!=null?le:"",t].join("\0")}function fh(){return new Map}function mh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function gh(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function hh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function ol(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function sn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function da(e,t){return sn(e)-e.scrollTop<=t}function nl(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,u=r-o;return s||Math.abs(u)<a?{action:"none",delta:u,nextLastScrollTop:r}:!t&&n&&(!d||u>0)?{action:"resume",delta:u,nextLastScrollTop:r}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:u,nextLastScrollTop:r}:{action:"none",delta:u,nextLastScrollTop:r}}function al(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}function xh(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function yh(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),r=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:r}}function bh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var kr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Lr=1e5,Hn=Lr+1;var Hs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},gb=["pre","code","a","script","style"],sl=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:Hs.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Hs.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Hs.speed,duration:(n=e==null?void 0:e.duration)!=null?n:Hs.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:Hs.buffer}},Ch=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Bs=new Map;for(let e of Ch)Bs.set(e.name,e);var ca=e=>{Bs.set(e.name,e)},cp=e=>{Ch.some(t=>t.name===e)||Bs.delete(e)},pp=()=>Array.from(Bs.keys()),Ds=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Bs.get(e))!=null?o:null},il=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
18
+ `);return a<0?"":e.slice(0,a)}return e},hb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},xb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},lp=/\s/,yb=(e,t)=>{let r=e.parentNode;for(;r;){if(r.nodeType===1){let o=r;if(t.has(o.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},bb=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(lp.test(a[i])){let d=i;for(;d<a.length&&lp.test(a[d]);)d+=1;s.appendChild(o.createTextNode(a.slice(i,d))),i=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let u=i;for(;u<a.length&&!lp.test(a[u]);)d.appendChild(hb(o,a[u],t,r.value)),r.value+=1,u+=1;s.appendChild(d),i=u}n.replaceChild(s,e)},vb=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let d of i)d&&(/^\s+$/.test(d)?s.appendChild(o.createTextNode(d)):(s.appendChild(xb(o,d,t,r.value)),r.value+=1));n.replaceChild(s,e)},Fs=(e,t,r,o)=>{var g,p;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((g=o==null?void 0:o.skipTags)!=null?g:gb).map(m=>m.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)yb(c,a)||i.push(c),c=s.nextNode();let d={value:(p=o==null?void 0:o.startIndex)!=null?p:0},u=t==="char"?bb:vb;for(let m of i)u(m,r,d);return n.innerHTML},ll=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ns=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},vh=new WeakMap,Cb=(e,t)=>{var a;if(!e.styles)return;let r=vh.get(t);if(r||(r=new Set,vh.set(t,r)),r.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:(a=t.ownerDocument)!=null?a:document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)},dp=new WeakMap,wb=(e,t)=>{if(!e.onAttach)return;let r=dp.get(t);if(r||(r=new Map,dp.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},wh=e=>{let t=dp.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},up=(e,t)=>{Cb(e,t),wb(e,t)};function fp(e,t=Lr){let r=e.style.position,o=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=o,e.style.isolation=n}}var Os=0,Bn=null;function mp(e=document){var r;if(Os++,Os===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Bn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Os=Math.max(0,Os-1),Os===0&&Bn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Bn.originalOverflow,n.style.position=Bn.originalPosition,n.style.top=Bn.originalTop,n.style.width=Bn.originalWidth,a.scrollTo(0,Bn.scrollY),Bn=null}}}var _s={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},pr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Dn=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},no=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:_s.side,width:(n=t==null?void 0:t.width)!=null?n:_s.width,animate:(a=t==null?void 0:t.animate)!=null?a:_s.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:_s.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:_s.maxHeight}};var To={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Sb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",dl=(e,t={})=>{var T,E,M,P,y,w;let{showClose:r=!0,wrapperClassName:o=Sb,buttonSize:n,iconSize:a="28px"}=t,s=(T=e==null?void 0:e.launcher)!=null?T:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=S("div",o),d=(M=s.closeButtonTooltipText)!=null?M:"Close chat",u=(P=s.closeButtonShowTooltip)!=null?P:!0,g=(y=s.closeButtonIconName)!=null?y:"x",p=(w=s.closeButtonIconText)!=null?w:"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=kt("button",{className:vs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||_r.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),C=ve(g,a,"currentColor",1);if(C?(C.style.display="block",x.appendChild(C)):x.textContent=p,c.appendChild(x),u&&d){let b=null,A=()=>{if(b)return;let W=x.ownerDocument,k=W.body;if(!k)return;b=Vo(W,"div","persona-clear-chat-tooltip"),b.textContent=d;let N=Vo(W,"div");N.className="persona-clear-chat-tooltip-arrow",b.appendChild(N);let q=x.getBoundingClientRect();b.style.position="fixed",b.style.zIndex=String(Hn),b.style.left=`${q.left+q.width/2}px`,b.style.top=`${q.top-8}px`,b.style.transform="translate(-50%, -100%)",k.appendChild(b)},H=()=>{b&&b.parentNode&&(b.parentNode.removeChild(b),b=null)};c.addEventListener("mouseenter",A),c.addEventListener("mouseleave",H),x.addEventListener("focus",A),x.addEventListener("blur",H),c._cleanupTooltip=()=>{H(),c.removeEventListener("mouseenter",A),c.removeEventListener("mouseleave",H),x.removeEventListener("focus",A),x.removeEventListener("blur",H)}}return{button:x,wrapper:c}},Ab="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",cl=(e,t={})=>{var b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue;let{wrapperClassName:r=Ab,buttonSize:o,iconSize:n="20px"}=t,s=(A=((b=e==null?void 0:e.launcher)!=null?b:{}).clearChat)!=null?A:{},i=(H=o!=null?o:s.size)!=null?H:"32px",c=(W=s.iconName)!=null?W:"refresh-cw",d=(k=s.iconColor)!=null?k:"",u=(N=s.backgroundColor)!=null?N:"",g=(q=s.borderWidth)!=null?q:"",p=(Z=s.borderColor)!=null?Z:"",m=(me=s.borderRadius)!=null?me:"",x=(Ke=s.paddingX)!=null?Ke:"",C=(Ce=s.paddingY)!=null?Ce:"",T=(Ie=s.tooltipText)!=null?Ie:"Clear chat",E=(Ue=s.showTooltip)!=null?Ue:!0,M=S("div",r),P=!!(g||p),y=kt("button",{className:vs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!P&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:d||_r.actionIconColor,backgroundColor:u||void 0,border:P?`${g||"0px"} solid ${p||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),w=ve(c,n,"currentColor",1);if(w&&(w.style.display="block",y.appendChild(w)),M.appendChild(y),E&&T){let Te=null,We=()=>{if(Te)return;let J=y.ownerDocument,le=J.body;if(!le)return;Te=Vo(J,"div","persona-clear-chat-tooltip"),Te.textContent=T;let ge=Vo(J,"div");ge.className="persona-clear-chat-tooltip-arrow",Te.appendChild(ge);let ue=y.getBoundingClientRect();Te.style.position="fixed",Te.style.zIndex=String(Hn),Te.style.left=`${ue.left+ue.width/2}px`,Te.style.top=`${ue.top-8}px`,Te.style.transform="translate(-50%, -100%)",le.appendChild(Te)},de=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};M.addEventListener("mouseenter",We),M.addEventListener("mouseleave",de),y.addEventListener("focus",We),y.addEventListener("blur",de),M._cleanupTooltip=()=>{de(),M.removeEventListener("mouseenter",We),M.removeEventListener("mouseleave",de),y.removeEventListener("focus",We),y.removeEventListener("blur",de)}}return{button:y,wrapper:M}};var _r={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ln=e=>{var w,b,A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We;let{config:t,showClose:r=!0}=e,o=kt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),n=(w=t==null?void 0:t.launcher)!=null?w:{},a=(b=n.headerIconSize)!=null?b:"48px",s=(A=n.closeButtonPlacement)!=null?A:"inline",i=(H=n.headerIconHidden)!=null?H:!1,c=n.headerIconName,d=kt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(c){let de=parseFloat(a)||24,J=ve(c,de*.6,"currentColor",1);J?d.replaceChildren(J):d.textContent=(k=(W=t==null?void 0:t.launcher)==null?void 0:W.agentIconText)!=null?k:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let de=S("img");de.src=t.launcher.iconUrl,de.alt="",de.className="persona-rounded-xl persona-object-cover",de.style.height=a,de.style.width=a,d.replaceChildren(de)}else d.textContent=(Z=(q=t==null?void 0:t.launcher)==null?void 0:q.agentIconText)!=null?Z:"\u{1F4AC}";let u=S("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=kt("span",{className:"persona-text-base persona-font-semibold",text:(Ke=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?Ke:"Chat Assistant",style:{color:_r.titleColor}}),p=kt("span",{className:"persona-text-xs",text:(Ie=(Ce=t==null?void 0:t.launcher)==null?void 0:Ce.subtitle)!=null?Ie:"Here to help you get answers fast",style:{color:_r.subtitleColor}});u.append(g,p),i?o.append(u):o.append(d,u);let m=(Ue=n.clearChat)!=null?Ue:{},x=(Te=m.enabled)!=null?Te:!0,C=(We=m.placement)!=null?We:"inline",T=null,E=null;if(x){let J=cl(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=J.button,E=J.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let M=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:y}=dl(t,{showClose:r,wrapperClassName:M});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:d,headerTitle:g,headerSubtitle:p,closeButton:P,closeButtonWrapper:y,clearChatButton:T,clearChatButtonWrapper:E}},pa=(e,t,r)=>{var s,i,c,d;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(d=(c=o.clearChat)==null?void 0:c.placement)!=null?d:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Fn(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=S("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Hn)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of t){if(m.dividerBefore){let T=document.createElement("hr");s.appendChild(T)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let T=ve(m.icon,16,"currentColor",1.5);T&&x.appendChild(T)}let C=document.createElement("span");C.textContent=m.label,x.appendChild(C),x.addEventListener("click",T=>{T.stopPropagation(),u(),r(m.id)}),s.appendChild(x)}let i=null;function c(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function d(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!s.contains(x.target)&&!o.contains(x.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){s.classList.add("persona-hidden"),i==null||i(),i=null}function g(){s.classList.contains("persona-hidden")?d():u()}function p(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:u,toggle:g,destroy:p}}function yr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=S("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let d=ve(t,o!=null?o:16,"currentColor",n!=null?n:2);if(d&&c.appendChild(d),s&&c.addEventListener("click",s),i)for(let[u,g]of Object.entries(i))c.setAttribute(u,g);return c}function Us(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let u=S("button",d);if(u.type="button",u.setAttribute("aria-label",r),t){let p=ve(t,a!=null?a:14,"currentColor",2);p&&u.appendChild(p)}let g=S("span");if(g.textContent=r,u.appendChild(g),i&&u.addEventListener("click",i),c)for(let[p,m]of Object.entries(c))u.setAttribute(p,m);return u}function Sh(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=S("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===s?"true":"false")}for(let u of t){let g;u.icon?g=yr({icon:u.icon,label:u.label,onClick:()=>{s=u.id,c(),o(u.id)}}):(g=S("button","persona-icon-btn"),g.type="button",g.setAttribute("aria-label",u.label),g.title=u.label,g.textContent=u.label,g.addEventListener("click",()=>{s=u.id,c(),o(u.id)})),g.setAttribute("aria-pressed",u.id===s?"true":"false"),i.push({id:u.id,btn:g}),a.appendChild(g)}function d(u){s=u,c()}return{element:a,setSelected:d}}function pl(e){var m,x;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,d=S("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let u=S("span","persona-combo-btn-label");u.textContent=t,d.appendChild(u);let g=ve(r,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",d.appendChild(g)),c&&(d.style.borderRadius=(m=c.borderRadius)!=null?m:"10px",d.style.padding=(x=c.padding)!=null?x:"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{var C,T;d.style.backgroundColor=(C=c.background)!=null?C:"",d.style.borderColor=(T=c.border)!=null?T:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let p=Fn({items:o,onSelect:C=>{d.setAttribute("aria-expanded","false"),n(C)},anchor:d,position:a,portal:s});return s||d.appendChild(p.element),d.addEventListener("click",C=>{C.stopPropagation();let T=!p.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",T?"false":"true"),p.toggle()}),d.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),d.click())}),{element:d,setLabel:C=>{u.textContent=C,d.setAttribute("aria-label",C)},open:()=>{d.setAttribute("aria-expanded","true"),p.show()},close:()=>{d.setAttribute("aria-expanded","false"),p.hide()},toggle:()=>{let C=!p.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",C?"false":"true"),p.toggle()},destroy:()=>{p.destroy(),d.remove()}}}var gp=e=>{var o;let t=ln({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(r){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>r()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function Mb(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=S("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let c=ve(s.icon,14,"currentColor",2);c&&i.appendChild(c)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let c=S("div","persona-relative");c.appendChild(i);let d=Fn({items:s.menuItems,onSelect:u=>r==null?void 0:r(u),anchor:c,position:"bottom-left"});c.appendChild(d.element),i.addEventListener("click",u=>{u.stopPropagation(),d.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var hp=e=>{var M,P,y,w,b,A,H,W,k;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(M=t==null?void 0:t.launcher)!=null?M:{},i=S("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=n==null?void 0:n.titleMenu,d,u;if(c)d=pl({label:(P=s.title)!=null?P:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,d.style.color=_r.titleColor,u=(y=d.querySelector(".persona-combo-btn-label"))!=null?y:d;else{if(d=S("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=S("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=_r.titleColor,u.textContent=(w=s.title)!=null?w:"Chat Assistant",d.appendChild(u),Mb(d,n==null?void 0:n.trailingActions,(b=n==null?void 0:n.onAction)!=null?b:a),n!=null&&n.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let q=n.onTitleClick;d.addEventListener("click",Z=>{Z.target.closest("button")||q()}),d.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),q())})}let N=n==null?void 0:n.titleRowHover;N&&(d.style.borderRadius=(A=N.borderRadius)!=null?A:"10px",d.style.padding=(H=N.padding)!=null?H:"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{var q,Z;d.style.backgroundColor=(q=N.background)!=null?q:"",d.style.borderColor=(Z=N.border)!=null?Z:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let g=(W=s.closeButtonSize)!=null?W:"32px",p=S("div",""),m=S("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none",m.style.color=s.closeButtonColor||_r.actionIconColor;let x=(k=s.closeButtonIconName)!=null?k:"x",C=ve(x,"28px","currentColor",1);C?m.appendChild(C):m.textContent="\xD7",o&&m.addEventListener("click",o),p.appendChild(m),i.appendChild(p);let T=S("div");T.style.display="none";let E=S("span");return E.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:E,closeButton:m,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},ul={default:gp,minimal:hp},xp=e=>{var t;return(t=ul[e])!=null?t:ul.default},za=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let d=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=S("div");u.style.display="none";let g=S("span"),p=S("span"),m=S("button");m.style.display="none";let x=S("div");return x.style.display="none",{header:d,iconHolder:u,headerTitle:g,headerSubtitle:p,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=xp(o)({config:e,showClose:(c=(i=t==null?void 0:t.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?c:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var fl=e=>{var s,i;let t=S("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,o=20;t.style.maxHeight=`${r*o}px`,t.style.overflowY="auto";let n=()=>{let c=parseFloat(t.style.maxHeight);return Number.isFinite(c)&&c>0?c:r*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let c=Math.min(t.scrollHeight,n());t.style.height=`${c}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:a}},ml=e=>{var w,b,A,H,W,k,N,q,Z,me,Ke,Ce;let t=(w=e==null?void 0:e.sendButton)!=null?w:{},r=(b=t.useIcon)!=null?b:!1,o=(A=t.iconText)!=null?A:"\u2191",n=t.iconName,a=(H=t.stopIconName)!=null?H:"square",s=(W=t.tooltipText)!=null?W:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",c=(q=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?q:"Send",d=(me=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?me:"Stop",u=(Ke=t.showTooltip)!=null?Ke:!1,g=(Ce=t.size)!=null?Ce:"40px",p=t.backgroundColor,m=t.textColor,x=S("div","persona-send-button-wrapper"),C=kt("button",{className:vs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!p&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?g:void 0,height:r?g:void 0,minWidth:r?g:void 0,minHeight:r?g:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:r&&p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=null,E=null;if(r){let Ie=parseFloat(g)||24,Ue=(m==null?void 0:m.trim())||"currentColor";n?(T=ve(n,Ie,Ue,2),T?C.appendChild(T):C.textContent=o):C.textContent=o,E=ve(a,Ie,Ue,2)}else C.textContent=c;let M=null;u&&s&&(M=S("div","persona-send-button-tooltip"),M.textContent=s,x.appendChild(M)),C.setAttribute("aria-label",s),x.appendChild(C);let P="send";return{button:C,wrapper:x,setMode:Ie=>{if(Ie===P)return;P=Ie;let Ue=Ie==="stop"?i:s;if(C.setAttribute("aria-label",Ue),M&&(M.textContent=Ue),r){if(T&&E){let Te=Ie==="stop"?E:T;C.replaceChildren(Te)}}else C.textContent=Ie==="stop"?d:c}}},gl=e=>{var M,P,y,w,b,A,H,W,k,N,q,Z;let t=(M=e==null?void 0:e.voiceRecognition)!=null?M:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(o||n))return null;let s=(w=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?w:"40px",i=(b=t.iconName)!=null?b:"mic",c=(A=t.iconSize)!=null?A:s,d=parseFloat(c)||24,u=(W=t.backgroundColor)!=null?W:(H=e==null?void 0:e.sendButton)==null?void 0:H.backgroundColor,g=(N=t.iconColor)!=null?N:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor,p=S("div","persona-send-button-wrapper"),m=kt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ve(i,d,g||"currentColor",1.5);C?m.appendChild(C):m.textContent="\u{1F3A4}",p.appendChild(m);let T=(q=t.tooltipText)!=null?q:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&T){let me=S("div","persona-send-button-tooltip");me.textContent=T,p.appendChild(me)}return{button:m,wrapper:p}},hl=e=>{var x,C,T,E,M,P,y,w;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(T=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?T:"40px",o=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=S("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:an).join(","),n.multiple=((M=t.maxFiles)!=null?M:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(P=t.buttonIconName)!=null?P:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),d=S("div","persona-send-button-wrapper"),u=kt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let g=ve(a,c,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",b=>{b.preventDefault(),n.click()}),d.appendChild(u);let p=(w=t.buttonTooltipText)!=null?w:"Attach file",m=S("div","persona-send-button-tooltip");return m.textContent=p,d.appendChild(m),{button:u,wrapper:d,input:n,previewsContainer:o}},xl=e=>{var s,i,c;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=S("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let d=S("a");d.href=t.idleLink,d.target="_blank",d.rel="noopener noreferrer",d.textContent=a,d.style.color="inherit",d.style.textDecoration="none",o.appendChild(d)}else o.textContent=a;return o},yl=()=>kt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ja=e=>{var x,C,T,E,M,P;let{config:t}=e,r=kt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=yl(),n=kt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=fl(t);s();let i=ml(t),c=gl(t),d=hl(t),u=xl(t);d&&(d.previewsContainer.style.gap="8px",n.append(d.previewsContainer,d.input)),n.append(a);let g=kt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),p=S("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=S("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&p.append(d.wrapper),c&&m.append(c.wrapper),m.append(i.wrapper),g.append(p,m),n.append(g),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),r.append(o,n,u),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,statusText:u,attachmentButton:(T=d==null?void 0:d.button)!=null?T:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(M=d==null?void 0:d.input)!=null?M:null,attachmentPreviewsContainer:(P=d==null?void 0:d.previewsContainer)!=null?P:null,actionsRow:g,leftActions:p,rightActions:m,setSendButtonMode:i.setMode}};var Ah=()=>{let e=kt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=S("span","persona-pill-peek__icon"),r=ve("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=S("span","persona-pill-peek__text"),n=S("span","persona-pill-peek__caret"),a=ve("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Mh=e=>{var x,C,T,E,M,P;let{config:t}=e,r=kt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=yl();o.style.display="none";let n=xl(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=fl(t);a.style.maxHeight="100px",s();let i=ml(t),c=gl(t),d=hl(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let u=kt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=S("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&g.append(d.wrapper);let p=S("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&p.append(c.wrapper),p.append(i.wrapper),u.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),d&&u.append(d.input),u.append(g,a,p),d&&r.append(d.previewsContainer),r.append(u,o,n);let m=u;return{footer:r,suggestions:o,composerForm:u,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,statusText:n,attachmentButton:(T=d==null?void 0:d.button)!=null?T:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(M=d==null?void 0:d.input)!=null?M:null,attachmentPreviewsContainer:(P=d==null?void 0:d.previewsContainer)!=null?P:null,actionsRow:m,leftActions:g,rightActions:p,setSendButtonMode:i.setMode}};var Th=e=>{var u,g,p,m,x,C,T,E,M,P,y,w,b,A,H,W,k;let t=(g=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?g:!0,r=pr(e);if(Dn(e)){let N=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.composerBar)!=null?m:{},q=S("div","persona-widget-wrapper persona-fixed persona-transition");q.setAttribute("data-persona-composer-bar",""),q.dataset.state="collapsed",q.dataset.expandedSize=(x=N.expandedSize)!=null?x:"anchored",q.style.zIndex=String((T=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?T:Lr);let Z=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",q.appendChild(Z);let me=S("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=N.expandedSize)!=null?E:"anchored",me.style.zIndex=String((P=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?P:Lr),{wrapper:q,panel:Z,pillRoot:me}}if(r){let N=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),q=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(q),{wrapper:N,panel:q}}if(!t){let N=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),q=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?w:"100%";return N.style.width=Z,q.style.width="100%",N.appendChild(q),{wrapper:N,panel:q}}let n=(b=e==null?void 0:e.launcher)!=null?b:{},a=n.position&&To[n.position]?To[n.position]:To["bottom-right"],s=S("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((H=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?H:Lr);let i=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(k=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?k:e==null?void 0:e.launcherWidth,d=c!=null?c:oo;return i.style.width=d,i.style.maxWidth=d,s.appendChild(i),{wrapper:s,panel:i}},Tb=(e,t)=>{var y,w,b,A,H,W,k,N,q;let r=S("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=dl(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(b=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:w.enabled)!=null?b:!0,s=null,i=null;if(a){let Z=cl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=kt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=kt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let u=kt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(H=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?H:"Hello \u{1F44B}"}),g=kt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),p=kt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,g),m=S("div","persona-flex persona-flex-col persona-gap-3"),x=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((q=e==null?void 0:e.copy)==null?void 0:q.showWelcomeCard)!==!1||(p.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(p,m);let T=kt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=Mh({config:e}),{root:M,textNode:P}=Ah();return r.append(c,n,d,T),i&&r.appendChild(i),{container:r,body:d,messagesWrapper:m,composerOverlay:T,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:u,introSubtitle:g,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("span"),header:c,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:M,peekTextNode:P}},Eh=(e,t=!0)=>{var T,E,M,P,y,w,b,A,H;if(Dn(e))return Tb(e,t);let r=kt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=(T=e==null?void 0:e.layout)==null?void 0:T.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?za(e,o,{showClose:t}):ln({config:e,showClose:t}),s=kt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let i=kt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(P=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?P:"Hello \u{1F44B}"}),c=kt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(w=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?w:"Ask anything about your account or products."}),d=kt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:pr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),u=S("div","persona-flex persona-flex-col persona-gap-3"),g=(b=e==null?void 0:e.layout)==null?void 0:b.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((A=e==null?void 0:e.copy)==null?void 0:A.showWelcomeCard)!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,u);let m=ja({config:e}),x=((H=e==null?void 0:e.layout)==null?void 0:H.showFooter)!==!1;n?pa(r,a,e):(a.header.style.display="none",pa(r,a,e)),r.append(s);let C=kt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return x||(m.footer.style.display="none"),r.append(m.footer),r.append(C),{container:r,body:s,messagesWrapper:u,composerOverlay:C,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:c,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var yp=(e,t)=>{let r=S("button");r.type="button",r.innerHTML=`
19
19
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
20
20
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
21
21
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -23,14 +23,14 @@ _Details: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]
23
23
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
24
24
  </span>
25
25
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
26
- `,r.addEventListener("click",t);let o=a=>{var P,y,w,b,A,H,W,k,N,q,Z,me,Ke;let s=(P=a.launcher)!=null?P:{},i=pr(a),c=r.querySelector("[data-role='launcher-title']");if(c){let Ce=(y=s.title)!=null?y:"Chat Assistant";c.textContent=Ce,c.setAttribute("title",Ce)}let d=r.querySelector("[data-role='launcher-subtitle']");if(d){let Ce=(w=s.subtitle)!=null?w:"Here to help you get answers fast";d.textContent=Ce,d.setAttribute("title",Ce)}let u=r.querySelector(".persona-flex-col");u&&(s.textHidden||i?u.style.display="none":u.style.display="");let g=r.querySelector("[data-role='launcher-icon']");if(g)if(s.agentIconHidden)g.style.display="none";else{let Ce=(b=s.agentIconSize)!=null?b:"40px";if(g.style.height=Ce,g.style.width=Ce,g.innerHTML="",s.agentIconName){let Ie=parseFloat(Ce)||24,Ue=ve(s.agentIconName,Ie*.6,"var(--persona-text-inverse, #ffffff)",2);Ue?(g.appendChild(Ue),g.style.display=""):(g.textContent=(A=s.agentIconText)!=null?A:"\u{1F4AC}",g.style.display="")}else s.iconUrl?g.style.display="none":(g.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}",g.style.display="")}let p=r.querySelector("[data-role='launcher-image']");if(p){let Ce=(W=s.agentIconSize)!=null?W:"40px";p.style.height=Ce,p.style.width=Ce,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(p.src=s.iconUrl,p.style.display="block"):p.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ce=(k=s.callToActionIconSize)!=null?k:"32px";m.style.height=Ce,m.style.width=Ce,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Ie=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,Ie=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let Ue=parseFloat(Ce)||24,Te=Math.max(Ue-Ie,8),We=ve(s.callToActionIconName,Te,"currentColor",2);We?m.appendChild(We):m.textContent=(N=s.callToActionIconText)!=null?N:"\u2197"}else m.textContent=(q=s.callToActionIconText)!=null?q:"\u2197"}let x=s.position&&To[s.position]?To[s.position]:To["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";r.className=i?T:`${C} ${x}`,i||(r.style.zIndex=String((Z=s.zIndex)!=null?Z:Lr));let E="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(me=s.border)!=null?me:E,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:M,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(Ke=s.collapsedMaxWidth)!=null?Ke:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},n=()=>{r.removeEventListener("click",t),r.remove()};return e&&o(e),{element:r,update:o,destroy:n}};var Th=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=Ah(e),a=Mh(e,t),s={wrapper:r,panel:o,pillRoot:n},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:c,composer:d,replaceHeader:p=>(c.element.replaceWith(p.header),c.element=p.header,c.iconHolder=p.iconHolder,c.headerTitle=p.headerTitle,c.headerSubtitle=p.headerSubtitle,c.closeButton=p.closeButton,c.closeButtonWrapper=p.closeButtonWrapper,c.clearChatButton=p.clearChatButton,c.clearChatButtonWrapper=p.clearChatButtonWrapper,p),replaceComposer:p=>{d.footer.replaceWith(p),d.footer=p}}},yp=({config:e,plugins:t,onToggle:r})=>{let o=t.find(a=>a.renderLauncher);if(o!=null&&o.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>xp(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=xp(e,r);return{instance:n,element:n.element}};var Tb=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}},Eb=(e,t)=>{if(!e)return null;let r=Tb(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},kb=(e,t)=>{let r=S("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},Lb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},bp=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(":"))},vp=320,kh=320,Pb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Rb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ib=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Wb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Hb=(e,t,r)=>{if(e.length===0)return null;try{let o=S("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,c)=>{var g;let d=S("img");d.alt=((g=i.alt)==null?void 0:g.trim())||`Attached image ${c+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${vp}px`,d.style.maxHeight=`${kh}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;n+=1,d.addEventListener("error",()=>{u||(u=!0,n=Math.max(0,n-1),d.remove(),n===0&&s())}),d.addEventListener("load",()=>{u=!0}),Lb(i.image)?(d.src=i.image,o.appendChild(d)):(u=!0,n=Math.max(0,n-1),d.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},Bb=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!bp(o.audio))return;let n=S("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${vp}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Db=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!bp(o.video))return;let n=S("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${vp}px`,n.style.maxHeight=`${kh}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}},Fb=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!bp(o.data))return;let n=S("a");n.href=o.data,n.download=o.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=o.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},pa=()=>{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},Cp=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:pa};if(t){let n=t(o);if(n!==null)return n}return pa()},Nb=(e,t)=>{let r=S("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let n=S("img");n.src=o,n.alt=t==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(n)}else r.textContent=o,r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},Eh=(e,t,r="div")=>{let o=S(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?o.textContent=t.format(n):o.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Ob=(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},wp=(e,t,r)=>{var x,C,T,E,M,P,y;let o=(x=t.showCopy)!=null?x:!0,n=(C=t.showUpvote)!=null?C:!0,a=(T=t.showDownvote)!=null?T:!0,s=(E=t.showReadAloud)!=null?E:!1;if(!o&&!n&&!a&&!s){let w=S("div");return w.style.display="none",w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id),w}let i=(M=t.visibility)!=null?M:"hover",c=(P=t.align)!=null?P:"right",d=(y=t.layout)!=null?y:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[c],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=S("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${g} ${i==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=(w,b,A)=>{let H=yr({icon:w,label:b,size:14,className:"persona-message-action-btn"});return H.setAttribute("data-action",A),H};return o&&p.appendChild(m("copy","Copy message","copy")),s&&p.appendChild(m("volume-2","Read aloud","read-aloud")),n&&p.appendChild(m("thumbs-up","Upvote","upvote")),a&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},ja=(e,t,r,o,n,a)=>{var de,J,le,ge,ue,G,ce,Be,ne,ee,ie,vt,Lt,gt,_e,be,Ze;let s=r!=null?r:{},i=(de=s.layout)!=null?de:"bubble",c=s.avatar,d=s.timestamp,u=(J=c==null?void 0:c.show)!=null?J:!1,g=(le=d==null?void 0:d.show)!=null?le:!1,p=(ge=c==null?void 0:c.position)!=null?ge:"left",m=(ue=d==null?void 0:d.position)!=null?ue:"below",x=Ob(e.role,i),C=S("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Pb(e),E=(ce=(G=e.content)==null?void 0:G.trim())!=null?ce:"",P=T.length>0&&E===Hi,y=al((ne=(Be=a==null?void 0:a.widgetConfig)==null?void 0:Be.features)==null?void 0:ne.streamAnimation),w=(vt=(ie=(ee=a==null?void 0:a.widgetConfig)==null?void 0:ee.features)==null?void 0:ie.streamAnimation)==null?void 0:vt.plugins,b=e.role==="assistant"&&y.type!=="none"?Bs(y.type,w):null,A=e.role==="assistant"&&((Lt=b==null?void 0:b.isAnimating)==null?void 0:Lt.call(b,e))===!0,H=e.role==="assistant"&&b!==null&&(!!e.streaming||A);H&&(b!=null&&b.bubbleClass)&&C.classList.add(b.bubbleClass);let W=document.createElement("div");W.classList.add("persona-message-content"),H&&b&&(b.containerClass&&W.classList.add(b.containerClass),W.style.setProperty("--persona-stream-step",`${y.speed}ms`),W.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let k=H?sl((gt=e.content)!=null?gt:"",y.buffer,b,e,!!e.streaming):(_e=e.content)!=null?_e:"",N=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),q=N;H&&(b==null?void 0:b.wrap)==="char"?q=Ds(N,"char",e.id,{skipTags:b.skipTags}):H&&(b==null?void 0:b.wrap)==="word"&&(q=Ds(N,"word",e.id,{skipTags:b.skipTags}));let Z=null;if(P?(Z=document.createElement("div"),Z.innerHTML=q,Z.style.display="none",W.appendChild(Z)):W.innerHTML=q,H&&(b!=null&&b.useCaret)&&!P&&E){let Y=il(),pe=W.querySelectorAll(".persona-stream-char, .persona-stream-word"),Me=pe[pe.length-1];if(Me!=null&&Me.parentNode)Me.parentNode.insertBefore(Y,Me.nextSibling);else{let Je=W.lastElementChild;Je?Je.appendChild(Y):W.appendChild(Y)}}if(g&&m==="inline"&&e.createdAt){let Y=Eh(e,d,"span");Y.classList.add("persona-timestamp-inline");let pe=W.lastElementChild;pe?pe.appendChild(Y):W.appendChild(Y)}if(T.length>0){let Y=Hb(T,!P&&!!E,()=>{P&&Z&&(Z.style.display="")});Y?C.appendChild(Y):P&&Z&&(Z.style.display="")}let me=Rb(e);if(me.length>0){let Y=Bb(me);Y&&C.appendChild(Y)}let Ke=Ib(e);if(Ke.length>0){let Y=Db(Ke);Y&&C.appendChild(Y)}let Ce=Wb(e);if(Ce.length>0){let Y=Fb(Ce);Y&&C.appendChild(Y)}if(C.appendChild(W),g&&m==="below"&&e.createdAt){let Y=Eh(e,d);Y.classList.add("persona-mt-1"),C.appendChild(Y)}let Ie=e.role==="assistant"?Eb(e.stopReason,(Ze=(be=a==null?void 0:a.widgetConfig)==null?void 0:be.copy)==null?void 0:Ze.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(k&&k.trim()),pe=y.placeholder==="skeleton",Me=pe&&y.buffer==="line"&&Y;if(Y)Me&&C.appendChild(Fs());else if(pe)C.appendChild(Fs());else{let Je=Cp("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Je&&C.appendChild(Je)}}if(Ie&&e.stopReason&&!e.streaming&&(E||(W.style.display="none"),C.appendChild(kb(e.stopReason,Ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let Y=wp(e,o,n);C.appendChild(Y)}if(!u||e.role==="system")return C;let Te=S("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),We=Nb(c,e.role);return p==="right"||p==="left"&&e.role==="user"?Te.append(C,We):Te.append(We,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Te},Lh=(e,t,r,o,n,a)=>{let s=r!=null?r:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ja(e,t,r,o,n,a)};var Ga=new Set,_b=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Ub=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
27
- `):""},Ph=(e,t)=>{let r=Ga.has(e),o=t.querySelector('button[data-expand-header="true"]'),n=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!n)return;o.setAttribute("aria-expanded",r?"true":"false");let s=o.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=ve(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}n.style.display=r?"":"none",a&&(a.style.display=r?"none":a.textContent||a.childNodes.length?"":"none")},Sp=(e,t)=>{var Ke,Ce,Ie,Ue,Te,We,de,J,le,ge,ue;let r=e.reasoning,o=S("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!r)return o;let n=(Ce=(Ke=t==null?void 0:t.features)==null?void 0:Ke.reasoningDisplay)!=null?Ce:{},a=n.expandable!==!1,s=a&&Ga.has(e.id),i=r.status!=="complete",c=Ub(e,(Ie=n.previewMaxLines)!=null?Ie:3),d=S("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",a&&(d.setAttribute("aria-expanded",s?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let u=S("div","persona-flex persona-flex-col persona-text-left"),g=S("span","persona-text-xs persona-text-persona-primary"),p="Thinking...",m=(Ue=t==null?void 0:t.reasoning)!=null?Ue:{},x=String((Te=r.startedAt)!=null?Te:Date.now()),C=()=>{let G=S("span","");return G.setAttribute("data-tool-elapsed",x),G.textContent=Ti(r),G},T=(We=m.renderCollapsedSummary)==null?void 0:We.call(m,{message:e,reasoning:r,defaultSummary:p,previewText:c,isActive:i,config:t!=null?t:{},elapsed:Ti(r),createElapsedElement:C});typeof T=="string"&&T.trim()?(g.textContent=T,u.appendChild(g)):T instanceof HTMLElement?u.appendChild(T):(g.textContent=p,u.appendChild(g));let E=S("span","persona-text-xs persona-text-persona-primary");E.textContent=Bg(r),u.appendChild(E);let M=(de=n.loadingAnimation)!=null?de:"none",P=m.activeTextTemplate,y=m.completeTextTemplate,w=i?P:y,b=T instanceof HTMLElement,A=(G,ce,Be)=>{let ne=Be;for(let ee of ce){let ie=S("span","persona-tool-char");ie.style.setProperty("--char-index",String(ne)),ie.textContent=ee===" "?"\xA0":ee,G.appendChild(ie),ne++}return ne},H=(G,ce)=>{g.textContent="";let Be=Ei(G,""),ne=0;for(let ee of Be){let ie=ee.styles.length>0?(()=>{let vt=S("span",ee.styles.map(Lt=>`persona-tool-text-${Lt}`).join(" "));return g.appendChild(vt),vt})():g;if(ee.isDuration&&i)ie.appendChild(C());else{let vt=ee.isDuration?Ti(r):ee.text;ce?ne=A(ie,vt,ne):ie.appendChild(document.createTextNode(vt))}}};if(!b&&w)if(E.style.display="none",g.style.display="",i&&M!=="none"){let G=(J=m.loadingAnimationDuration)!=null?J:2e3;g.setAttribute("data-preserve-animation","true"),M==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),H(w,!1)):(g.classList.add(`persona-tool-loading-${M}`),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),M==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),H(w,!0))}else H(w,!1);else if(!b&&i&&M!=="none"){g.style.display="";let G=(le=m.loadingAnimationDuration)!=null?le:2e3;if(g.setAttribute("data-preserve-animation","true"),M==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`);else{g.classList.add(`persona-tool-loading-${M}`),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),M==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ce=g.textContent||p;g.textContent="",A(g,ce,0)}r.status==="complete"&&(g.style.display="none")}else b||(r.status==="complete"?g.style.display="none":g.style.display="");let W=null;if(a){W=S("div","persona-flex persona-items-center");let ce=ve(s?"chevron-up":"chevron-down",16,"currentColor",2);ce?W.appendChild(ce):W.textContent=s?"Hide":"Show";let Be=S("div","persona-flex persona-items-center persona-ml-auto");Be.append(W),d.append(u,Be)}else d.append(u);let k=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!s&&i&&n.activePreview&&c){let G=(ue=(ge=t==null?void 0:t.reasoning)==null?void 0:ge.renderCollapsedPreview)==null?void 0:ue.call(ge,{message:e,reasoning:r,defaultPreview:c,isActive:i,config:t!=null?t:{}});_b(k,G)||(k.textContent=c),k.style.display=""}if(!s&&i&&n.activeMinHeight&&(o.style.minHeight=n.activeMinHeight),!a)return o.append(d,k),o;let N=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=s?"":"none";let q=r.chunks.join(""),Z=S("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=q||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(Z),(()=>{if(d.setAttribute("aria-expanded",s?"true":"false"),W){W.innerHTML="";let ce=ve(s?"chevron-up":"chevron-down",16,"currentColor",2);ce?W.appendChild(ce):W.textContent=s?"Hide":"Show"}N.style.display=s?"":"none",k.style.display=s?"none":k.textContent||k.childNodes.length?"":"none"})(),o.append(d,k,N),o};var Ka=new Set,qb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Vb=(e,t)=>{var a;let r=e.toolCall;if(!r)return"";let o=((a=r.chunks)!=null?a:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
28
- `);let n=Fa(r.args).trim();return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
29
- `):""},$b=(e,t)=>{var u,g,p,m,x;let r=e.toolCall,o=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,n=(g=o==null?void 0:o.collapsedMode)!=null?g:"tool-call",a=Vb(e,(p=o==null?void 0:o.previewMaxLines)!=null?p: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:{},d=s;return n==="tool-name"?d=((x=r.name)==null?void 0:x.trim())||s:n==="tool-preview"&&a&&(d=a),i&&c.activeTextTemplate?d=rd(r,c.activeTextTemplate,d):!i&&c.completeTextTemplate&&(d=rd(r,c.completeTextTemplate,d)),{summary:d,previewText:a,isActive:i}},Rh=(e,t,r)=>{var u;let o=Ka.has(e),n=(u=r==null?void 0:r.toolCall)!=null?u:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto"),d=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=n.toggleTextColor||n.headerTextColor||"currentColor",p=ve(o?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Ap=(e,t)=>{var q,Z,me,Ke,Ce,Ie,Ue,Te,We;let r=e.toolCall,o=(q=t==null?void 0:t.toolCall)!=null?q:{},n=S("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),o.backgroundColor&&(n.style.backgroundColor=o.backgroundColor),o.borderColor&&(n.style.borderColor=o.borderColor),o.borderWidth&&(n.style.borderWidth=o.borderWidth),o.borderRadius&&(n.style.borderRadius=o.borderRadius),n.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return n;let a=(me=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?me:{},s=a.expandable!==!1,i=s&&Ka.has(e.id),{summary:c,previewText:d,isActive:u}=$b(e,t),g=S("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",s&&(g.setAttribute("aria-expanded",i?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let p=S("div","persona-flex persona-flex-col persona-text-left"),m=S("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let x=String((Ke=r.startedAt)!=null?Ke:Date.now()),C=()=>{let de=S("span","");return de.setAttribute("data-tool-elapsed",x),de.textContent=Ts(r),de},T=(Ie=o.renderCollapsedSummary)==null?void 0:Ie.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:d,collapsedMode:(Ce=a.collapsedMode)!=null?Ce:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Ts(r),createElapsedElement:C});typeof T=="string"&&T.trim()?(m.textContent=T,p.appendChild(m)):T instanceof HTMLElement?p.appendChild(T):(m.textContent=c,p.appendChild(m));let E=(Ue=a.loadingAnimation)!=null?Ue:"none",M=o.activeTextTemplate,P=o.completeTextTemplate,y=u?M:P,w=T instanceof HTMLElement,b=(de,J,le)=>{let ge=le;for(let ue of J){let G=S("span","persona-tool-char");G.style.setProperty("--char-index",String(ge)),G.textContent=ue===" "?"\xA0":ue,de.appendChild(G),ge++}return ge},A=(de,J)=>{var G;m.textContent="";let le=((G=r.name)==null?void 0:G.trim())||"tool",ge=Ei(de,le),ue=0;for(let ce of ge){let Be=ce.styles.length>0?(()=>{let ne=S("span",ce.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(ne),ne})():m;if(ce.isDuration&&u)Be.appendChild(C());else{let ne=ce.isDuration?Ts(r):ce.text;J?ue=b(Be,ne,ue):Be.appendChild(document.createTextNode(ne))}}};if(!w)if(u&&E!=="none"){let de=(Te=o.loadingAnimationDuration)!=null?Te:2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),y&&A(y,!1);else if(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),E==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),y)A(y,!0);else{let J=m.textContent||c;m.textContent="",b(m,J,0)}}else y&&A(y,!1);let H=null;if(s){H=S("div","persona-flex persona-items-center");let de=o.toggleTextColor||o.headerTextColor||"currentColor",J=ve(i?"chevron-up":"chevron-down",16,de,2);J?H.appendChild(J):H.textContent=i?"Hide":"Show";let le=S("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");le.append(H),g.append(p,le)}else g.append(p);let W=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","tool"),W.style.display="none",W.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&d){let de=(We=o.renderCollapsedPreview)==null?void 0:We.call(o,{message:e,toolCall:r,defaultPreview:d,isActive:u,config:t!=null?t:{}});qb(W,de)||(W.textContent=d),W.style.display=""}if(!i&&u&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(g,W),n;let k=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",o.contentBackgroundColor&&(k.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(k.style.color=o.contentTextColor),o.contentPaddingX&&(k.style.paddingLeft=o.contentPaddingX,k.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(k.style.paddingTop=o.contentPaddingY,k.style.paddingBottom=o.contentPaddingY),r.name){let de=S("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?de.style.color=o.contentTextColor:o.headerTextColor&&(de.style.color=o.headerTextColor),de.textContent=r.name,k.appendChild(de)}if(r.args!==void 0){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Arguments";let le=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=Fa(r.args),de.append(J,le),k.appendChild(de)}if(r.chunks&&r.chunks.length){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Activity";let le=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=r.chunks.join(""),de.append(J,le),k.appendChild(de)}if(r.status==="complete"&&r.result!==void 0){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Result";let le=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=Fa(r.result),de.append(J,le),k.appendChild(de)}if(r.status==="complete"&&typeof r.duration=="number"){let de=S("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(de.style.color=o.contentTextColor),de.textContent=`Duration: ${r.duration}ms`,k.appendChild(de)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),H){H.innerHTML="";let de=o.toggleTextColor||o.headerTextColor||"currentColor",J=ve(i?"chevron-up":"chevron-down",16,de,2);J?H.appendChild(J):H.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",W.style.display=i?"none":W.textContent||W.childNodes.length?"":"none"})(),n.append(g,W,k),n};var yl=new Map,zb=e=>{let r=(e.startsWith(tn)?e.slice(tn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(r.length===0)return e;let o=r.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Ih=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Wh=(e,t)=>{var o,n,a;let r=(n=(o=Ih(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=yl.get(e))!=null?a:r==="expanded"},Hh=(e,t,r)=>{var s,i;let o=Ih(r);e.setAttribute("aria-expanded",t?"true":"false");let n=e.querySelector("[data-approval-details-label]");n&&(n.textContent=t?(s=o==null?void 0:o.hideDetailsLabel)!=null?s:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let c=ve(t?"chevron-up":"chevron-down",14,"currentColor",2);c&&a.appendChild(c)}},Bh=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=Wh(e,r);Hh(o,a,r),n.style.display=a?"":"none"};var bl=(e,t)=>{var A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de;let r=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,n=(r==null?void 0:r.status)==="pending",a=S("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(A=o==null?void 0:o.backgroundColor)!=null?A:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(H=o==null?void 0:o.borderColor)!=null?H:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return a;let s=S("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=S("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let c=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",d=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(W=o==null?void 0:o.titleColor)!=null?W:"currentColor",u=ve(c,20,d,2);u&&i.appendChild(u);let g=S("div","persona-flex-1 persona-min-w-0"),p=S("div","persona-flex persona-items-center persona-gap-2"),m=S("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(k=o==null?void 0:o.title)!=null?k:"Approval Required",p.appendChild(m),!n){let J=S("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");J.setAttribute("data-approval-status",r.status),r.status==="approved"?(J.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",J.style.color="var(--persona-palette-colors-success-700, #15803d)",J.textContent="Approved"):r.status==="denied"?(J.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",J.style.color="var(--persona-palette-colors-error-700, #b91c1c)",J.textContent="Denied"):r.status==="timeout"&&(J.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",J.style.color="var(--persona-palette-colors-warning-700, #b45309)",J.textContent="Timeout"),p.appendChild(J)}g.appendChild(p);let C=r.toolType==="webmcp"||r.toolName.startsWith(tn)?$l(r.toolName):void 0,T=(N=o==null?void 0:o.formatDescription)==null?void 0:N.call(o,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...C?{displayTitle:C}:{},...r.reason?{reason:r.reason}:{}}),E=!r.toolName,M=T||(E?r.description:`The assistant wants to use \u201C${C!=null?C:zb(r.toolName)}\u201D.`),P=S("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(P.style.color=o.descriptionColor),P.textContent=M,g.appendChild(P),r.reason){let J=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");J.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?J.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(J.style.color=o.descriptionColor);let le=S("span","persona-font-medium");le.textContent=`${(q=o==null?void 0:o.reasonLabel)!=null?q:"Agent's stated reason:"} `,J.appendChild(le),J.appendChild(document.createTextNode(r.reason)),g.appendChild(J)}let y=(Z=o==null?void 0:o.detailsDisplay)!=null?Z:"collapsed",w=!!r.description&&!E,b=w||!!r.parameters;if(y!=="hidden"&&b){let J=Wh(e.id,t),le=S("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");le.type="button",le.setAttribute("data-expand-header","true"),le.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(le.style.color=o.descriptionColor);let ge=S("span");ge.setAttribute("data-approval-details-label","true");let ue=S("span","persona-inline-flex persona-items-center");ue.setAttribute("data-approval-details-chevron","true"),le.append(ge,ue),Hh(le,J,t),g.appendChild(le);let G=S("div");if(G.setAttribute("data-approval-details","true"),G.style.display=J?"":"none",w){let ce=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ce.style.color=o.descriptionColor),ce.textContent=r.description,G.appendChild(ce)}if(r.parameters){let ce=S("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(ce.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ce.style.color=o.parameterTextColor),ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",ce.textContent=Fa(r.parameters),G.appendChild(ce)}g.appendChild(G)}if(n){let J=S("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");let le=S("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");le.type="button",le.style.backgroundColor=(me=o==null?void 0:o.approveButtonColor)!=null?me:"var(--persona-approval-approve-bg, #22c55e)",le.style.color=(Ke=o==null?void 0:o.approveButtonTextColor)!=null?Ke:"#ffffff",le.setAttribute("data-approval-action","approve");let ge=ve("shield-check",14,(Ce=o==null?void 0:o.approveButtonTextColor)!=null?Ce:"#ffffff",2);ge&&(ge.style.marginRight="4px",le.appendChild(ge));let ue=document.createTextNode((Ie=o==null?void 0:o.approveLabel)!=null?Ie:"Approve");le.appendChild(ue);let G=S("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");G.type="button",G.style.backgroundColor=(Ue=o==null?void 0:o.denyButtonColor)!=null?Ue:"transparent",G.style.color=(Te=o==null?void 0:o.denyButtonTextColor)!=null?Te:"var(--persona-feedback-error, #dc2626)",G.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,G.setAttribute("data-approval-action","deny");let ce=ve("shield-x",14,(We=o==null?void 0:o.denyButtonTextColor)!=null?We:"var(--persona-feedback-error, #dc2626)",2);ce&&(ce.style.marginRight="4px",G.appendChild(ce));let Be=document.createTextNode((de=o==null?void 0:o.denyLabel)!=null?de:"Deny");G.appendChild(Be),J.append(le,G),g.appendChild(J)}return s.append(i,g),a.appendChild(s),a};var Dh=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,d)=>{e.innerHTML="",t.length=0;let u=(d==null?void 0:d.agentPushed)===!0;if(u||(r=null),!n||!n.length||!u&&(i!=null?i:a?a.getMessages():[]).some(T=>T.role==="user"))return;let g=document.createDocumentFragment(),p=a?a.isStreaming():!1,m=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(n.forEach(x=>{let C=S("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=x,C.disabled=p,c!=null&&c.fontFamily&&(C.style.fontFamily=m(c.fontFamily)),c!=null&&c.fontWeight&&(C.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(C.style.paddingLeft=c.paddingX,C.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(C.style.paddingTop=c.paddingY,C.style.paddingBottom=c.paddingY),C.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",u&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),a.sendMessage(x))}),g.appendChild(C),t.push(C)}),e.appendChild(g),u){let x=JSON.stringify(n);x!==r&&(r=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var Us=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of r)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var qs=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let n=o.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(o){r(o)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}};var jb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Gb=new Set(["step_start","execution_start"]),Kb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Xb=new Set(["step_complete","agent_turn_complete"]),Qb=new Set(["flow_complete","agent_complete"]),Fh=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Oh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ao=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ua=(e,t)=>{let r=e[t];return Oh(r)?r:void 0};function Mp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function vl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Jb(e,t){return typeof t.type=="string"?t.type:e}function Yb(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 Zb(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 Nh(e){var o,n,a,s,i;let t=ua(e,"result"),r=[ua(e,"tokens"),ua(e,"totalTokens"),t?ua(t,"tokens"):void 0,ua(e,"usage"),t?ua(t,"usage"):void 0];for(let c of r){if(!c)continue;let d=(n=(o=ao(c.output))!=null?o:ao(c.outputTokens))!=null?n:ao(c.completionTokens);if(d!==void 0)return d}return(i=(a=ao(e.outputTokens))!=null?a:ao(e.completionTokens))!=null?i:t?(s=ao(t.outputTokens))!=null?s:ao(t.completionTokens):void 0}function ev(e){var r,o,n,a,s;let t=ua(e,"result");return(s=(n=(o=(r=ao(e.executionTime))!=null?r:ao(e.executionTimeMs))!=null?o:ao(e.execution_time))!=null?n:ao(e.duration))!=null?s:t?(a=ao(t.executionTime))!=null?a:ao(t.executionTimeMs):void 0}function tv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Vs=class{constructor(t=tv){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:vl(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(!Oh(r)){Fh.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Jb(t,r),n=this.now();if(jb.has(o)){this.startRun(n);return}if(Gb.has(o)){this.run||this.startRun(n);return}if(Kb.has(o)){if(!Zb(o,r))return;let s=Yb(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+Mp(i.visibleCharCount),d=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:vl(c,d),outputTokens:c,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Xb.has(o)){if(!this.run)return;let s=this.run,i=Nh(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,d=s.exactOutputTokens+Mp(s.visibleCharCount),u=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:vl(d,u),outputTokens:d,durationMs:u,source:c?"usage":"estimate"};return}if(Qb.has(o)){if(!this.run)return;let s=this.run,i=Nh(r),c=i!=null?i:s.exactOutputTokens+Mp(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:vl(c,u),outputTokens:c,durationMs:u,source:d},this.run=null;return}if(Fh.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 Xa(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var rv={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)"}},ov={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},nv=["flowName","stepName","reasoningText","text","name","tool","toolName"],av=100;function sv(e,t){let r={...rv,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return ov}function iv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function lv(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 cv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),r()})}function pv(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 uv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function fv(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 mv(e,t,r){let o,n;try{n=JSON.parse(e.payload),o=JSON.stringify(n,null,2)}catch{n=e.payload,o=e.payload}let a=t.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&r){let i=a.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:n});if(i)return i}return s();function s(){let i=S("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),c=S("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,i.appendChild(c),i}}function Tp(e,t,r,o,n,a,s,i){var p;let c=n.has(e.id),d=S("div","persona-border-b persona-border-persona-divider persona-text-xs");Xa(d,(p=o.classNames)==null?void 0:p.eventRow);let u=s.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>g(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(m)return d.appendChild(m),d}return d.appendChild(g()),d;function g(){var q,Z;let m=S("div",""),x=S("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let C=S("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=ve(c?"chevron-down":"chevron-right","14px","currentColor",2);T&&C.appendChild(T);let E=S("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(q=o.timestampFormat)!=null?q:"relative";E.textContent=M==="relative"?iv(e.timestamp,r):lv(e.timestamp);let P=null;o.showSequenceNumbers!==!1&&(P=S("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let y=sv(e.type,o.badgeColors),w=S("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=y.bg,w.style.color=y.text,w.style.borderColor=y.text+"50",w.textContent=e.type;let b=(Z=o.descriptionFields)!=null?Z:nv,A=dv(e.payload,b),H=null;A&&(H=S("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),H.textContent=A);let W=S("div","persona-flex-1 persona-min-w-0"),k=S("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),N=ve("clipboard","12px","currentColor",1.5);return N&&k.appendChild(N),k.addEventListener("click",async me=>{me.stopPropagation(),await cv(pv(e)),k.innerHTML="";let Ke=ve("check","12px","currentColor",1.5);Ke&&k.appendChild(Ke),setTimeout(()=>{k.innerHTML="";let Ce=ve("clipboard","12px","currentColor",1.5);Ce&&k.appendChild(Ce)},1500)}),x.appendChild(C),x.appendChild(E),P&&x.appendChild(P),x.appendChild(w),H&&x.appendChild(H),x.appendChild(W),x.appendChild(k),m.appendChild(x),c&&m.appendChild(mv(e,s,i)),m}}function _h(e){var x,C,T,E,M;let{buffer:t,getFullHistory:r,onClose:o,config:n,plugins:a=[],getThroughput:s}=e,i=(x=n==null?void 0:n.features)==null?void 0:x.scrollToBottom,c=(i==null?void 0:i.enabled)!==!1,d=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",u=(T=i==null?void 0:i.label)!=null?T:"",g=(M=(E=n==null?void 0:n.features)==null?void 0:E.eventStream)!=null?M:{},p=a.find(P=>P.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&n){let P=p.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return m();function m(){let P=g.classNames,y=S("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Xa(y,P==null?void 0:P.panel);let w=[],b="",A="",H=null,W=[],k={},N=0,q=rl(),Z=0,me=0,Ke=!1,Ce=null,Ie=!1,Ue=0,Te=new Set,We=new Map,de="",J="",le=null,ge,ue,G,ce,Be,ne=null,ee=null,ie=null;function vt(){let oe=S("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),we=S("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Xa(we,P==null?void 0:P.headerBar);let De=S("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(De.textContent="Events",ge=S("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),ge.textContent="0",s){ee=S("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let so=S("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");so.textContent="Throughput",ne=S("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ne.textContent="-- tok/s",ie=S("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ie.style.display="none",ie.style.pointerEvents="none";let Rr=ee,ir=ie,Ur=()=>{if(!ir.textContent)return;let yt=Rr.getBoundingClientRect(),jr=oe.getBoundingClientRect();ir.style.left=`${yt.left-jr.left}px`,ir.style.top=`${yt.bottom-jr.top+4}px`,ir.style.display="block"},ko=()=>{ir.style.display="none"};ee.addEventListener("mouseenter",Ur),ee.addEventListener("mouseleave",ko),ee.appendChild(so),ee.appendChild(ne)}let At=S("div","persona-flex-1");ue=S("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ar=S("option","");ar.value="",ar.textContent="All events",ue.appendChild(ar),G=S("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),G.type="button",G.title="Copy All";let wr=ve("clipboard-copy","12px","currentColor",1.5);wr&&G.appendChild(wr);let Ft=S("span","persona-text-xs");Ft.textContent="Copy All",G.appendChild(Ft),we.appendChild(De),we.appendChild(ge),ee&&we.appendChild(ee),we.appendChild(At),we.appendChild(ue),we.appendChild(G);let ot=S("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Xa(ot,P==null?void 0:P.searchBar);let Dt=ve("search","14px","var(--persona-muted, #9ca3af)",1.5),lt=S("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Dt&&lt.appendChild(Dt),ce=S("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Xa(ce,P==null?void 0:P.searchInput),ce.type="text",ce.placeholder="Search event payloads...",Be=S("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Be.type="button",Be.style.display="none";let Yt=ve("x","12px","currentColor",2);return Yt&&Be.appendChild(Yt),ot.appendChild(lt),ot.appendChild(ce),ot.appendChild(Be),oe.appendChild(we),oe.appendChild(ot),ie&&oe.appendChild(ie),oe}let Lt,gt=a.find(oe=>oe.renderEventStreamToolbar);if(gt!=null&&gt.renderEventStreamToolbar&&n){let oe=gt.renderEventStreamToolbar({config:n,defaultRenderer:()=>vt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:we=>{b=we,Wt(),V()},onSearchChange:we=>{A=we,Wt(),V()}});Lt=oe!=null?oe:vt()}else Lt=vt();let _e=S("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");_e.style.display="none";function be(){if(!s||!ne||!ee)return;let oe=s();ne.textContent=uv(oe);let we=fv(oe);ie&&(ie.textContent=we,we||(ie.style.display="none")),we?ee.setAttribute("aria-label",we):ee.removeAttribute("aria-label")}let Ze=S("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=S("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let pe=S("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Xa(pe,P==null?void 0:P.scrollIndicator),pe.style.display="none",pe.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let Me=ve(d,"14px","currentColor",2);Me&&pe.appendChild(Me);let Je=S("span","");Je.textContent=u,pe.appendChild(Je);let Ge=S("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ge.style.display="none",Ze.appendChild(Y),Ze.appendChild(Ge),Ze.appendChild(pe),y.setAttribute("tabindex","0"),y.appendChild(Lt),y.appendChild(_e),y.appendChild(Ze);function ke(){let oe=t.getAll(),we={};for(let Ft of oe)we[Ft.type]=(we[Ft.type]||0)+1;let De=Object.keys(we).sort(),At=De.length!==W.length||!De.every((Ft,ot)=>Ft===W[ot]),ar=!At&&De.some(Ft=>we[Ft]!==k[Ft]),sr=oe.length!==Object.values(k).reduce((Ft,ot)=>Ft+ot,0);if(!At&&!ar&&!sr||(W=De,k=we,!ue))return;let wr=ue.value;if(ue.options[0].textContent="All events",At){for(;ue.options.length>1;)ue.remove(1);for(let Ft of De){let ot=S("option","");ot.value=Ft,ot.textContent=`${Ft} (${we[Ft]||0})`,ue.appendChild(ot)}wr&&De.includes(wr)?ue.value=wr:wr&&(ue.value="",b="")}else for(let Ft=1;Ft<ue.options.length;Ft++){let ot=ue.options[Ft];ot.textContent=`${ot.value} (${we[ot.value]||0})`}}function je(){let oe=t.getAll();if(b&&(oe=oe.filter(we=>we.type===b)),A){let we=A.toLowerCase();oe=oe.filter(De=>De.type.toLowerCase().includes(we)||De.payload.toLowerCase().includes(we))}return oe}function Cr(){return b!==""||A!==""}function Wt(){N=0,Z=0,q.resume(),pe.style.display="none"}function ur(oe){Te.has(oe)?Te.delete(oe):Te.add(oe),le=oe;let we=Y.scrollTop,De=q.isFollowing();Ie=!0,q.pause(),V(),Y.scrollTop=we,De&&q.resume(),Ie=!1}function Eo(){return la(Y,50)}function V(){me=Date.now(),Ke=!1,be(),ke();let oe=t.getEvictedCount();oe>0?(_e.textContent=`${oe.toLocaleString()} older events truncated`,_e.style.display=""):_e.style.display="none",w=je();let we=w.length,De=t.getSize()>0;ge&&(ge.textContent=String(t.getSize())),we===0&&De&&Cr()?(Ge.textContent=A?`No events matching '${A}'`:"No events matching filter",Ge.style.display="",Y.style.display="none"):(Ge.style.display="none",Y.style.display=""),G&&(G.title=Cr()?`Copy Filtered (${we})`:"Copy All"),c&&!q.isFollowing()&&we>N&&(Z+=we-N,Je.textContent=u?`${u}${Z>0?` (${Z})`:""}`:"",pe.style.display=""),N=we;let At=t.getAll(),ar=At.length>0?At[0].timestamp:0,sr=new Set(w.map(ot=>ot.id));for(let ot of Te)sr.has(ot)||Te.delete(ot);let wr=b!==de||A!==J,Ft=We.size===0&&w.length>0;if(wr||Ft||w.length===0){Y.innerHTML="",We.clear();let ot=document.createDocumentFragment();for(let Dt=0;Dt<w.length;Dt++){let lt=Tp(w[Dt],Dt,ar,g,Te,ur,a,n);We.set(w[Dt].id,lt),ot.appendChild(lt)}Y.appendChild(ot),de=b,J=A,le=null}else{if(le!==null){let Dt=We.get(le);if(Dt&&Dt.parentNode===Y){let lt=w.findIndex(Yt=>Yt.id===le);if(lt>=0){let Yt=Tp(w[lt],lt,ar,g,Te,ur,a,n);Y.insertBefore(Yt,Dt),Dt.remove(),We.set(le,Yt)}}le=null}let ot=new Set(w.map(Dt=>Dt.id));for(let[Dt,lt]of We)ot.has(Dt)||(lt.remove(),We.delete(Dt));for(let Dt=0;Dt<w.length;Dt++){let lt=w[Dt];if(!We.has(lt.id)){let Yt=Tp(lt,Dt,ar,g,Te,ur,a,n);We.set(lt.id,Yt),Y.appendChild(Yt)}}}q.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function j(){if(Date.now()-me>=av){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),V();return}Ke||(Ke=!0,Ce=requestAnimationFrame(()=>{Ce=null,V()}))}let he=(oe,we)=>{if(!G)return;G.innerHTML="";let De=ve(oe,"12px","currentColor",1.5);De&&G.appendChild(De);let At=S("span","persona-text-xs");At.textContent="Copy All",G.appendChild(At),setTimeout(()=>{G.innerHTML="";let ar=ve("clipboard-copy","12px","currentColor",1.5);ar&&G.appendChild(ar);let sr=S("span","persona-text-xs");sr.textContent="Copy All",G.appendChild(sr),G.disabled=!1},we)},Xe=async()=>{if(G){G.disabled=!0;try{let oe;Cr()?oe=w:r?(oe=await r(),oe.length===0&&(oe=t.getAll())):oe=t.getAll();let we=oe.map(De=>{try{return JSON.parse(De.payload)}catch{return De.payload}});await navigator.clipboard.writeText(JSON.stringify(we,null,2)),he("check",1500)}catch{he("x",1500)}}},et=()=>{ue&&(b=ue.value,Wt(),V())},qe=()=>{!ce||!Be||(Be.style.display=ce.value?"":"none",H&&clearTimeout(H),H=setTimeout(()=>{A=ce.value,Wt(),V()},150))},Ne=()=>{!ce||!Be||(ce.value="",A="",Be.style.display="none",H&&clearTimeout(H),Wt(),V())},Pt=()=>{if(Ie)return;let oe=Y.scrollTop,{action:we,nextLastScrollTop:De}=ol({following:q.isFollowing(),currentScrollTop:oe,lastScrollTop:Ue,nearBottom:Eo(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ue=De,we==="resume"?(q.resume(),Z=0,pe.style.display="none"):we==="pause"&&(q.pause(),c&&(Je.textContent=u,pe.style.display=""))},Gt=oe=>{let we=nl({following:q.isFollowing(),deltaY:oe.deltaY,nearBottom:Eo(),resumeWhenNearBottom:!0});we==="pause"?(q.pause(),c&&(Je.textContent=u,pe.style.display="")):we==="resume"&&(q.resume(),Z=0,pe.style.display="none")},Jt=()=>{c&&(Y.scrollTop=Y.scrollHeight,q.resume(),Z=0,pe.style.display="none")},Pr=oe=>{let we=oe.target;if(!we||we.closest("button"))return;let De=we.closest("[data-event-id]");if(!De)return;let At=De.getAttribute("data-event-id");At&&ur(At)},z=oe=>{if((oe.metaKey||oe.ctrlKey)&&oe.key==="f"){oe.preventDefault(),ce==null||ce.focus(),ce==null||ce.select();return}oe.key==="Escape"&&(ce&&document.activeElement===ce?(Ne(),ce.blur(),y.focus()):o&&o())};G&&G.addEventListener("click",Xe),ue&&ue.addEventListener("change",et),ce&&ce.addEventListener("input",qe),Be&&Be.addEventListener("click",Ne),Y.addEventListener("scroll",Pt),Y.addEventListener("wheel",Gt,{passive:!0}),Y.addEventListener("click",Pr),pe.addEventListener("click",Jt),y.addEventListener("keydown",z);function Ht(){H&&clearTimeout(H),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ke=!1,We.clear(),G&&G.removeEventListener("click",Xe),ue&&ue.removeEventListener("change",et),ce&&ce.removeEventListener("input",qe),Be&&Be.removeEventListener("click",Ne),Y.removeEventListener("scroll",Pt),Y.removeEventListener("wheel",Gt),Y.removeEventListener("click",Pr),pe.removeEventListener("click",Jt),y.removeEventListener("keydown",z)}return{element:y,update:j,destroy:Ht}}}function Uh(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",n=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=r;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #171717)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(p);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,g.appendChild(m)}else g.textContent=s;if(d.append(u,g),i.append(c,d),n==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${r}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",o),i.append(p)}return i}var qh=(e,t)=>{var o,n,a;let r=(a=(n=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(r){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",c=e.status==="streaming"?"streaming":"complete",d=typeof e.artifactType=="string"?e.artifactType:"markdown",u=r({artifact:{artifactId:i,title:s,artifactType:d,status:c},config:t.config,defaultRenderer:()=>Uh(e,t)});if(u)return u}return Uh(e,t)};var Ep=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,o])=>{this.register(r,o)})}},dn=new Ep;dn.register("PersonaArtifactCard",qh);function gv(e){var n;let t=S("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=S("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let o=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((n=e.props)!=null?n:{},null,2),t.appendChild(r),t.appendChild(o),t}function Vh(e,t){var ue,G,ce,Be;let r=(G=(ue=e.features)==null?void 0:ue.artifacts)==null?void 0:G.layout,n=((ce=r==null?void 0:r.toolbarPreset)!=null?ce:"default")==="document",a=(Be=r==null?void 0:r.panePadding)==null?void 0:Be.trim(),s=e.markdown?Zn(e.markdown):null,i=Ia(e.sanitize),c=ne=>{let ee=s?s(ne):qo(ne);return i?i(ee):ee},d=typeof document!="undefined"?S("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{d==null||d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};d&&d.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let g=S("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");g.setAttribute("data-persona-theme-zone","artifact-pane"),n&&g.classList.add("persona-artifact-pane-document");let p=S("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");p.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&p.classList.add("persona-artifact-toolbar-document");let m=S("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=S("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let C="rendered",T=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=n?yr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):yr({icon:"eye",label:"Rendered view"}),M=n?yr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):yr({icon:"code-2",label:"Source"}),P=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),y=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,w=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,b=r==null?void 0:r.documentToolbarCopyMenuItems,A=!!(w&&b&&b.length>0),H=null,W,k=null,N=null;if(n&&(y||w)&&!A){if(W=y?_s({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let ne=ve("chevron-down",14,"currentColor",2);ne&&W.appendChild(ne)}}else n&&A?(H=S("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),W=y?_s({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=yr({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),H.append(W,k)):n?W=yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):W=yr({icon:"copy",label:"Copy"});let q=n?yr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):yr({icon:"refresh-cw",label:"Refresh"}),Z=n?yr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):yr({icon:"x",label:"Close"}),me=()=>{var Lt,gt,_e;let ne=(Lt=We.find(be=>be.id===de))!=null?Lt:We[We.length-1],ee=(gt=ne==null?void 0:ne.id)!=null?gt:null,ie=(ne==null?void 0:ne.artifactType)==="markdown"&&(_e=ne.markdown)!=null?_e:"",vt=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:ie,jsonPayload:vt,id:ee}},Ke=async()=>{var Lt;let{markdown:ne,jsonPayload:ee}=me(),ie=(Lt=We.find(gt=>gt.id===de))!=null?Lt:We[We.length-1],vt=(ie==null?void 0:ie.artifactType)==="markdown"?ne:ie?ee:"";try{await navigator.clipboard.writeText(vt)}catch{}};if(W.addEventListener("click",async()=>{let ne=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(ne&&A){let{markdown:ee,jsonPayload:ie,id:vt}=me();try{await ne({actionId:"primary",artifactId:vt,markdown:ee,jsonPayload:ie})}catch{}return}await Ke()}),k&&(b!=null&&b.length)){let ne=()=>{var ie;return(ie=g.closest("[data-persona-root]"))!=null?ie:document.body},ee=()=>{N=Fn({items:b.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:vt,jsonPayload:Lt,id:gt}=me(),_e=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:ie,artifactId:gt,markdown:vt,jsonPayload:Lt}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(vt):ie==="json"||ie==="source"?await navigator.clipboard.writeText(Lt):await navigator.clipboard.writeText(vt||Lt)}catch{}},anchor:H!=null?H:k,position:"bottom-right",portal:ne()})};g.isConnected?ee():requestAnimationFrame(ee),k.addEventListener("click",ie=>{ie.stopPropagation(),N==null||N.toggle()})}q.addEventListener("click",async()=>{var ne;try{await((ne=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:ne.call(r))}catch{}le()}),Z.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let Ce=()=>{n&&(E.setAttribute("aria-pressed",C==="rendered"?"true":"false"),M.setAttribute("aria-pressed",C==="source"?"true":"false"))};E.addEventListener("click",()=>{C="rendered",Ce(),le()}),M.addEventListener("click",()=>{C="source",Ce(),le()});let Ie=S("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");n?(p.replaceChildren(),T.append(E,M),H?P.append(H,q,Z):P.append(W,q,Z),p.append(T,Ie,P),Ce()):(p.appendChild(m),p.appendChild(x)),a&&(p.style.paddingLeft=a,p.style.paddingRight=a);let Ue=S("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Te=S("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(Ue.style.paddingLeft=a,Ue.style.paddingRight=a,Te.style.padding=a),g.appendChild(p),g.appendChild(Ue),g.appendChild(Te);let We=[],de=null,J=!1,le=()=>{var vt,Lt,gt,_e;let ne=n&&We.length<=1;Ue.classList.toggle("persona-hidden",ne),Ue.replaceChildren();for(let be of We){let Ze=S("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Ze.type="button",Ze.textContent=be.title||be.id.slice(0,8),be.id===de&&Ze.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ze.addEventListener("click",()=>t.onSelect(be.id)),Ue.appendChild(Ze)}Te.replaceChildren();let ee=de&&We.find(be=>be.id===de)||We[We.length-1];if(!ee)return;if(n){let be=ee.artifactType==="markdown"?"MD":(vt=ee.component)!=null?vt:"Component",Y=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ie.textContent=`${Y} \xB7 ${be}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(n&&C==="source"){let Ze=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ze.textContent=(Lt=ee.markdown)!=null?Lt:"",Te.appendChild(Ze);return}let be=S("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");be.innerHTML=c((gt=ee.markdown)!=null?gt:""),Te.appendChild(be);return}let ie=ee.component?dn.get(ee.component):void 0;if(ie){let Ze={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Y=ie((_e=ee.props)!=null?_e:{},Ze);if(Y){Te.appendChild(Y);return}}catch{}}Te.appendChild(gv(ee))},ge=()=>{var ee;let ne=We.length>0;if(g.classList.toggle("persona-hidden",!ne),d){let ie=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,Lt=((ee=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ne&&Lt&&J?(d.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:d,update(ne){var ee,ie,vt;We=ne.artifacts,de=(vt=(ie=ne.selectedId)!=null?ie:(ee=ne.artifacts[ne.artifacts.length-1])==null?void 0:ee.id)!=null?vt:null,We.length>0&&(J=!0),le(),ge()},setMobileOpen(ne){J=ne,!ne&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):ge()}}}function xo(e){var t,r;return((r=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:r.enabled)===!0}function $h(e,t){var a,s,i,c;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!xo(t))return;let r=(s=(a=t.features)==null?void 0:a.artifacts)==null?void 0:s.layout,o=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),n=(c=r==null?void 0:r.paneBorderLeft)==null?void 0:c.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}function hv(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 Cl(e,t){var c,d,u,g,p,m,x,C,T,E;if(!xo(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),hv(e),$h(e,t);return}let r=(d=(c=t.features)==null?void 0:c.artifacts)==null?void 0:d.layout;e.style.setProperty("--persona-artifact-split-gap",(u=r==null?void 0:r.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(g=r==null?void 0:r.paneWidth)!=null?g:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(p=r==null?void 0:r.paneMaxWidth)!=null?p:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=r==null?void 0:r.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let n=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();n?e.style.setProperty("--persona-artifact-pane-padding",n):e.style.removeProperty("--persona-artifact-pane-padding");let a=(C=r==null?void 0:r.documentToolbarIconColor)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(T=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:T.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),$h(e,t)}var zh=["panel","seamless"];function wl(e,t){var i,c,d,u,g,p;for(let m of zh)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!xo(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(d=r==null?void 0:r.paneAppearance)!=null?d:"panel",n=zh.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${n}`);let a=(u=r==null?void 0:r.paneBorderRadius)==null?void 0:u.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(g=r==null?void 0:r.paneShadow)==null?void 0:g.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((p=r.unifiedSplitOuterRadius)==null?void 0:p.trim())||a;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function jh(e,t){var r,o,n;return!t||!xo(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function xv(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 yv(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 bv(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function vv(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function Gh(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 Kh(e,t,r,o,n,a){let s=xv(n,200),i=vv(t,r,o,200);i=Math.max(s,i);let c=yv(a);return c!==null&&(i=Math.min(i,c)),bv(e,s,i)}var Xh={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"}},kp=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var x,C,T;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(C=Xh[s])!=null?C:Xh.init;a.classList.add("persona-form-card","persona-space-y-4");let c=S("div","persona-space-y-1"),d=S("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,c.appendChild(d),i.description){let E=S("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,c.appendChild(E)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var b,A;let M=S("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${t.id}-${s}-${E.name}`;let P=S("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=E.label,M.appendChild(P);let y=(b=E.type)!=null?b:"text",w;y==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=y),w.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",w.id=`${t.id}-${s}-${E.name}`,w.name=E.name,w.placeholder=(A=E.placeholder)!=null?A:"",E.required&&(w.required=!0),M.appendChild(w),u.appendChild(M)});let g=S("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),p=S("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=S("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(T=i.submitLabel)!=null?T:"Submit",g.appendChild(p),g.appendChild(m),u.appendChild(g),a.replaceChildren(c,u),u.addEventListener("submit",async E=>{var w,b;E.preventDefault();let M=(w=r.formEndpoint)!=null?w:"/form",P=new FormData(u),y={};P.forEach((A,H)=>{y[H]=A}),y.type=s,m.disabled=!0,p.textContent="Submitting\u2026";try{let A=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!A.ok)throw new Error(`Form submission failed (${A.status})`);let H=await A.json();p.textContent=(b=H.message)!=null?b:"Thanks! We'll be in touch soon.",H.success&&H.nextPrompt&&await o.sendMessage(String(H.nextPrompt))}catch(A){p.textContent=A instanceof Error?A.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Lp=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 Lp;var Qh=()=>{let e=new Map,t=(n,a)=>(e.has(n)||e.set(n,new Set),e.get(n).add(a),()=>r(n,a)),r=(n,a)=>{var s;(s=e.get(n))==null||s.delete(a)};return{on:t,off:r,emit:(n,a)=>{var s;(s=e.get(n))==null||s.forEach(i=>{try{i(a)}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var Cv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},wv=e=>{let t=e.trim(),r=t.indexOf("{");if(r===-1)return null;let o=0;for(let n=r;n<t.length;n+=1){let a=t[n];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(r,n+1)}return null},zs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Cv(e),r=wv(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}},Pp=e=>typeof e=="string"?e:e==null?"":String(e),fa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Pp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=Pp(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:Pp(r.text)}}},Jh=e=>Array.isArray(e)?e.map(t=>String(t)):[],js=e=>{let t=new Set(Jh(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(Jh(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?e.parsers.reduce((d,u)=>d||(u==null?void 0:u({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),o();let c={action:i,message:a.message};e.emit("action:detected",c);for(let d of e.handlers)if(d)try{let u=()=>{e.emit("action:resubmit",c)},g=d(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let p=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:p,resubmit:g.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:r}};var Sv=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}},Av=e=>e.map(t=>({...t,streaming:!1})),Mv=e=>e.map(t=>({...t,status:"complete"})),Sl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Sv(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?Av(r.messages):void 0,artifacts:r.artifacts?Mv(r.artifacts):void 0};o.setItem(e,JSON.stringify(n))}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",n)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Qa=La(yi(),1);function Tv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Ev(e,t){if(!Tv(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 Al(){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=Ev(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function Yh(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ml(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=dn.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:r,updateProps:i=>{n&&n(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Zh(){let e=Al();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ex(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Tl(e){let t=ex(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 El(e){let t=ex(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 kv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function kl(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,ratingLabels:d=kv}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let g=null,p=document.createElement("div");p.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,m.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=n,m.appendChild(C),p.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let b=1;b<=5;b++){let A=document.createElement("button");A.type="button",A.className="persona-feedback-rating-btn persona-feedback-star-btn",A.setAttribute("role","radio"),A.setAttribute("aria-checked","false"),A.setAttribute("aria-label",`${b} star${b>1?"s":""}: ${d[b-1]}`),A.title=d[b-1],A.dataset.rating=String(b),A.innerHTML=`
26
+ `,r.addEventListener("click",t);let o=a=>{var P,y,w,b,A,H,W,k,N,q,Z,me,Ke;let s=(P=a.launcher)!=null?P:{},i=pr(a),c=r.querySelector("[data-role='launcher-title']");if(c){let Ce=(y=s.title)!=null?y:"Chat Assistant";c.textContent=Ce,c.setAttribute("title",Ce)}let d=r.querySelector("[data-role='launcher-subtitle']");if(d){let Ce=(w=s.subtitle)!=null?w:"Here to help you get answers fast";d.textContent=Ce,d.setAttribute("title",Ce)}let u=r.querySelector(".persona-flex-col");u&&(s.textHidden||i?u.style.display="none":u.style.display="");let g=r.querySelector("[data-role='launcher-icon']");if(g)if(s.agentIconHidden)g.style.display="none";else{let Ce=(b=s.agentIconSize)!=null?b:"40px";if(g.style.height=Ce,g.style.width=Ce,g.innerHTML="",s.agentIconName){let Ie=parseFloat(Ce)||24,Ue=ve(s.agentIconName,Ie*.6,"var(--persona-text-inverse, #ffffff)",2);Ue?(g.appendChild(Ue),g.style.display=""):(g.textContent=(A=s.agentIconText)!=null?A:"\u{1F4AC}",g.style.display="")}else s.iconUrl?g.style.display="none":(g.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}",g.style.display="")}let p=r.querySelector("[data-role='launcher-image']");if(p){let Ce=(W=s.agentIconSize)!=null?W:"40px";p.style.height=Ce,p.style.width=Ce,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(p.src=s.iconUrl,p.style.display="block"):p.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ce=(k=s.callToActionIconSize)!=null?k:"32px";m.style.height=Ce,m.style.width=Ce,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Ie=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,Ie=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let Ue=parseFloat(Ce)||24,Te=Math.max(Ue-Ie,8),We=ve(s.callToActionIconName,Te,"currentColor",2);We?m.appendChild(We):m.textContent=(N=s.callToActionIconText)!=null?N:"\u2197"}else m.textContent=(q=s.callToActionIconText)!=null?q:"\u2197"}let x=s.position&&To[s.position]?To[s.position]:To["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";r.className=i?T:`${C} ${x}`,i||(r.style.zIndex=String((Z=s.zIndex)!=null?Z:Lr));let E="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(me=s.border)!=null?me:E,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:M,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(Ke=s.collapsedMaxWidth)!=null?Ke:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},n=()=>{r.removeEventListener("click",t),r.remove()};return e&&o(e),{element:r,update:o,destroy:n}};var kh=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=Th(e),a=Eh(e,t),s={wrapper:r,panel:o,pillRoot:n},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:c,composer:d,replaceHeader:p=>(c.element.replaceWith(p.header),c.element=p.header,c.iconHolder=p.iconHolder,c.headerTitle=p.headerTitle,c.headerSubtitle=p.headerSubtitle,c.closeButton=p.closeButton,c.closeButtonWrapper=p.closeButtonWrapper,c.clearChatButton=p.clearChatButton,c.clearChatButtonWrapper=p.clearChatButtonWrapper,p),replaceComposer:p=>{d.footer.replaceWith(p),d.footer=p}}},bp=({config:e,plugins:t,onToggle:r})=>{let o=t.find(a=>a.renderLauncher);if(o!=null&&o.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>yp(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=yp(e,r);return{instance:n,element:n.element}};var Eb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},kb=(e,t)=>{if(!e)return null;let r=Eb(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},Lb=(e,t)=>{let r=S("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},Pb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},vp=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Cp=320,Ph=320,Rb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ib=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Wb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Hb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Bb=(e,t,r)=>{if(e.length===0)return null;try{let o=S("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,c)=>{var g;let d=S("img");d.alt=((g=i.alt)==null?void 0:g.trim())||`Attached image ${c+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Cp}px`,d.style.maxHeight=`${Ph}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;n+=1,d.addEventListener("error",()=>{u||(u=!0,n=Math.max(0,n-1),d.remove(),n===0&&s())}),d.addEventListener("load",()=>{u=!0}),Pb(i.image)?(d.src=i.image,o.appendChild(d)):(u=!0,n=Math.max(0,n-1),d.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},Db=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!vp(o.audio))return;let n=S("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${Cp}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Fb=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!vp(o.video))return;let n=S("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${Cp}px`,n.style.maxHeight=`${Ph}px`,n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Nb=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!vp(o.data))return;let n=S("a");n.href=o.data,n.download=o.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=o.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},ua=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(o),e.appendChild(n),e},wp=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:ua};if(t){let n=t(o);if(n!==null)return n}return ua()},Ob=(e,t)=>{let r=S("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let n=S("img");n.src=o,n.alt=t==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(n)}else r.textContent=o,r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},Lh=(e,t,r="div")=>{let o=S(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?o.textContent=t.format(n):o.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},_b=(e,t="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return r},Sp=(e,t,r)=>{var x,C,T,E,M,P,y;let o=(x=t.showCopy)!=null?x:!0,n=(C=t.showUpvote)!=null?C:!0,a=(T=t.showDownvote)!=null?T:!0,s=(E=t.showReadAloud)!=null?E:!1;if(!o&&!n&&!a&&!s){let w=S("div");return w.style.display="none",w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id),w}let i=(M=t.visibility)!=null?M:"hover",c=(P=t.align)!=null?P:"right",d=(y=t.layout)!=null?y:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[c],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=S("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${g} ${i==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=(w,b,A)=>{let H=yr({icon:w,label:b,size:14,className:"persona-message-action-btn"});return H.setAttribute("data-action",A),H};return o&&p.appendChild(m("copy","Copy message","copy")),s&&p.appendChild(m("volume-2","Read aloud","read-aloud")),n&&p.appendChild(m("thumbs-up","Upvote","upvote")),a&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},Ga=(e,t,r,o,n,a)=>{var de,J,le,ge,ue,G,ce,Be,ne,ee,ie,vt,Lt,gt,_e,be,Ze;let s=r!=null?r:{},i=(de=s.layout)!=null?de:"bubble",c=s.avatar,d=s.timestamp,u=(J=c==null?void 0:c.show)!=null?J:!1,g=(le=d==null?void 0:d.show)!=null?le:!1,p=(ge=c==null?void 0:c.position)!=null?ge:"left",m=(ue=d==null?void 0:d.position)!=null?ue:"below",x=_b(e.role,i),C=S("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Rb(e),E=(ce=(G=e.content)==null?void 0:G.trim())!=null?ce:"",P=T.length>0&&E===Bi,y=sl((ne=(Be=a==null?void 0:a.widgetConfig)==null?void 0:Be.features)==null?void 0:ne.streamAnimation),w=(vt=(ie=(ee=a==null?void 0:a.widgetConfig)==null?void 0:ee.features)==null?void 0:ie.streamAnimation)==null?void 0:vt.plugins,b=e.role==="assistant"&&y.type!=="none"?Ds(y.type,w):null,A=e.role==="assistant"&&((Lt=b==null?void 0:b.isAnimating)==null?void 0:Lt.call(b,e))===!0,H=e.role==="assistant"&&b!==null&&(!!e.streaming||A);H&&(b!=null&&b.bubbleClass)&&C.classList.add(b.bubbleClass);let W=document.createElement("div");W.classList.add("persona-message-content"),H&&b&&(b.containerClass&&W.classList.add(b.containerClass),W.style.setProperty("--persona-stream-step",`${y.speed}ms`),W.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let k=H?il((gt=e.content)!=null?gt:"",y.buffer,b,e,!!e.streaming):(_e=e.content)!=null?_e:"",N=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),q=N;H&&(b==null?void 0:b.wrap)==="char"?q=Fs(N,"char",e.id,{skipTags:b.skipTags}):H&&(b==null?void 0:b.wrap)==="word"&&(q=Fs(N,"word",e.id,{skipTags:b.skipTags}));let Z=null;if(P?(Z=document.createElement("div"),Z.innerHTML=q,Z.style.display="none",W.appendChild(Z)):W.innerHTML=q,H&&(b!=null&&b.useCaret)&&!P&&E){let Y=ll(),pe=W.querySelectorAll(".persona-stream-char, .persona-stream-word"),Me=pe[pe.length-1];if(Me!=null&&Me.parentNode)Me.parentNode.insertBefore(Y,Me.nextSibling);else{let Je=W.lastElementChild;Je?Je.appendChild(Y):W.appendChild(Y)}}if(g&&m==="inline"&&e.createdAt){let Y=Lh(e,d,"span");Y.classList.add("persona-timestamp-inline");let pe=W.lastElementChild;pe?pe.appendChild(Y):W.appendChild(Y)}if(T.length>0){let Y=Bb(T,!P&&!!E,()=>{P&&Z&&(Z.style.display="")});Y?C.appendChild(Y):P&&Z&&(Z.style.display="")}let me=Ib(e);if(me.length>0){let Y=Db(me);Y&&C.appendChild(Y)}let Ke=Wb(e);if(Ke.length>0){let Y=Fb(Ke);Y&&C.appendChild(Y)}let Ce=Hb(e);if(Ce.length>0){let Y=Nb(Ce);Y&&C.appendChild(Y)}if(C.appendChild(W),g&&m==="below"&&e.createdAt){let Y=Lh(e,d);Y.classList.add("persona-mt-1"),C.appendChild(Y)}let Ie=e.role==="assistant"?kb(e.stopReason,(Ze=(be=a==null?void 0:a.widgetConfig)==null?void 0:be.copy)==null?void 0:Ze.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(k&&k.trim()),pe=y.placeholder==="skeleton",Me=pe&&y.buffer==="line"&&Y;if(Y)Me&&C.appendChild(Ns());else if(pe)C.appendChild(Ns());else{let Je=wp("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Je&&C.appendChild(Je)}}if(Ie&&e.stopReason&&!e.streaming&&(E||(W.style.display="none"),C.appendChild(Lb(e.stopReason,Ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let Y=Sp(e,o,n);C.appendChild(Y)}if(!u||e.role==="system")return C;let Te=S("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),We=Ob(c,e.role);return p==="right"||p==="left"&&e.role==="user"?Te.append(C,We):Te.append(We,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Te},Rh=(e,t,r,o,n,a)=>{let s=r!=null?r:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ga(e,t,r,o,n,a)};var Ka=new Set,Ub=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),qb=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
27
+ `):""},Ih=(e,t)=>{let r=Ka.has(e),o=t.querySelector('button[data-expand-header="true"]'),n=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!n)return;o.setAttribute("aria-expanded",r?"true":"false");let s=o.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=ve(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}n.style.display=r?"":"none",a&&(a.style.display=r?"none":a.textContent||a.childNodes.length?"":"none")},Ap=(e,t)=>{var Ke,Ce,Ie,Ue,Te,We,de,J,le,ge,ue;let r=e.reasoning,o=S("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!r)return o;let n=(Ce=(Ke=t==null?void 0:t.features)==null?void 0:Ke.reasoningDisplay)!=null?Ce:{},a=n.expandable!==!1,s=a&&Ka.has(e.id),i=r.status!=="complete",c=qb(e,(Ie=n.previewMaxLines)!=null?Ie:3),d=S("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",a&&(d.setAttribute("aria-expanded",s?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let u=S("div","persona-flex persona-flex-col persona-text-left"),g=S("span","persona-text-xs persona-text-persona-primary"),p="Thinking...",m=(Ue=t==null?void 0:t.reasoning)!=null?Ue:{},x=String((Te=r.startedAt)!=null?Te:Date.now()),C=()=>{let G=S("span","");return G.setAttribute("data-tool-elapsed",x),G.textContent=Ei(r),G},T=(We=m.renderCollapsedSummary)==null?void 0:We.call(m,{message:e,reasoning:r,defaultSummary:p,previewText:c,isActive:i,config:t!=null?t:{},elapsed:Ei(r),createElapsedElement:C});typeof T=="string"&&T.trim()?(g.textContent=T,u.appendChild(g)):T instanceof HTMLElement?u.appendChild(T):(g.textContent=p,u.appendChild(g));let E=S("span","persona-text-xs persona-text-persona-primary");E.textContent=Dg(r),u.appendChild(E);let M=(de=n.loadingAnimation)!=null?de:"none",P=m.activeTextTemplate,y=m.completeTextTemplate,w=i?P:y,b=T instanceof HTMLElement,A=(G,ce,Be)=>{let ne=Be;for(let ee of ce){let ie=S("span","persona-tool-char");ie.style.setProperty("--char-index",String(ne)),ie.textContent=ee===" "?"\xA0":ee,G.appendChild(ie),ne++}return ne},H=(G,ce)=>{g.textContent="";let Be=ki(G,""),ne=0;for(let ee of Be){let ie=ee.styles.length>0?(()=>{let vt=S("span",ee.styles.map(Lt=>`persona-tool-text-${Lt}`).join(" "));return g.appendChild(vt),vt})():g;if(ee.isDuration&&i)ie.appendChild(C());else{let vt=ee.isDuration?Ei(r):ee.text;ce?ne=A(ie,vt,ne):ie.appendChild(document.createTextNode(vt))}}};if(!b&&w)if(E.style.display="none",g.style.display="",i&&M!=="none"){let G=(J=m.loadingAnimationDuration)!=null?J:2e3;g.setAttribute("data-preserve-animation","true"),M==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),H(w,!1)):(g.classList.add(`persona-tool-loading-${M}`),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),M==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),H(w,!0))}else H(w,!1);else if(!b&&i&&M!=="none"){g.style.display="";let G=(le=m.loadingAnimationDuration)!=null?le:2e3;if(g.setAttribute("data-preserve-animation","true"),M==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`);else{g.classList.add(`persona-tool-loading-${M}`),g.style.setProperty("--persona-tool-anim-duration",`${G}ms`),M==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ce=g.textContent||p;g.textContent="",A(g,ce,0)}r.status==="complete"&&(g.style.display="none")}else b||(r.status==="complete"?g.style.display="none":g.style.display="");let W=null;if(a){W=S("div","persona-flex persona-items-center");let ce=ve(s?"chevron-up":"chevron-down",16,"currentColor",2);ce?W.appendChild(ce):W.textContent=s?"Hide":"Show";let Be=S("div","persona-flex persona-items-center persona-ml-auto");Be.append(W),d.append(u,Be)}else d.append(u);let k=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!s&&i&&n.activePreview&&c){let G=(ue=(ge=t==null?void 0:t.reasoning)==null?void 0:ge.renderCollapsedPreview)==null?void 0:ue.call(ge,{message:e,reasoning:r,defaultPreview:c,isActive:i,config:t!=null?t:{}});Ub(k,G)||(k.textContent=c),k.style.display=""}if(!s&&i&&n.activeMinHeight&&(o.style.minHeight=n.activeMinHeight),!a)return o.append(d,k),o;let N=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=s?"":"none";let q=r.chunks.join(""),Z=S("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=q||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(Z),(()=>{if(d.setAttribute("aria-expanded",s?"true":"false"),W){W.innerHTML="";let ce=ve(s?"chevron-up":"chevron-down",16,"currentColor",2);ce?W.appendChild(ce):W.textContent=s?"Hide":"Show"}N.style.display=s?"":"none",k.style.display=s?"none":k.textContent||k.childNodes.length?"":"none"})(),o.append(d,k,N),o};var Xa=new Set,Vb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),$b=(e,t)=>{var a;let r=e.toolCall;if(!r)return"";let o=((a=r.chunks)!=null?a:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
28
+ `);let n=Na(r.args).trim();return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
29
+ `):""},zb=(e,t)=>{var u,g,p,m,x;let r=e.toolCall,o=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,n=(g=o==null?void 0:o.collapsedMode)!=null?g:"tool-call",a=$b(e,(p=o==null?void 0:o.previewMaxLines)!=null?p:3),s=r?Fg(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i=r.status!=="complete",c=(m=t==null?void 0:t.toolCall)!=null?m:{},d=s;return n==="tool-name"?d=((x=r.name)==null?void 0:x.trim())||s:n==="tool-preview"&&a&&(d=a),i&&c.activeTextTemplate?d=od(r,c.activeTextTemplate,d):!i&&c.completeTextTemplate&&(d=od(r,c.completeTextTemplate,d)),{summary:d,previewText:a,isActive:i}},Wh=(e,t,r)=>{var u;let o=Xa.has(e),n=(u=r==null?void 0:r.toolCall)!=null?u:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto"),d=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=n.toggleTextColor||n.headerTextColor||"currentColor",p=ve(o?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Mp=(e,t)=>{var q,Z,me,Ke,Ce,Ie,Ue,Te,We;let r=e.toolCall,o=(q=t==null?void 0:t.toolCall)!=null?q:{},n=S("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),o.backgroundColor&&(n.style.backgroundColor=o.backgroundColor),o.borderColor&&(n.style.borderColor=o.borderColor),o.borderWidth&&(n.style.borderWidth=o.borderWidth),o.borderRadius&&(n.style.borderRadius=o.borderRadius),n.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return n;let a=(me=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?me:{},s=a.expandable!==!1,i=s&&Xa.has(e.id),{summary:c,previewText:d,isActive:u}=zb(e,t),g=S("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",s&&(g.setAttribute("aria-expanded",i?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let p=S("div","persona-flex persona-flex-col persona-text-left"),m=S("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let x=String((Ke=r.startedAt)!=null?Ke:Date.now()),C=()=>{let de=S("span","");return de.setAttribute("data-tool-elapsed",x),de.textContent=Es(r),de},T=(Ie=o.renderCollapsedSummary)==null?void 0:Ie.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:d,collapsedMode:(Ce=a.collapsedMode)!=null?Ce:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Es(r),createElapsedElement:C});typeof T=="string"&&T.trim()?(m.textContent=T,p.appendChild(m)):T instanceof HTMLElement?p.appendChild(T):(m.textContent=c,p.appendChild(m));let E=(Ue=a.loadingAnimation)!=null?Ue:"none",M=o.activeTextTemplate,P=o.completeTextTemplate,y=u?M:P,w=T instanceof HTMLElement,b=(de,J,le)=>{let ge=le;for(let ue of J){let G=S("span","persona-tool-char");G.style.setProperty("--char-index",String(ge)),G.textContent=ue===" "?"\xA0":ue,de.appendChild(G),ge++}return ge},A=(de,J)=>{var G;m.textContent="";let le=((G=r.name)==null?void 0:G.trim())||"tool",ge=ki(de,le),ue=0;for(let ce of ge){let Be=ce.styles.length>0?(()=>{let ne=S("span",ce.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(ne),ne})():m;if(ce.isDuration&&u)Be.appendChild(C());else{let ne=ce.isDuration?Es(r):ce.text;J?ue=b(Be,ne,ue):Be.appendChild(document.createTextNode(ne))}}};if(!w)if(u&&E!=="none"){let de=(Te=o.loadingAnimationDuration)!=null?Te:2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),y&&A(y,!1);else if(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),E==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),y)A(y,!0);else{let J=m.textContent||c;m.textContent="",b(m,J,0)}}else y&&A(y,!1);let H=null;if(s){H=S("div","persona-flex persona-items-center");let de=o.toggleTextColor||o.headerTextColor||"currentColor",J=ve(i?"chevron-up":"chevron-down",16,de,2);J?H.appendChild(J):H.textContent=i?"Hide":"Show";let le=S("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");le.append(H),g.append(p,le)}else g.append(p);let W=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","tool"),W.style.display="none",W.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&d){let de=(We=o.renderCollapsedPreview)==null?void 0:We.call(o,{message:e,toolCall:r,defaultPreview:d,isActive:u,config:t!=null?t:{}});Vb(W,de)||(W.textContent=d),W.style.display=""}if(!i&&u&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(g,W),n;let k=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",o.contentBackgroundColor&&(k.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(k.style.color=o.contentTextColor),o.contentPaddingX&&(k.style.paddingLeft=o.contentPaddingX,k.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(k.style.paddingTop=o.contentPaddingY,k.style.paddingBottom=o.contentPaddingY),r.name){let de=S("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?de.style.color=o.contentTextColor:o.headerTextColor&&(de.style.color=o.headerTextColor),de.textContent=r.name,k.appendChild(de)}if(r.args!==void 0){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Arguments";let le=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=Na(r.args),de.append(J,le),k.appendChild(de)}if(r.chunks&&r.chunks.length){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Activity";let le=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=r.chunks.join(""),de.append(J,le),k.appendChild(de)}if(r.status==="complete"&&r.result!==void 0){let de=S("div","persona-space-y-1"),J=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Result";let le=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(le.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(le.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(le.style.color=o.codeBlockTextColor),le.textContent=Na(r.result),de.append(J,le),k.appendChild(de)}if(r.status==="complete"&&typeof r.duration=="number"){let de=S("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(de.style.color=o.contentTextColor),de.textContent=`Duration: ${r.duration}ms`,k.appendChild(de)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),H){H.innerHTML="";let de=o.toggleTextColor||o.headerTextColor||"currentColor",J=ve(i?"chevron-up":"chevron-down",16,de,2);J?H.appendChild(J):H.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",W.style.display=i?"none":W.textContent||W.childNodes.length?"":"none"})(),n.append(g,W,k),n};var bl=new Map,jb=e=>{let r=(e.startsWith(tn)?e.slice(tn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(r.length===0)return e;let o=r.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Hh=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Bh=(e,t)=>{var o,n,a;let r=(n=(o=Hh(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=bl.get(e))!=null?a:r==="expanded"},Dh=(e,t,r)=>{var s,i;let o=Hh(r);e.setAttribute("aria-expanded",t?"true":"false");let n=e.querySelector("[data-approval-details-label]");n&&(n.textContent=t?(s=o==null?void 0:o.hideDetailsLabel)!=null?s:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let c=ve(t?"chevron-up":"chevron-down",14,"currentColor",2);c&&a.appendChild(c)}},Fh=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=Bh(e,r);Dh(o,a,r),n.style.display=a?"":"none"};var vl=(e,t)=>{var A,H,W,k,N,q,Z,me,Ke,Ce,Ie,Ue,Te,We,de;let r=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,n=(r==null?void 0:r.status)==="pending",a=S("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(A=o==null?void 0:o.backgroundColor)!=null?A:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(H=o==null?void 0:o.borderColor)!=null?H:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return a;let s=S("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=S("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let c=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",d=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(W=o==null?void 0:o.titleColor)!=null?W:"currentColor",u=ve(c,20,d,2);u&&i.appendChild(u);let g=S("div","persona-flex-1 persona-min-w-0"),p=S("div","persona-flex persona-items-center persona-gap-2"),m=S("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(k=o==null?void 0:o.title)!=null?k:"Approval Required",p.appendChild(m),!n){let J=S("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");J.setAttribute("data-approval-status",r.status),r.status==="approved"?(J.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",J.style.color="var(--persona-palette-colors-success-700, #15803d)",J.textContent="Approved"):r.status==="denied"?(J.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",J.style.color="var(--persona-palette-colors-error-700, #b91c1c)",J.textContent="Denied"):r.status==="timeout"&&(J.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",J.style.color="var(--persona-palette-colors-warning-700, #b45309)",J.textContent="Timeout"),p.appendChild(J)}g.appendChild(p);let C=r.toolType==="webmcp"||r.toolName.startsWith(tn)?zl(r.toolName):void 0,T=(N=o==null?void 0:o.formatDescription)==null?void 0:N.call(o,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...C?{displayTitle:C}:{},...r.reason?{reason:r.reason}:{}}),E=!r.toolName,M=T||(E?r.description:`The assistant wants to use \u201C${C!=null?C:jb(r.toolName)}\u201D.`),P=S("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(P.style.color=o.descriptionColor),P.textContent=M,g.appendChild(P),r.reason){let J=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");J.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?J.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(J.style.color=o.descriptionColor);let le=S("span","persona-font-medium");le.textContent=`${(q=o==null?void 0:o.reasonLabel)!=null?q:"Agent's stated reason:"} `,J.appendChild(le),J.appendChild(document.createTextNode(r.reason)),g.appendChild(J)}let y=(Z=o==null?void 0:o.detailsDisplay)!=null?Z:"collapsed",w=!!r.description&&!E,b=w||!!r.parameters;if(y!=="hidden"&&b){let J=Bh(e.id,t),le=S("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");le.type="button",le.setAttribute("data-expand-header","true"),le.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(le.style.color=o.descriptionColor);let ge=S("span");ge.setAttribute("data-approval-details-label","true");let ue=S("span","persona-inline-flex persona-items-center");ue.setAttribute("data-approval-details-chevron","true"),le.append(ge,ue),Dh(le,J,t),g.appendChild(le);let G=S("div");if(G.setAttribute("data-approval-details","true"),G.style.display=J?"":"none",w){let ce=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ce.style.color=o.descriptionColor),ce.textContent=r.description,G.appendChild(ce)}if(r.parameters){let ce=S("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(ce.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ce.style.color=o.parameterTextColor),ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",ce.textContent=Na(r.parameters),G.appendChild(ce)}g.appendChild(G)}if(n){let J=S("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");let le=S("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");le.type="button",le.style.backgroundColor=(me=o==null?void 0:o.approveButtonColor)!=null?me:"var(--persona-approval-approve-bg, #22c55e)",le.style.color=(Ke=o==null?void 0:o.approveButtonTextColor)!=null?Ke:"#ffffff",le.setAttribute("data-approval-action","approve");let ge=ve("shield-check",14,(Ce=o==null?void 0:o.approveButtonTextColor)!=null?Ce:"#ffffff",2);ge&&(ge.style.marginRight="4px",le.appendChild(ge));let ue=document.createTextNode((Ie=o==null?void 0:o.approveLabel)!=null?Ie:"Approve");le.appendChild(ue);let G=S("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");G.type="button",G.style.backgroundColor=(Ue=o==null?void 0:o.denyButtonColor)!=null?Ue:"transparent",G.style.color=(Te=o==null?void 0:o.denyButtonTextColor)!=null?Te:"var(--persona-feedback-error, #dc2626)",G.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,G.setAttribute("data-approval-action","deny");let ce=ve("shield-x",14,(We=o==null?void 0:o.denyButtonTextColor)!=null?We:"var(--persona-feedback-error, #dc2626)",2);ce&&(ce.style.marginRight="4px",G.appendChild(ce));let Be=document.createTextNode((de=o==null?void 0:o.denyLabel)!=null?de:"Deny");G.appendChild(Be),J.append(le,G),g.appendChild(J)}return s.append(i,g),a.appendChild(s),a};var Nh=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,d)=>{e.innerHTML="",t.length=0;let u=(d==null?void 0:d.agentPushed)===!0;if(u||(r=null),!n||!n.length||!u&&(i!=null?i:a?a.getMessages():[]).some(T=>T.role==="user"))return;let g=document.createDocumentFragment(),p=a?a.isStreaming():!1,m=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(n.forEach(x=>{let C=S("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=x,C.disabled=p,c!=null&&c.fontFamily&&(C.style.fontFamily=m(c.fontFamily)),c!=null&&c.fontWeight&&(C.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(C.style.paddingLeft=c.paddingX,C.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(C.style.paddingTop=c.paddingY,C.style.paddingBottom=c.paddingY),C.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",u&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),a.sendMessage(x))}),g.appendChild(C),t.push(C)}),e.appendChild(g),u){let x=JSON.stringify(n);x!==r&&(r=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var qs=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of r)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Vs=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let n=o.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(o){r(o)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}};var Gb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Kb=new Set(["step_start","execution_start"]),Xb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Qb=new Set(["step_complete","agent_turn_complete"]),Jb=new Set(["flow_complete","agent_complete"]),Oh=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Uh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ao=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,fa=(e,t)=>{let r=e[t];return Uh(r)?r:void 0};function Tp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Cl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Yb(e,t){return typeof t.type=="string"?t.type:e}function Zb(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function ev(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function _h(e){var o,n,a,s,i;let t=fa(e,"result"),r=[fa(e,"tokens"),fa(e,"totalTokens"),t?fa(t,"tokens"):void 0,fa(e,"usage"),t?fa(t,"usage"):void 0];for(let c of r){if(!c)continue;let d=(n=(o=ao(c.output))!=null?o:ao(c.outputTokens))!=null?n:ao(c.completionTokens);if(d!==void 0)return d}return(i=(a=ao(e.outputTokens))!=null?a:ao(e.completionTokens))!=null?i:t?(s=ao(t.outputTokens))!=null?s:ao(t.completionTokens):void 0}function tv(e){var r,o,n,a,s;let t=fa(e,"result");return(s=(n=(o=(r=ao(e.executionTime))!=null?r:ao(e.executionTimeMs))!=null?o:ao(e.execution_time))!=null?n:ao(e.duration))!=null?s:t?(a=ao(t.executionTime))!=null?a:ao(t.executionTimeMs):void 0}function rv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var $s=class{constructor(t=rv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let r=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:Cl(this.metric.outputTokens,r)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,r){var a;if(!Uh(r)){Oh.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Yb(t,r),n=this.now();if(Gb.has(o)){this.startRun(n);return}if(Kb.has(o)){this.run||this.startRun(n);return}if(Xb.has(o)){if(!ev(o,r))return;let s=Zb(r);if(!s)return;this.run||this.startRun(n);let i=this.run;(a=i.firstDeltaAt)!=null||(i.firstDeltaAt=n),i.visibleCharCount+=s.length;let c=i.exactOutputTokens+Tp(i.visibleCharCount),d=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Cl(c,d),outputTokens:c,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Qb.has(o)){if(!this.run)return;let s=this.run,i=_h(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,d=s.exactOutputTokens+Tp(s.visibleCharCount),u=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:Cl(d,u),outputTokens:d,durationMs:u,source:c?"usage":"estimate"};return}if(Jb.has(o)){if(!this.run)return;let s=this.run,i=_h(r),c=i!=null?i:s.exactOutputTokens+Tp(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:Cl(c,u),outputTokens:c,durationMs:u,source:d},this.run=null;return}if(Oh.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,r,o){let n=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(n!==void 0&&n>=250)return n;let a=tv(r);return a!=null?a:o-t.startedAt}};function Qa(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var ov={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},nv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},av=["flowName","stepName","reasoningText","text","name","tool","toolName"],sv=100;function iv(e,t){let r={...ov,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return nv}function lv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function dv(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${o}:${n}.${a}`}function cv(e,t){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let o of t){let n=o.split("."),a=r;for(let s of n)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function pv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),r()})}function uv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function fv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function mv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function gv(e,t,r){let o,n;try{n=JSON.parse(e.payload),o=JSON.stringify(n,null,2)}catch{n=e.payload,o=e.payload}let a=t.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&r){let i=a.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:n});if(i)return i}return s();function s(){let i=S("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),c=S("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,i.appendChild(c),i}}function Ep(e,t,r,o,n,a,s,i){var p;let c=n.has(e.id),d=S("div","persona-border-b persona-border-persona-divider persona-text-xs");Qa(d,(p=o.classNames)==null?void 0:p.eventRow);let u=s.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>g(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(m)return d.appendChild(m),d}return d.appendChild(g()),d;function g(){var q,Z;let m=S("div",""),x=S("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let C=S("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=ve(c?"chevron-down":"chevron-right","14px","currentColor",2);T&&C.appendChild(T);let E=S("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(q=o.timestampFormat)!=null?q:"relative";E.textContent=M==="relative"?lv(e.timestamp,r):dv(e.timestamp);let P=null;o.showSequenceNumbers!==!1&&(P=S("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let y=iv(e.type,o.badgeColors),w=S("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=y.bg,w.style.color=y.text,w.style.borderColor=y.text+"50",w.textContent=e.type;let b=(Z=o.descriptionFields)!=null?Z:av,A=cv(e.payload,b),H=null;A&&(H=S("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),H.textContent=A);let W=S("div","persona-flex-1 persona-min-w-0"),k=S("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),N=ve("clipboard","12px","currentColor",1.5);return N&&k.appendChild(N),k.addEventListener("click",async me=>{me.stopPropagation(),await pv(uv(e)),k.innerHTML="";let Ke=ve("check","12px","currentColor",1.5);Ke&&k.appendChild(Ke),setTimeout(()=>{k.innerHTML="";let Ce=ve("clipboard","12px","currentColor",1.5);Ce&&k.appendChild(Ce)},1500)}),x.appendChild(C),x.appendChild(E),P&&x.appendChild(P),x.appendChild(w),H&&x.appendChild(H),x.appendChild(W),x.appendChild(k),m.appendChild(x),c&&m.appendChild(gv(e,s,i)),m}}function qh(e){var x,C,T,E,M;let{buffer:t,getFullHistory:r,onClose:o,config:n,plugins:a=[],getThroughput:s}=e,i=(x=n==null?void 0:n.features)==null?void 0:x.scrollToBottom,c=(i==null?void 0:i.enabled)!==!1,d=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",u=(T=i==null?void 0:i.label)!=null?T:"",g=(M=(E=n==null?void 0:n.features)==null?void 0:E.eventStream)!=null?M:{},p=a.find(P=>P.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&n){let P=p.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return m();function m(){let P=g.classNames,y=S("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Qa(y,P==null?void 0:P.panel);let w=[],b="",A="",H=null,W=[],k={},N=0,q=ol(),Z=0,me=0,Ke=!1,Ce=null,Ie=!1,Ue=0,Te=new Set,We=new Map,de="",J="",le=null,ge,ue,G,ce,Be,ne=null,ee=null,ie=null;function vt(){let oe=S("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),we=S("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Qa(we,P==null?void 0:P.headerBar);let De=S("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(De.textContent="Events",ge=S("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),ge.textContent="0",s){ee=S("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let so=S("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");so.textContent="Throughput",ne=S("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ne.textContent="-- tok/s",ie=S("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ie.style.display="none",ie.style.pointerEvents="none";let Rr=ee,ir=ie,Ur=()=>{if(!ir.textContent)return;let yt=Rr.getBoundingClientRect(),jr=oe.getBoundingClientRect();ir.style.left=`${yt.left-jr.left}px`,ir.style.top=`${yt.bottom-jr.top+4}px`,ir.style.display="block"},ko=()=>{ir.style.display="none"};ee.addEventListener("mouseenter",Ur),ee.addEventListener("mouseleave",ko),ee.appendChild(so),ee.appendChild(ne)}let At=S("div","persona-flex-1");ue=S("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ar=S("option","");ar.value="",ar.textContent="All events",ue.appendChild(ar),G=S("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),G.type="button",G.title="Copy All";let wr=ve("clipboard-copy","12px","currentColor",1.5);wr&&G.appendChild(wr);let Ft=S("span","persona-text-xs");Ft.textContent="Copy All",G.appendChild(Ft),we.appendChild(De),we.appendChild(ge),ee&&we.appendChild(ee),we.appendChild(At),we.appendChild(ue),we.appendChild(G);let ot=S("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Qa(ot,P==null?void 0:P.searchBar);let Dt=ve("search","14px","var(--persona-muted, #9ca3af)",1.5),lt=S("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Dt&&lt.appendChild(Dt),ce=S("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Qa(ce,P==null?void 0:P.searchInput),ce.type="text",ce.placeholder="Search event payloads...",Be=S("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Be.type="button",Be.style.display="none";let Yt=ve("x","12px","currentColor",2);return Yt&&Be.appendChild(Yt),ot.appendChild(lt),ot.appendChild(ce),ot.appendChild(Be),oe.appendChild(we),oe.appendChild(ot),ie&&oe.appendChild(ie),oe}let Lt,gt=a.find(oe=>oe.renderEventStreamToolbar);if(gt!=null&&gt.renderEventStreamToolbar&&n){let oe=gt.renderEventStreamToolbar({config:n,defaultRenderer:()=>vt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:we=>{b=we,Wt(),V()},onSearchChange:we=>{A=we,Wt(),V()}});Lt=oe!=null?oe:vt()}else Lt=vt();let _e=S("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");_e.style.display="none";function be(){if(!s||!ne||!ee)return;let oe=s();ne.textContent=fv(oe);let we=mv(oe);ie&&(ie.textContent=we,we||(ie.style.display="none")),we?ee.setAttribute("aria-label",we):ee.removeAttribute("aria-label")}let Ze=S("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=S("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let pe=S("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Qa(pe,P==null?void 0:P.scrollIndicator),pe.style.display="none",pe.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let Me=ve(d,"14px","currentColor",2);Me&&pe.appendChild(Me);let Je=S("span","");Je.textContent=u,pe.appendChild(Je);let Ge=S("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ge.style.display="none",Ze.appendChild(Y),Ze.appendChild(Ge),Ze.appendChild(pe),y.setAttribute("tabindex","0"),y.appendChild(Lt),y.appendChild(_e),y.appendChild(Ze);function ke(){let oe=t.getAll(),we={};for(let Ft of oe)we[Ft.type]=(we[Ft.type]||0)+1;let De=Object.keys(we).sort(),At=De.length!==W.length||!De.every((Ft,ot)=>Ft===W[ot]),ar=!At&&De.some(Ft=>we[Ft]!==k[Ft]),sr=oe.length!==Object.values(k).reduce((Ft,ot)=>Ft+ot,0);if(!At&&!ar&&!sr||(W=De,k=we,!ue))return;let wr=ue.value;if(ue.options[0].textContent="All events",At){for(;ue.options.length>1;)ue.remove(1);for(let Ft of De){let ot=S("option","");ot.value=Ft,ot.textContent=`${Ft} (${we[Ft]||0})`,ue.appendChild(ot)}wr&&De.includes(wr)?ue.value=wr:wr&&(ue.value="",b="")}else for(let Ft=1;Ft<ue.options.length;Ft++){let ot=ue.options[Ft];ot.textContent=`${ot.value} (${we[ot.value]||0})`}}function je(){let oe=t.getAll();if(b&&(oe=oe.filter(we=>we.type===b)),A){let we=A.toLowerCase();oe=oe.filter(De=>De.type.toLowerCase().includes(we)||De.payload.toLowerCase().includes(we))}return oe}function Cr(){return b!==""||A!==""}function Wt(){N=0,Z=0,q.resume(),pe.style.display="none"}function ur(oe){Te.has(oe)?Te.delete(oe):Te.add(oe),le=oe;let we=Y.scrollTop,De=q.isFollowing();Ie=!0,q.pause(),V(),Y.scrollTop=we,De&&q.resume(),Ie=!1}function Eo(){return da(Y,50)}function V(){me=Date.now(),Ke=!1,be(),ke();let oe=t.getEvictedCount();oe>0?(_e.textContent=`${oe.toLocaleString()} older events truncated`,_e.style.display=""):_e.style.display="none",w=je();let we=w.length,De=t.getSize()>0;ge&&(ge.textContent=String(t.getSize())),we===0&&De&&Cr()?(Ge.textContent=A?`No events matching '${A}'`:"No events matching filter",Ge.style.display="",Y.style.display="none"):(Ge.style.display="none",Y.style.display=""),G&&(G.title=Cr()?`Copy Filtered (${we})`:"Copy All"),c&&!q.isFollowing()&&we>N&&(Z+=we-N,Je.textContent=u?`${u}${Z>0?` (${Z})`:""}`:"",pe.style.display=""),N=we;let At=t.getAll(),ar=At.length>0?At[0].timestamp:0,sr=new Set(w.map(ot=>ot.id));for(let ot of Te)sr.has(ot)||Te.delete(ot);let wr=b!==de||A!==J,Ft=We.size===0&&w.length>0;if(wr||Ft||w.length===0){Y.innerHTML="",We.clear();let ot=document.createDocumentFragment();for(let Dt=0;Dt<w.length;Dt++){let lt=Ep(w[Dt],Dt,ar,g,Te,ur,a,n);We.set(w[Dt].id,lt),ot.appendChild(lt)}Y.appendChild(ot),de=b,J=A,le=null}else{if(le!==null){let Dt=We.get(le);if(Dt&&Dt.parentNode===Y){let lt=w.findIndex(Yt=>Yt.id===le);if(lt>=0){let Yt=Ep(w[lt],lt,ar,g,Te,ur,a,n);Y.insertBefore(Yt,Dt),Dt.remove(),We.set(le,Yt)}}le=null}let ot=new Set(w.map(Dt=>Dt.id));for(let[Dt,lt]of We)ot.has(Dt)||(lt.remove(),We.delete(Dt));for(let Dt=0;Dt<w.length;Dt++){let lt=w[Dt];if(!We.has(lt.id)){let Yt=Ep(lt,Dt,ar,g,Te,ur,a,n);We.set(lt.id,Yt),Y.appendChild(Yt)}}}q.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function j(){if(Date.now()-me>=sv){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),V();return}Ke||(Ke=!0,Ce=requestAnimationFrame(()=>{Ce=null,V()}))}let he=(oe,we)=>{if(!G)return;G.innerHTML="";let De=ve(oe,"12px","currentColor",1.5);De&&G.appendChild(De);let At=S("span","persona-text-xs");At.textContent="Copy All",G.appendChild(At),setTimeout(()=>{G.innerHTML="";let ar=ve("clipboard-copy","12px","currentColor",1.5);ar&&G.appendChild(ar);let sr=S("span","persona-text-xs");sr.textContent="Copy All",G.appendChild(sr),G.disabled=!1},we)},Xe=async()=>{if(G){G.disabled=!0;try{let oe;Cr()?oe=w:r?(oe=await r(),oe.length===0&&(oe=t.getAll())):oe=t.getAll();let we=oe.map(De=>{try{return JSON.parse(De.payload)}catch{return De.payload}});await navigator.clipboard.writeText(JSON.stringify(we,null,2)),he("check",1500)}catch{he("x",1500)}}},et=()=>{ue&&(b=ue.value,Wt(),V())},qe=()=>{!ce||!Be||(Be.style.display=ce.value?"":"none",H&&clearTimeout(H),H=setTimeout(()=>{A=ce.value,Wt(),V()},150))},Ne=()=>{!ce||!Be||(ce.value="",A="",Be.style.display="none",H&&clearTimeout(H),Wt(),V())},Pt=()=>{if(Ie)return;let oe=Y.scrollTop,{action:we,nextLastScrollTop:De}=nl({following:q.isFollowing(),currentScrollTop:oe,lastScrollTop:Ue,nearBottom:Eo(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ue=De,we==="resume"?(q.resume(),Z=0,pe.style.display="none"):we==="pause"&&(q.pause(),c&&(Je.textContent=u,pe.style.display=""))},Gt=oe=>{let we=al({following:q.isFollowing(),deltaY:oe.deltaY,nearBottom:Eo(),resumeWhenNearBottom:!0});we==="pause"?(q.pause(),c&&(Je.textContent=u,pe.style.display="")):we==="resume"&&(q.resume(),Z=0,pe.style.display="none")},Jt=()=>{c&&(Y.scrollTop=Y.scrollHeight,q.resume(),Z=0,pe.style.display="none")},Pr=oe=>{let we=oe.target;if(!we||we.closest("button"))return;let De=we.closest("[data-event-id]");if(!De)return;let At=De.getAttribute("data-event-id");At&&ur(At)},z=oe=>{if((oe.metaKey||oe.ctrlKey)&&oe.key==="f"){oe.preventDefault(),ce==null||ce.focus(),ce==null||ce.select();return}oe.key==="Escape"&&(ce&&document.activeElement===ce?(Ne(),ce.blur(),y.focus()):o&&o())};G&&G.addEventListener("click",Xe),ue&&ue.addEventListener("change",et),ce&&ce.addEventListener("input",qe),Be&&Be.addEventListener("click",Ne),Y.addEventListener("scroll",Pt),Y.addEventListener("wheel",Gt,{passive:!0}),Y.addEventListener("click",Pr),pe.addEventListener("click",Jt),y.addEventListener("keydown",z);function Ht(){H&&clearTimeout(H),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ke=!1,We.clear(),G&&G.removeEventListener("click",Xe),ue&&ue.removeEventListener("change",et),ce&&ce.removeEventListener("input",qe),Be&&Be.removeEventListener("click",Ne),Y.removeEventListener("scroll",Pt),Y.removeEventListener("wheel",Gt),Y.removeEventListener("click",Pr),pe.removeEventListener("click",Jt),y.removeEventListener("keydown",z)}return{element:y,update:j,destroy:Ht}}}function Vh(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",n=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=r;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #171717)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(p);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,g.appendChild(m)}else g.textContent=s;if(d.append(u,g),i.append(c,d),n==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${r}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",o),i.append(p)}return i}var $h=(e,t)=>{var o,n,a;let r=(a=(n=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(r){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",c=e.status==="streaming"?"streaming":"complete",d=typeof e.artifactType=="string"?e.artifactType:"markdown",u=r({artifact:{artifactId:i,title:s,artifactType:d,status:c},config:t.config,defaultRenderer:()=>Vh(e,t)});if(u)return u}return Vh(e,t)};var kp=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,o])=>{this.register(r,o)})}},dn=new kp;dn.register("PersonaArtifactCard",$h);function hv(e){var n;let t=S("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=S("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let o=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((n=e.props)!=null?n:{},null,2),t.appendChild(r),t.appendChild(o),t}function zh(e,t){var ue,G,ce,Be;let r=(G=(ue=e.features)==null?void 0:ue.artifacts)==null?void 0:G.layout,n=((ce=r==null?void 0:r.toolbarPreset)!=null?ce:"default")==="document",a=(Be=r==null?void 0:r.panePadding)==null?void 0:Be.trim(),s=e.markdown?Zn(e.markdown):null,i=Wa(e.sanitize),c=ne=>{let ee=s?s(ne):qo(ne);return i?i(ee):ee},d=typeof document!="undefined"?S("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{d==null||d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};d&&d.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let g=S("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");g.setAttribute("data-persona-theme-zone","artifact-pane"),n&&g.classList.add("persona-artifact-pane-document");let p=S("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");p.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&p.classList.add("persona-artifact-toolbar-document");let m=S("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=S("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let C="rendered",T=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=n?yr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):yr({icon:"eye",label:"Rendered view"}),M=n?yr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):yr({icon:"code-2",label:"Source"}),P=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),y=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,w=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,b=r==null?void 0:r.documentToolbarCopyMenuItems,A=!!(w&&b&&b.length>0),H=null,W,k=null,N=null;if(n&&(y||w)&&!A){if(W=y?Us({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let ne=ve("chevron-down",14,"currentColor",2);ne&&W.appendChild(ne)}}else n&&A?(H=S("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),W=y?Us({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=yr({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),H.append(W,k)):n?W=yr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):W=yr({icon:"copy",label:"Copy"});let q=n?yr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):yr({icon:"refresh-cw",label:"Refresh"}),Z=n?yr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):yr({icon:"x",label:"Close"}),me=()=>{var Lt,gt,_e;let ne=(Lt=We.find(be=>be.id===de))!=null?Lt:We[We.length-1],ee=(gt=ne==null?void 0:ne.id)!=null?gt:null,ie=(ne==null?void 0:ne.artifactType)==="markdown"&&(_e=ne.markdown)!=null?_e:"",vt=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:ie,jsonPayload:vt,id:ee}},Ke=async()=>{var Lt;let{markdown:ne,jsonPayload:ee}=me(),ie=(Lt=We.find(gt=>gt.id===de))!=null?Lt:We[We.length-1],vt=(ie==null?void 0:ie.artifactType)==="markdown"?ne:ie?ee:"";try{await navigator.clipboard.writeText(vt)}catch{}};if(W.addEventListener("click",async()=>{let ne=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(ne&&A){let{markdown:ee,jsonPayload:ie,id:vt}=me();try{await ne({actionId:"primary",artifactId:vt,markdown:ee,jsonPayload:ie})}catch{}return}await Ke()}),k&&(b!=null&&b.length)){let ne=()=>{var ie;return(ie=g.closest("[data-persona-root]"))!=null?ie:document.body},ee=()=>{N=Fn({items:b.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:vt,jsonPayload:Lt,id:gt}=me(),_e=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:ie,artifactId:gt,markdown:vt,jsonPayload:Lt}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(vt):ie==="json"||ie==="source"?await navigator.clipboard.writeText(Lt):await navigator.clipboard.writeText(vt||Lt)}catch{}},anchor:H!=null?H:k,position:"bottom-right",portal:ne()})};g.isConnected?ee():requestAnimationFrame(ee),k.addEventListener("click",ie=>{ie.stopPropagation(),N==null||N.toggle()})}q.addEventListener("click",async()=>{var ne;try{await((ne=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:ne.call(r))}catch{}le()}),Z.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let Ce=()=>{n&&(E.setAttribute("aria-pressed",C==="rendered"?"true":"false"),M.setAttribute("aria-pressed",C==="source"?"true":"false"))};E.addEventListener("click",()=>{C="rendered",Ce(),le()}),M.addEventListener("click",()=>{C="source",Ce(),le()});let Ie=S("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");n?(p.replaceChildren(),T.append(E,M),H?P.append(H,q,Z):P.append(W,q,Z),p.append(T,Ie,P),Ce()):(p.appendChild(m),p.appendChild(x)),a&&(p.style.paddingLeft=a,p.style.paddingRight=a);let Ue=S("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Te=S("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(Ue.style.paddingLeft=a,Ue.style.paddingRight=a,Te.style.padding=a),g.appendChild(p),g.appendChild(Ue),g.appendChild(Te);let We=[],de=null,J=!1,le=()=>{var vt,Lt,gt,_e;let ne=n&&We.length<=1;Ue.classList.toggle("persona-hidden",ne),Ue.replaceChildren();for(let be of We){let Ze=S("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Ze.type="button",Ze.textContent=be.title||be.id.slice(0,8),be.id===de&&Ze.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ze.addEventListener("click",()=>t.onSelect(be.id)),Ue.appendChild(Ze)}Te.replaceChildren();let ee=de&&We.find(be=>be.id===de)||We[We.length-1];if(!ee)return;if(n){let be=ee.artifactType==="markdown"?"MD":(vt=ee.component)!=null?vt:"Component",Y=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ie.textContent=`${Y} \xB7 ${be}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(n&&C==="source"){let Ze=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ze.textContent=(Lt=ee.markdown)!=null?Lt:"",Te.appendChild(Ze);return}let be=S("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");be.innerHTML=c((gt=ee.markdown)!=null?gt:""),Te.appendChild(be);return}let ie=ee.component?dn.get(ee.component):void 0;if(ie){let Ze={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Y=ie((_e=ee.props)!=null?_e:{},Ze);if(Y){Te.appendChild(Y);return}}catch{}}Te.appendChild(hv(ee))},ge=()=>{var ee;let ne=We.length>0;if(g.classList.toggle("persona-hidden",!ne),d){let ie=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,Lt=((ee=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ne&&Lt&&J?(d.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:d,update(ne){var ee,ie,vt;We=ne.artifacts,de=(vt=(ie=ne.selectedId)!=null?ie:(ee=ne.artifacts[ne.artifacts.length-1])==null?void 0:ee.id)!=null?vt:null,We.length>0&&(J=!0),le(),ge()},setMobileOpen(ne){J=ne,!ne&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):ge()}}}function xo(e){var t,r;return((r=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:r.enabled)===!0}function jh(e,t){var a,s,i,c;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!xo(t))return;let r=(s=(a=t.features)==null?void 0:a.artifacts)==null?void 0:s.layout,o=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),n=(c=r==null?void 0:r.paneBorderLeft)==null?void 0:c.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}function xv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function wl(e,t){var c,d,u,g,p,m,x,C,T,E;if(!xo(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),xv(e),jh(e,t);return}let r=(d=(c=t.features)==null?void 0:c.artifacts)==null?void 0:d.layout;e.style.setProperty("--persona-artifact-split-gap",(u=r==null?void 0:r.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(g=r==null?void 0:r.paneWidth)!=null?g:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(p=r==null?void 0:r.paneMaxWidth)!=null?p:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=r==null?void 0:r.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let n=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();n?e.style.setProperty("--persona-artifact-pane-padding",n):e.style.removeProperty("--persona-artifact-pane-padding");let a=(C=r==null?void 0:r.documentToolbarIconColor)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(T=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:T.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),jh(e,t)}var Gh=["panel","seamless"];function Sl(e,t){var i,c,d,u,g,p;for(let m of Gh)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!xo(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(d=r==null?void 0:r.paneAppearance)!=null?d:"panel",n=Gh.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${n}`);let a=(u=r==null?void 0:r.paneBorderRadius)==null?void 0:u.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(g=r==null?void 0:r.paneShadow)==null?void 0:g.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((p=r.unifiedSplitOuterRadius)==null?void 0:p.trim())||a;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Kh(e,t){var r,o,n;return!t||!xo(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function yv(e,t){if(!(e!=null&&e.trim()))return t;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):t}function bv(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function vv(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function Cv(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function Xh(e,t){var s;let o=(s=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",n=/^([\d.]+)px$/i.exec(o);if(n)return Number(n[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function Qh(e,t,r,o,n,a){let s=yv(n,200),i=Cv(t,r,o,200);i=Math.max(s,i);let c=bv(a);return c!==null&&(i=Math.min(i,c)),vv(e,s,i)}var Jh={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Lp=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var x,C,T;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(C=Jh[s])!=null?C:Jh.init;a.classList.add("persona-form-card","persona-space-y-4");let c=S("div","persona-space-y-1"),d=S("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,c.appendChild(d),i.description){let E=S("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,c.appendChild(E)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var b,A;let M=S("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${t.id}-${s}-${E.name}`;let P=S("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=E.label,M.appendChild(P);let y=(b=E.type)!=null?b:"text",w;y==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=y),w.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",w.id=`${t.id}-${s}-${E.name}`,w.name=E.name,w.placeholder=(A=E.placeholder)!=null?A:"",E.required&&(w.required=!0),M.appendChild(w),u.appendChild(M)});let g=S("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),p=S("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=S("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(T=i.submitLabel)!=null?T:"Submit",g.appendChild(p),g.appendChild(m),u.appendChild(g),a.replaceChildren(c,u),u.addEventListener("submit",async E=>{var w,b;E.preventDefault();let M=(w=r.formEndpoint)!=null?w:"/form",P=new FormData(u),y={};P.forEach((A,H)=>{y[H]=A}),y.type=s,m.disabled=!0,p.textContent="Submitting\u2026";try{let A=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!A.ok)throw new Error(`Form submission failed (${A.status})`);let H=await A.json();p.textContent=(b=H.message)!=null?b:"Thanks! We'll be in touch soon.",H.success&&H.nextPrompt&&await o.sendMessage(String(H.nextPrompt))}catch(A){p.textContent=A instanceof Error?A.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Pp=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var o;let r=this.plugins.get(t);r&&((o=r.onUnregister)==null||o.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var o,n;return((o=r.priority)!=null?o:0)-((n=t.priority)!=null?n:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let o=new Set(t.map(a=>a.id));return[...r.filter(a=>!o.has(a.id)),...t].sort((a,s)=>{var i,c;return((i=s.priority)!=null?i:0)-((c=a.priority)!=null?c:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},zs=new Pp;var Yh=()=>{let e=new Map,t=(n,a)=>(e.has(n)||e.set(n,new Set),e.get(n).add(a),()=>r(n,a)),r=(n,a)=>{var s;(s=e.get(n))==null||s.delete(a)};return{on:t,off:r,emit:(n,a)=>{var s;(s=e.get(n))==null||s.forEach(i=>{try{i(a)}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var wv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Sv=e=>{let t=e.trim(),r=t.indexOf("{");if(r===-1)return null;let o=0;for(let n=r;n<t.length;n+=1){let a=t[n];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(r,n+1)}return null},js=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=wv(e),r=Sv(t);if(!r)return null;let o=JSON.parse(r);if(!o||typeof o!="object"||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},Rp=e=>typeof e=="string"?e:e==null?"":String(e),ma={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Rp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=Rp(r.element);if(o&&((n=t.document)!=null&&n.querySelector)){let a=t.document.querySelector(o);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Rp(r.text)}}},Zh=e=>Array.isArray(e)?e.map(t=>String(t)):[],Gs=e=>{let t=new Set(Zh(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(Zh(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?e.parsers.reduce((d,u)=>d||(u==null?void 0:u({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),o();let c={action:i,message:a.message};e.emit("action:detected",c);for(let d of e.handlers)if(d)try{let u=()=>{e.emit("action:resubmit",c)},g=d(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let p=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:p,resubmit:g.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:r}};var Av=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Mv=e=>e.map(t=>({...t,streaming:!1})),Tv=e=>e.map(t=>({...t,status:"complete"})),Al=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Av(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?Mv(r.messages):void 0,artifacts:r.artifacts?Tv(r.artifacts):void 0};o.setItem(e,JSON.stringify(n))}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",n)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Ja=Pa(bi(),1);function Ev(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function kv(e,t){if(!Ev(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:t}}function Ml(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e;try{let n=(0,Ja.parse)(r,Ja.STR|Ja.OBJ),a=kv(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function ex(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Tl(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=dn.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:r,updateProps:i=>{n&&n(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function tx(){let e=Ml();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function rx(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function El(e){let t=rx(e);if(!t)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function kl(e){let t=rx(e);if(!t)return null;try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let o=r;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Lv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ll(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,ratingLabels:d=Lv}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let g=null,p=document.createElement("div");p.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,m.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=n,m.appendChild(C),p.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let b=1;b<=5;b++){let A=document.createElement("button");A.type="button",A.className="persona-feedback-rating-btn persona-feedback-star-btn",A.setAttribute("role","radio"),A.setAttribute("aria-checked","false"),A.setAttribute("aria-label",`${b} star${b>1?"s":""}: ${d[b-1]}`),A.title=d[b-1],A.dataset.rating=String(b),A.innerHTML=`
30
30
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
31
31
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
32
32
  </svg>
33
- `,A.addEventListener("click",()=>{g=b,E.forEach((H,W)=>{let k=W<b;H.classList.toggle("selected",k),H.setAttribute("aria-checked",W===b-1?"true":"false")})}),E.push(A),T.appendChild(A)}p.appendChild(T);let M=null;if(c){let b=document.createElement("div");b.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),b.appendChild(M),p.appendChild(b)}let P=document.createElement("div");P.className="persona-feedback-actions";let y=document.createElement("button");y.type="button",y.className="persona-feedback-btn persona-feedback-btn-skip",y.textContent=i,y.addEventListener("click",()=>{r==null||r(),u.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=s,w.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let b=(M==null?void 0:M.value.trim())||void 0;await t(g,b),u.remove()}catch(b){w.disabled=!1,w.textContent=s,console.error("[CSAT Feedback] Failed to submit:",b)}}),P.appendChild(y),P.appendChild(w),p.appendChild(P),u.appendChild(p),u}function 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:d="Not likely",highLabel:u="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let p=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,x.appendChild(C);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=n,x.appendChild(T),m.appendChild(x);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=d;let y=document.createElement("span");y.className="persona-feedback-label-high",y.textContent=u,M.appendChild(P),M.appendChild(y);let w=document.createElement("div");w.className="persona-feedback-numbers";let b=[];for(let N=0;N<=10;N++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${N} out of 10`),q.textContent=String(N),q.dataset.rating=String(N),N<=6?q.classList.add("persona-feedback-detractor"):N<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{p=N,b.forEach((Z,me)=>{Z.classList.toggle("selected",me===N),Z.setAttribute("aria-checked",me===N?"true":"false")})}),b.push(q),w.appendChild(q)}E.appendChild(M),E.appendChild(w),m.appendChild(E);let A=null;if(c){let N=document.createElement("div");N.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),N.appendChild(A),m.appendChild(N)}let H=document.createElement("div");H.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=i,W.addEventListener("click",()=>{r==null||r(),g.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=s,k.addEventListener("click",async()=>{if(p===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let N=(A==null?void 0:A.value.trim())||void 0;await t(p,N),g.remove()}catch(N){k.disabled=!1,k.textContent=s,console.error("[NPS Feedback] Failed to submit:",N)}}),H.appendChild(W),H.appendChild(k),m.appendChild(H),g.appendChild(m),g}var Ja="persona-chat-history",Lv=30*1e3,Pv={"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 Rv(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=Pv[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 Pl(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 Iv(e){var t,r,o,n,a,s,i,c,d;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(n=(o=e.persist)==null?void 0:o.openState)!=null?n:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(c=(i=e.persist)==null?void 0:i.focusInput)!=null?c:!0},clearOnChatClear:(d=e.clearOnChatClear)!=null?d:!0}:null}function Wv(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Rp=e=>!e||typeof e!="object"?{}:{...e},tx=e=>e.map(t=>({...t,streaming:!1})),rx=(e,t,r)=>{let o=e!=null&&e.markdown?Zn(e.markdown):null,n=Ia(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&n&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),a=>{var d,u,g;let s=(d=a.text)!=null?d:"",i=(u=a.message.rawContent)!=null?u:null;if(t){let p=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});p!==null&&(s=p.text,p.persist||(a.message.__skipPersist=!0),p.resubmit&&!a.streaming&&r&&r())}let c;return e!=null&&e.postprocessMessage?c=e.postprocessMessage({...a,text:s,raw:(g=i!=null?i:a.text)!=null?g:""}):o?c=o(s):c=qo(s),n?n(c):c}};function ox(e){var i,c,d,u;let t=S("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let r=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(c=e==null?void 0:e.iconSize)!=null?c:"48px",n=(d=e==null?void 0:e.iconColor)!=null?d:"rgba(59, 130, 246, 0.6)",a=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,s=ve(r,o,n,a);if(s&&t.appendChild(s),e!=null&&e.label){let g=S("span","persona-drop-overlay-label");g.textContent=e.label,t.appendChild(g)}return t}var Rl=(e,t,r)=>{var uu,fu,mu,gu,hu,xu,yu,bu,vu,Cu,wu,Su,Au,Mu,Tu,Eu,ku,Lu,Pu,Ru,Iu,Wu,Hu,Bu,Du,Fu,Nu,Ou,_u,Uu,qu,Vu,$u,zu,ju,Gu,Ku,Xu,Qu,Ju,Yu,Zu,ef,tf,rf,of,nf,af,sf,lf;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=Qi(t),n=$s.getForInstance(o.plugins);o.components&&dn.registerAll(o.components);let a=Qh(),i=o.persistState===!1?null:(uu=o.storageAdapter)!=null?uu:Sl(),c={},d=null,u=!1,g=l=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(l);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:v}=f;return v&&(u=!0),h}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l.then(f=>{let h=f!=null?f:{messages:[],metadata:{}};return g(h)});else{let f=l!=null?l:{messages:[],metadata:{}},h=g(f);h.metadata&&(c=Rp(h.metadata)),(fu=h.messages)!=null&&fu.length&&(o={...o,initialMessages:h.messages}),(mu=h.artifacts)!=null&&mu.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(gu=h.selectedArtifactId)!=null?gu:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=g({messages:[],metadata:{}});(hu=l.messages)!=null&&hu.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>c,m=l=>{var h;c=(h=l({...c}))!=null?h:{},Ca()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zs],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[fa.message,fa.messageAndClick],T=js({parsers:x,handlers:C,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let E=(yu=(xu=o.launcher)==null?void 0:xu.enabled)!=null?yu:!0,M=(vu=(bu=o.launcher)==null?void 0:bu.autoExpand)!=null?vu:!1,P=(Cu=o.autoFocusInput)!=null?Cu:!1,y=M,w=E,b=(Su=(wu=o.layout)==null?void 0:wu.header)==null?void 0:Su.layout,A=!1,H=()=>Dn(o),W=()=>E||H(),k=H()?!1:E?M:!0,N=!1,q=null,Z=()=>{N=!0,q&&clearTimeout(q),q=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},me=rx(o,T,Z),Ke=(Mu=(Au=o.features)==null?void 0:Au.showReasoning)!=null?Mu:!0,Ce=(Eu=(Tu=o.features)==null?void 0:Tu.showToolCalls)!=null?Eu:!0,Ie=(Lu=(ku=o.features)==null?void 0:ku.showEventStreamToggle)!=null?Lu:!1,Ue=(Ru=(Pu=o.features)==null?void 0:Pu.scrollToBottom)!=null?Ru:{},Te=(Wu=(Iu=o.features)==null?void 0:Iu.scrollBehavior)!=null?Wu:{},de=`${(Bu=typeof o.persistState=="object"?(Hu=o.persistState)==null?void 0:Hu.keyPrefix:void 0)!=null?Bu:"persona-"}event-stream`,J=Ie?new qs(de):null,le=(Nu=(Fu=(Du=o.features)==null?void 0:Du.eventStream)==null?void 0:Fu.maxEvents)!=null?Nu:2e3,ge=Ie?new Us(le,J):null,ue=Ie?new Vs:null,G=null,ce=!1,Be=null,ne=0;J==null||J.open().then(()=>ge==null?void 0:ge.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ee={onCopy:l=>{var f,h;a.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(v=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",v)}),(h=(f=o.messageActions)==null?void 0:f.onCopy)==null||h.call(f,l)},onFeedback:l=>{var f,h;a.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(v=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",v)}),(h=(f=o.messageActions)==null?void 0:f.onFeedback)==null||h.call(f,l)}},ie=(Ou=o.statusIndicator)!=null?Ou:{},vt=l=>{var f,h,v,R;return l==="idle"?(f=ie.idleText)!=null?f:kr.idle:l==="connecting"?(h=ie.connectingText)!=null?h:kr.connecting:l==="connected"?(v=ie.connectedText)!=null?v:kr.connected:l==="error"?(R=ie.errorText)!=null?R:kr.error:kr[l]};function Lt(l,f,h,v){if(v==="idle"&&h.idleLink){l.textContent="";let R=document.createElement("a");R.href=h.idleLink,R.target="_blank",R.rel="noopener noreferrer",R.textContent=f,R.style.color="inherit",R.style.textDecoration="none",l.appendChild(R)}else l.textContent=f}let gt=Th({config:o,showClose:W()}),{wrapper:_e,panel:be,pillRoot:Ze}=gt.shell,Y=gt.panelElements,{container:pe,body:Me,messagesWrapper:Je,suggestions:Ge,textarea:ke,sendButton:je,sendButtonWrapper:Cr,composerForm:Wt,statusText:ur,introTitle:Eo,introSubtitle:V,closeButton:j,iconHolder:he,headerTitle:Xe,headerSubtitle:et,header:qe,footer:Ne,actionsRow:Pt,leftActions:Gt,rightActions:Jt}=Y,Pr=Y.setSendButtonMode,z=Y.micButton,Ht=Y.micButtonWrapper,oe=Y.attachmentButton,we=Y.attachmentButtonWrapper,De=Y.attachmentInput,At=Y.attachmentPreviewsContainer;pe.classList.add("persona-relative"),Me.classList.add("persona-relative");let ar=12,sr=()=>{var l;return(l=Ue.label)!=null?l:""},wr=()=>{var l;return(l=Ue.iconName)!=null?l:"arrow-down"},Ft=()=>Ue.enabled!==!1,ot=()=>{var l;return(l=Te.mode)!=null?l:"follow"},Dt=()=>{var l;return(l=Te.anchorTopOffset)!=null?l:16},lt=S("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");lt.type="button",lt.style.display="none",lt.setAttribute("data-persona-scroll-to-bottom","true");let Yt=S("span","persona-flex persona-items-center"),so=S("span",""),Rr=S("span","");Rr.setAttribute("data-persona-scroll-to-bottom-count",""),Rr.style.display="none",lt.append(Yt,so,Rr),pe.appendChild(lt);let ir=S("div","persona-stream-anchor-spacer");ir.setAttribute("aria-hidden","true"),ir.setAttribute("data-persona-anchor-spacer",""),ir.style.flexShrink="0",ir.style.pointerEvents="none",ir.style.height="0px",Me.appendChild(ir);let Ur=()=>{let f=Ne.style.display==="none"?0:Ne.offsetHeight;lt.style.bottom=`${f+ar}px`};Ur();let ko=()=>{let l=!!sr();lt.setAttribute("aria-label",sr()||"Jump to latest"),lt.title=sr(),lt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Yt.innerHTML="";let f=ve(wr(),"14px","currentColor",2);f?(Yt.appendChild(f),Yt.style.display=""):Yt.style.display="none",so.textContent=sr(),so.style.display=l?"":"none"};ko();let yt=null,jr=null,Lo=n.find(l=>l.renderHeader);if(Lo!=null&&Lo.renderHeader){let l=Lo.renderHeader({config:o,defaultRenderer:()=>{let f=ln({config:o,showClose:W()});return ca(pe,f,o),f.header},onClose:()=>I(!1,"user")});if(l){let f=pe.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),qe=l,gt.header.element=l)}}let zo=()=>{var f,h,v,R;if(!ge)return;if(ce=!0,!G&&ge&&(G=_h({buffer:ge,getFullHistory:()=>ge.getAllFromStore(),onClose:()=>yo(),config:o,plugins:n,getThroughput:()=>{var F;return(F=ue==null?void 0:ue.getMetric())!=null?F:{status:"idle"}}})),G&&(Me.style.display="none",(f=Ne.parentNode)==null||f.insertBefore(G.element,Ne),G.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${_r.actionIconColor}`;let F=(R=(v=(h=o.features)==null?void 0:h.eventStream)==null?void 0:v.classNames)==null?void 0:R.toggleButtonActive;F&&F.split(/\s+/).forEach($=>$&&ht.classList.add($))}let l=()=>{if(!ce)return;let F=Date.now();F-ne>=200&&(G==null||G.update(),ne=F),Be=requestAnimationFrame(l)};ne=0,Be=requestAnimationFrame(l),$r(),a.emit("eventStream:opened",{timestamp:Date.now()})},yo=()=>{var l,f,h;if(ce){if(ce=!1,G&&G.element.remove(),Me.style.display="",ht){ht.style.boxShadow="";let v=(h=(f=(l=o.features)==null?void 0:l.eventStream)==null?void 0:f.classNames)==null?void 0:h.toggleButtonActive;v&&v.split(/\s+/).forEach(R=>R&&ht.classList.remove(R))}Be!==null&&(cancelAnimationFrame(Be),Be=null),$r(),a.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(Ie){let l=(Uu=(_u=o.features)==null?void 0:_u.eventStream)==null?void 0:Uu.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");ht=S("button",f),ht.style.width="28px",ht.style.height="28px",ht.style.color=_r.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let h=ve("activity","18px","currentColor",1.5);h&&ht.appendChild(h);let v=Y.clearChatButtonWrapper,R=Y.closeButtonWrapper,F=v||R;F&&F.parentNode===qe?qe.insertBefore(ht,F):qe.appendChild(ht),ht.addEventListener("click",()=>{ce?yo():zo()})}let Nn=l=>{var R,F,$,O,D;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=(R=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?R:l.querySelector(".persona-attachment-previews");if(!h){h=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let ae=l.querySelector("[data-persona-composer-form]");ae!=null&&ae.parentNode?ae.parentNode.insertBefore(h,ae):l.insertBefore(h,l.firstChild)}if(!((F=l.querySelector("[data-persona-composer-attachment-input]"))!=null?F:l.querySelector('input[type="file"]'))){let ae=S("input");ae.type="file",ae.setAttribute("data-persona-composer-attachment-input",""),ae.accept=(($=f.allowedTypes)!=null?$:an).join(","),ae.multiple=((O=f.maxFiles)!=null?O:4)>1,ae.style.display="none",ae.setAttribute("aria-label",(D=f.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(ae)}},Po=n.find(l=>l.renderComposer);if(Po!=null&&Po.renderComposer){let l=o.composer,f=Po.renderComposer({config:o,defaultRenderer:()=>za({config:o}).footer,onSubmit:h=>{var $;if(!_||_.isStreaming())return;let v=h.trim(),R=($=yt==null?void 0:yt.hasAttachments())!=null?$:!1;if(!v&&!R)return;tt();let F;R&&(F=[],F.push(...yt.getContentParts()),v&&F.push(Es(v))),_.sendMessage(v,{contentParts:F}),R&&yt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{De==null||De.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((qu=o.voiceRecognition)==null?void 0:qu.enabled)===!0?()=>{jr==null||jr()}:void 0});f&&(gt.replaceComposer(f),Ne=gt.composer.footer)}let On=l=>{let f=(...se)=>{for(let Q of se){let ye=l.querySelector(Q);if(ye)return ye}return null},h=l.querySelector("[data-persona-composer-form]"),v=l.querySelector("[data-persona-composer-input]"),R=l.querySelector("[data-persona-composer-submit]"),F=l.querySelector("[data-persona-composer-mic]"),$=l.querySelector("[data-persona-composer-status]");h&&(Wt=h),v&&(ke=v),R&&(je=R),F&&(z=F,Ht=F.parentElement),$&&(ur=$);let O=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Ge=O);let D=f("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(oe=D,we=D.parentElement),De=f("[data-persona-composer-attachment-input]",'input[type="file"]'),At=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(Pt=ae)};Nn(Ne),On(Ne);let qr=(Gu=(Vu=o.layout)==null?void 0:Vu.contentMaxWidth)!=null?Gu:H()?(ju=(zu=($u=o.launcher)==null?void 0:$u.composerBar)==null?void 0:zu.contentMaxWidth)!=null?ju:"720px":void 0;if(qr&&(Je.style.maxWidth=qr,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%"),qr&&Wt&&!H()&&(Wt.style.maxWidth=qr,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),qr&&Ge&&!H()&&(Ge.style.maxWidth=qr,Ge.style.marginLeft="auto",Ge.style.marginRight="auto"),qr&&At&&!H()&&(At.style.maxWidth=qr,At.style.marginLeft="auto",At.style.marginRight="auto"),(Ku=o.attachments)!=null&&Ku.enabled&&De&&At){yt=ia.fromConfig(o.attachments),yt.setPreviewsContainer(At),De.addEventListener("change",h=>{let v=h.target;yt==null||yt.handleFileSelect(v.files),v.value=""});let l=o.attachments.dropOverlay,f=ox(l);pe.appendChild(f)}(()=>{var v,R;let l=(R=(v=o.layout)==null?void 0:v.slots)!=null?R:{},f=F=>{switch(F){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Je;case"footer-top":return Ge;case"composer":return Wt;case"footer-bottom":return ur;default:return null}},h=(F,$)=>{var O;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")qe.insertBefore($,qe.firstChild);else if(F==="header-right")qe.appendChild($);else{let D=qe.querySelector(".persona-flex-col");D?(O=D.parentNode)==null||O.insertBefore($,D.nextSibling):qe.appendChild($)}break;case"body-top":{let D=Me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith($):Me.insertBefore($,Me.firstChild);break}case"body-bottom":Me.appendChild($);break;case"footer-top":Ge.replaceWith($);break;case"footer-bottom":ur.replaceWith($);break;default:break}};for(let[F,$]of Object.entries(l))if($)try{let O=$({config:o,defaultContent:()=>f(F)});O&&h(F,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,O)}})();let cn=l=>{var $,O;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let v=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let R=v.getAttribute("data-message-id");if(!R)return;let F=h.getAttribute("data-bubble-type");if(F==="reasoning")Ga.has(R)?Ga.delete(R):Ga.add(R),Ph(R,v);else if(F==="tool")Ka.has(R)?Ka.delete(R):Ka.add(R),Rh(R,v,o);else if(F==="approval"){let D=o.approval!==!1?o.approval:void 0,ae=(($=D==null?void 0:D.detailsDisplay)!=null?$:"collapsed")==="expanded",se=(O=yl.get(R))!=null?O:ae;yl.set(R,!se),Bh(R,v,o)}Bo.delete(R)};Je.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))}),Je.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))});let jo=new Map,pn=null,un="idle",_n={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Un=(l,f)=>{let{icon:h,label:v}=_n[f];l.setAttribute("aria-label",v),l.title=v,l.setAttribute("aria-pressed",f==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",f!=="idle"),l.classList.toggle("persona-message-action-loading",f==="loading");let R=ve(h,14,"currentColor",2);R&&(l.innerHTML="",l.appendChild(R))},fn=()=>{Je.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{var F;let h=f.closest("[data-actions-for]"),v=(F=h==null?void 0:h.getAttribute("data-actions-for"))!=null?F:null;Un(f,v&&v===pn?un:"idle")})};Je.addEventListener("click",l=>{var $;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.closest("[data-actions-for]");if(!v)return;let R=v.getAttribute("data-actions-for");if(!R)return;let F=h.getAttribute("data-action");if(F==="copy"){let D=_.getMessages().find(ae=>ae.id===R);if(D&&ee.onCopy){let ae=D.content||"";navigator.clipboard.writeText(ae).then(()=>{h.classList.add("persona-message-action-success");let se=ve("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Q=ve("copy",14,"currentColor",2);Q&&(h.innerHTML="",h.appendChild(Q))},2e3)}).catch(se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",se)}),ee.onCopy(D)}}else if(F==="read-aloud")_.toggleReadAloud(R);else if(F==="upvote"||F==="downvote"){let D=(($=jo.get(R))!=null?$:null)===F,ae=F==="upvote"?"thumbs-up":"thumbs-down";if(D){jo.delete(R),h.classList.remove("persona-message-action-active");let se=ve(ae,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=F==="upvote"?"downvote":"upvote",Q=v.querySelector(`[data-action="${se}"]`);if(Q){Q.classList.remove("persona-message-action-active");let $e=ve(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);$e&&(Q.innerHTML="",Q.appendChild($e))}jo.set(R,F),h.classList.add("persona-message-action-active");let ye=ve(ae,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ye)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Se=_.getMessages().find(nt=>nt.id===R);Se&&ee.onFeedback&&ee.onFeedback({type:F,messageId:Se.id,message:Se})}}}),Je.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.closest(".persona-approval-bubble");if(!v)return;let R=v.getAttribute("data-message-id");if(!R)return;let F=h.getAttribute("data-approval-action");if(!F)return;let $=F==="approve"?"approved":"denied",D=_.getMessages().find(se=>se.id===R);if(!(D!=null&&D.approval))return;let ae=v.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(Q=>{Q.disabled=!0,Q.style.opacity="0.5",Q.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?_.resolveWebMcpApproval(R,$):_.resolveApproval(D.approval,$)});let Ct=null,Gr=null,Kr={artifacts:[],selectedId:null},Ir=!1,Mt={current:null};Je.addEventListener("click",l=>{var Q,ye,He,Se,nt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.getAttribute("data-download-artifact");if(!v||((He=(ye=(Q=o.features)==null?void 0:Q.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:He.call(ye,{type:"download",artifactId:v}))===!0)return;let F=_.getArtifactById(v),$=F==null?void 0:F.markdown,O=(F==null?void 0:F.title)||"artifact";if(!$){let $e=h.closest("[data-open-artifact]"),ut=$e==null?void 0:$e.closest("[data-message-id]"),st=ut==null?void 0:ut.getAttribute("data-message-id");if(st){let Ee=_.getMessages().find(ze=>ze.id===st);if(Ee!=null&&Ee.rawContent)try{let ze=JSON.parse(Ee.rawContent);$=(Se=ze==null?void 0:ze.props)==null?void 0:Se.markdown,O=((nt=ze==null?void 0:ze.props)==null?void 0:nt.title)||O}catch{}}}if(!$)return;let D=new Blob([$],{type:"text/markdown"}),ae=URL.createObjectURL(D),se=document.createElement("a");se.href=ae,se.download=`${O}.md`,se.click(),URL.revokeObjectURL(ae)}),Je.addEventListener("click",l=>{var F,$,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let v=h.getAttribute("data-open-artifact");!v||((O=($=(F=o.features)==null?void 0:F.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:O.call($,{type:"open",artifactId:v}))===!0||(l.preventDefault(),l.stopPropagation(),Ir=!1,_.selectArtifact(v),Jr())}),Je.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;f.hasAttribute("data-open-artifact")&&(l.preventDefault(),f.click())});let io=Y.composerOverlay,lo=(l,f,h)=>{var O,D,ae,se;let v=f.trim();if(!v||!Mt.current)return;let R=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",F=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:R,answer:v,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?v.split(", "):[v],isFreeText:F,source:h.source},bubbles:!0,composed:!0})),Ln(io,R);let $=Mt.current.getMessages().find(Q=>{var ye;return((ye=Q.toolCall)==null?void 0:ye.id)===R});(ae=$==null?void 0:$.agentMetadata)!=null&&ae.awaitingLocalTool?Mt.current.resolveAskUserQuestion($,(se=h.structured)!=null?se:v):Mt.current.sendMessage(v)},Xr=l=>{var R;let f=Mt.current;if(!f)return;let h=(R=l.getAttribute("data-tool-call-id"))!=null?R:"",v=f.getMessages().find(F=>{var $;return(($=F.toolCall)==null?void 0:$.id)===h});v&&f.persistAskUserQuestionProgress(v,{answers:vi(l,v),currentIndex:ho(l)})},mn=l=>Object.entries(l).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Go=l=>{var R,F,$;if(((F=(R=o.features)==null?void 0:R.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let f=ho(l),h=Ba(l);if(f>=h-1)return;let v=($=Mt.current)==null?void 0:$.getMessages().find(O=>{var D;return((D=O.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});v&&(Ci(l,v,o,f+1),Xr(l))};io.addEventListener("click",l=>{var F,$,O,D,ae,se,Q,ye,He,Se,nt,$e,ut,st;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;let R=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),R==="dismiss"){let Le=(F=v.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Ln(io,Le);let Ee=($=Mt.current)==null?void 0:$.getMessages().find(ze=>{var Qe;return((Qe=ze.toolCall)==null?void 0:Qe.id)===Le});(O=Ee==null?void 0:Ee.agentMetadata)!=null&&O.awaitingLocalTool&&((D=Mt.current)==null||D.markAskUserQuestionResolved(Ee),(ae=Mt.current)==null||ae.resolveAskUserQuestion(Ee,"(dismissed)"));return}if(R==="pick"){let Le=h.getAttribute("data-option-label");if(!Le)return;let Ee=v.getAttribute("data-multi-select")==="true",ze=kn(v);if(ze&&Ee){let Qe=ta(v)[ho(v)],xt=new Set(Array.isArray(Qe)?Qe:[]);xt.has(Le)?xt.delete(Le):xt.add(Le),Pn(v,Array.from(xt)),Xr(v);return}if(ze){Pn(v,Le),Xr(v),Go(v);return}if(Ee){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let xt=v.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=Ql(v).length===0);return}lo(v,Le,{source:"pick",values:[Le]});return}if(R==="submit-multi"){let Le=Ql(v);if(Le.length===0)return;lo(v,Le.join(", "),{source:"multi",values:Le});return}if(R==="open-free-text"){let Le=v.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let Ee=Le.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus()}return}if(R==="focus-free-text"){let Le=v.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(R==="submit-free-text"){let Le=v.querySelector('[data-ask-free-text-input="true"]'),Ee=(se=Le==null?void 0:Le.value)!=null?se:"";if(!Ee.trim())return;if(kn(v)){Pn(v,Ee.trim()),Xr(v),Go(v);return}lo(v,Ee,{source:"free-text"});return}if(R==="next"||R==="back"){if(!Mt.current)return;let Le=(Q=v.getAttribute("data-tool-call-id"))!=null?Q:"",Ee=Mt.current.getMessages().find(Re=>{var Pe;return((Pe=Re.toolCall)==null?void 0:Pe.id)===Le});if(!Ee)return;let ze=v.querySelector('[data-ask-free-text-input="true"]'),Qe=(He=(ye=ze==null?void 0:ze.value)==null?void 0:ye.trim())!=null?He:"";if(Qe){let Re=ta(v)[ho(v)];(typeof Re!="string"||Re!==Qe)&&Pn(v,Qe)}let xt=R==="next"?1:-1,B=ho(v)+xt;Ci(v,Ee,o,B),Xr(v);return}if(R==="submit-all"){if(!Mt.current)return;let Le=(Se=v.getAttribute("data-tool-call-id"))!=null?Se:"",Ee=Mt.current.getMessages().find(Re=>{var Pe;return((Pe=Re.toolCall)==null?void 0:Pe.id)===Le});if(!Ee)return;let ze=v.querySelector('[data-ask-free-text-input="true"]'),Qe=($e=(nt=ze==null?void 0:ze.value)==null?void 0:nt.trim())!=null?$e:"";Qe&&Pn(v,Qe);let xt=vi(v,Ee);Mt.current.persistAskUserQuestionProgress(Ee,{answers:xt,currentIndex:ho(v)});let B=mn(xt);lo(v,B||"(submitted)",{source:"submit-all",structured:xt});return}if(R==="skip"){if(!Mt.current)return;let Le=(ut=v.getAttribute("data-tool-call-id"))!=null?ut:"",Ee=Mt.current.getMessages().find(Pe=>{var fe;return((fe=Pe.toolCall)==null?void 0:fe.id)===Le});if(!Ee)return;let ze=kn(v),Qe=ho(v),xt=Ba(v),B=Qe>=xt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Ln(io,Le),(st=Ee.agentMetadata)!=null&&st.awaitingLocalTool&&(Mt.current.markAskUserQuestionResolved(Ee),Mt.current.resolveAskUserQuestion(Ee,"(dismissed)"));return}Pn(v,"");let Re=v.querySelector('[data-ask-free-text-input="true"]');if(Re&&(Re.value=""),B){let Pe=vi(v,Ee),fe=mn(Pe);lo(v,fe||"(skipped)",{source:"submit-all",structured:Pe});return}Ci(v,Ee,o,Qe+1),Xr(v);return}}),io.addEventListener("keydown",l=>{var F;if(l.key!=="Enter")return;let h=l.target;if(!((F=h.matches)!=null&&F.call(h,'[data-ask-free-text-input="true"]')))return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;l.preventDefault();let R=h.value;if(R.trim()){if(kn(v)){Pn(v,R.trim()),Xr(v),Go(v);return}lo(v,R,{source:"free-text"})}});let gn=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let f=l.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let h=io.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let v=Number(l.key),F=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];F&&(l.preventDefault(),F.click())};document.addEventListener("keydown",gn);let Qr=null,Nt=null,Wr=null,co=null,hn=()=>{};function Ko(){co==null||co(),co=null}let xn=()=>{var $;if(!Qr||!Nt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=(($=e.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Nt.style.removeProperty("position"),Nt.style.removeProperty("left"),Nt.style.removeProperty("top"),Nt.style.removeProperty("bottom"),Nt.style.removeProperty("width"),Nt.style.removeProperty("z-index");return}let v=Qr.firstElementChild;if(!v||v===Nt)return;let R=10;Nt.style.position="absolute",Nt.style.top="0",Nt.style.bottom="0",Nt.style.width=`${R}px`,Nt.style.zIndex="5";let F=v.offsetWidth-R/2;Nt.style.left=`${Math.max(0,F)}px`},Ro=()=>{},Jr=()=>{var h,v,R,F,$;if(!Ct||!xo(o))return;Cl(e,o),wl(e,o),Ro();let l=(F=(R=(v=(h=o.features)==null?void 0:h.artifacts)==null?void 0:v.layout)==null?void 0:R.narrowHostMaxWidth)!=null?F:520,f=be.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l),Ct.update(Kr),Ir?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),($=Ct.backdrop)==null||$.classList.add("persona-hidden")):Kr.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),hn()};if(xo(o)){be.style.position="relative";let l=S("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=S("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(pe),Ct=Vh(o,{onSelect:h=>{var v;return(v=Mt.current)==null?void 0:v.selectArtifact(h)},onDismiss:()=>{Ir=!0,Jr()}}),Ct.element.classList.add("persona-hidden"),Qr=f,f.appendChild(l),f.appendChild(Ct.element),Ct.backdrop&&be.appendChild(Ct.backdrop),be.appendChild(f),hn=()=>{var v,R,F,$;if(!Qr||!Ct)return;if(!(((F=(R=(v=o.features)==null?void 0:v.artifacts)==null?void 0:R.layout)==null?void 0:F.resizable)===!0)){Wr==null||Wr(),Wr=null,Ko(),Nt&&(Nt.remove(),Nt=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Nt){let O=S("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let D=e.ownerDocument,ae=($=D.defaultView)!=null?$:window,se=Q=>{var ut,st;if(!Ct||Q.button!==0||e.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;Q.preventDefault(),Ko();let ye=Q.clientX,He=Ct.element.getBoundingClientRect().width,Se=(st=(ut=o.features)==null?void 0:ut.artifacts)==null?void 0:st.layout,nt=Le=>{let Ee=Qr.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Qe=ze?0:Gh(Qr,ae),xt=ze?0:O.getBoundingClientRect().width||6,B=He-(Le.clientX-ye),Re=Kh(B,Ee,Qe,xt,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);Ct.element.style.width=`${Re}px`,Ct.element.style.maxWidth="none",xn()},$e=()=>{D.removeEventListener("pointermove",nt),D.removeEventListener("pointerup",$e),D.removeEventListener("pointercancel",$e),co=null;try{O.releasePointerCapture(Q.pointerId)}catch{}};co=$e,D.addEventListener("pointermove",nt),D.addEventListener("pointerup",$e),D.addEventListener("pointercancel",$e);try{O.setPointerCapture(Q.pointerId)}catch{}};O.addEventListener("pointerdown",se),Nt=O,Qr.insertBefore(O,Ct.element),Wr=()=>{O.removeEventListener("pointerdown",se)}}if(Nt){let O=Kr.artifacts.length>0&&!Ir;Nt.classList.toggle("persona-hidden",!O),xn()}},Ro=()=>{var ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee,ze,Qe;if(!E||!Ct||((se=(ae=o.launcher)==null?void 0:ae.sidebarMode)!=null?se:!1)||pr(o)&&no(o).reveal==="emerge")return;let v=(Q=e.ownerDocument.defaultView)!=null?Q:window,R=(He=(ye=o.launcher)==null?void 0:ye.mobileFullscreen)!=null?He:!0,F=(nt=(Se=o.launcher)==null?void 0:Se.mobileBreakpoint)!=null?nt:640;if(R&&v.innerWidth<=F||!jh(o,E))return;let $=(st=(ut=($e=o.launcher)==null?void 0:$e.width)!=null?ut:o.launcherWidth)!=null?st:oo,O=(Qe=(ze=(Ee=(Le=o.features)==null?void 0:Le.artifacts)==null?void 0:Ee.layout)==null?void 0:ze.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Kr.artifacts.length>0&&!Ir?(be.style.width=O,be.style.maxWidth=O):(be.style.width=$,be.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Gr=new ResizeObserver(()=>{Jr()}),Gr.observe(be))}else be.appendChild(pe),H()&&Ze&&(Y.peekBanner&&Ze.appendChild(Y.peekBanner),Ze.appendChild(Ne));e.appendChild(_e),Ze&&e.appendChild(Ze);let xe=()=>{var Re,Pe,fe,Ut,Ot,Kt,bt,zt,eo,or,Ye,Rt,cr,go,to,jn,Gn,Ea,ka,Xt,Kn,Mn,Tn,en,Xn,wo,rt,gr;if(H()){be.style.width="100%",be.style.maxWidth="100%";let Vt=(Pe=(Re=o.launcher)==null?void 0:Re.composerBar)!=null?Pe:{},qt=_e.dataset.state==="expanded",ft=(fe=Vt.expandedSize)!=null?fe:"anchored";if(!(qt&&ft!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let St=(Ot=(Ut=o.theme)==null?void 0:Ut.components)==null?void 0:Ot.panel,Tr=Va(o),Br=(Fr,Qn)=>{var ms;return Fr==null||Fr===""?Qn:(ms=Ua(Tr,Fr))!=null?ms:Fr},Uo="1px solid var(--persona-border)",vr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Dr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Br(St==null?void 0:St.border,Uo),pe.style.borderRadius=Br(St==null?void 0:St.borderRadius,Dr),pe.style.boxShadow=Br(St==null?void 0:St.shadow,vr),pe.style.overflow="hidden";return}let l=pr(o),f=(bt=(Kt=o.launcher)==null?void 0:Kt.sidebarMode)!=null?bt:!1,h=l||f||((eo=(zt=o.launcher)==null?void 0:zt.fullHeight)!=null?eo:!1),v=((or=o.launcher)==null?void 0:or.enabled)===!1,R=(Rt=(Ye=o.theme)==null?void 0:Ye.components)==null?void 0:Rt.panel,F=Va(o),$=(Vt,qt)=>{var ft;return Vt==null||Vt===""?qt:(ft=Ua(F,Vt))!=null?ft:Vt},O=(cr=e.ownerDocument.defaultView)!=null?cr:window,D=(to=(go=o.launcher)==null?void 0:go.mobileFullscreen)!=null?to:!0,ae=(Gn=(jn=o.launcher)==null?void 0:jn.mobileBreakpoint)!=null?Gn:640,se=O.innerWidth<=ae,Q=D&&se&&E,ye=(ka=(Ea=o.launcher)==null?void 0:Ea.position)!=null?ka:"bottom-left",He=ye==="bottom-left"||ye==="top-left",Se=(Kn=(Xt=o.launcher)==null?void 0:Xt.zIndex)!=null?Kn:Lr,nt=f||Q?"none":"1px solid var(--persona-border)",$e=Q?"none":f?He?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Q&&($e="none",nt="none");let ut=f||Q?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=$(R==null?void 0:R.border,nt),Le=$(R==null?void 0:R.shadow,$e),Ee=$(R==null?void 0:R.borderRadius,ut),ze=Me.scrollTop;e.style.cssText="",_e.style.cssText="",be.style.cssText="",pe.style.cssText="",Me.style.cssText="",Ne.style.cssText="";let Qe=()=>{var qt;if(ze<=0)return;((qt=Me.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(Me.scrollTop===ze)return;let ft=Me.scrollHeight-Me.clientHeight;ft<=0||(Me.scrollTop=Math.min(ze,ft))})};if(Q){_e.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),_e.style.cssText=`
33
+ `,A.addEventListener("click",()=>{g=b,E.forEach((H,W)=>{let k=W<b;H.classList.toggle("selected",k),H.setAttribute("aria-checked",W===b-1?"true":"false")})}),E.push(A),T.appendChild(A)}p.appendChild(T);let M=null;if(c){let b=document.createElement("div");b.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),b.appendChild(M),p.appendChild(b)}let P=document.createElement("div");P.className="persona-feedback-actions";let y=document.createElement("button");y.type="button",y.className="persona-feedback-btn persona-feedback-btn-skip",y.textContent=i,y.addEventListener("click",()=>{r==null||r(),u.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=s,w.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let b=(M==null?void 0:M.value.trim())||void 0;await t(g,b),u.remove()}catch(b){w.disabled=!1,w.textContent=s,console.error("[CSAT Feedback] Failed to submit:",b)}}),P.appendChild(y),P.appendChild(w),p.appendChild(P),u.appendChild(p),u}function Pl(e){let{onSubmit:t,onDismiss:r,title:o="How likely are you to recommend us?",subtitle:n="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,lowLabel:d="Not likely",highLabel:u="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let p=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,x.appendChild(C);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=n,x.appendChild(T),m.appendChild(x);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=d;let y=document.createElement("span");y.className="persona-feedback-label-high",y.textContent=u,M.appendChild(P),M.appendChild(y);let w=document.createElement("div");w.className="persona-feedback-numbers";let b=[];for(let N=0;N<=10;N++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${N} out of 10`),q.textContent=String(N),q.dataset.rating=String(N),N<=6?q.classList.add("persona-feedback-detractor"):N<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{p=N,b.forEach((Z,me)=>{Z.classList.toggle("selected",me===N),Z.setAttribute("aria-checked",me===N?"true":"false")})}),b.push(q),w.appendChild(q)}E.appendChild(M),E.appendChild(w),m.appendChild(E);let A=null;if(c){let N=document.createElement("div");N.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),N.appendChild(A),m.appendChild(N)}let H=document.createElement("div");H.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=i,W.addEventListener("click",()=>{r==null||r(),g.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=s,k.addEventListener("click",async()=>{if(p===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let N=(A==null?void 0:A.value.trim())||void 0;await t(p,N),g.remove()}catch(N){k.disabled=!1,k.textContent=s,console.error("[NPS Feedback] Failed to submit:",N)}}),H.appendChild(W),H.appendChild(k),m.appendChild(H),g.appendChild(m),g}var Ya="persona-chat-history",Pv=30*1e3,Rv={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Iv(e){var o,n,a;if(!e)return[];let t=[],r=Array.from((o=e.items)!=null?o:[]);for(let s of r){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let c=(n=Rv[i.type])!=null?n:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${c}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let s of Array.from((a=e.files)!=null?a:[]))s.type.startsWith("image/")&&t.push(s);return t}function Rl(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Wv(e){var t,r,o,n,a,s,i,c,d;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(n=(o=e.persist)==null?void 0:o.openState)!=null?n:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(c=(i=e.persist)==null?void 0:i.focusInput)!=null?c:!0},clearOnChatClear:(d=e.clearOnChatClear)!=null?d:!0}:null}function Hv(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Ip=e=>!e||typeof e!="object"?{}:{...e},ox=e=>e.map(t=>({...t,streaming:!1})),nx=(e,t,r)=>{let o=e!=null&&e.markdown?Zn(e.markdown):null,n=Wa(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&n&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),a=>{var d,u,g;let s=(d=a.text)!=null?d:"",i=(u=a.message.rawContent)!=null?u:null;if(t){let p=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});p!==null&&(s=p.text,p.persist||(a.message.__skipPersist=!0),p.resubmit&&!a.streaming&&r&&r())}let c;return e!=null&&e.postprocessMessage?c=e.postprocessMessage({...a,text:s,raw:(g=i!=null?i:a.text)!=null?g:""}):o?c=o(s):c=qo(s),n?n(c):c}};function ax(e){var i,c,d,u;let t=S("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let r=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(c=e==null?void 0:e.iconSize)!=null?c:"48px",n=(d=e==null?void 0:e.iconColor)!=null?d:"rgba(59, 130, 246, 0.6)",a=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,s=ve(r,o,n,a);if(s&&t.appendChild(s),e!=null&&e.label){let g=S("span","persona-drop-overlay-label");g.textContent=e.label,t.appendChild(g)}return t}var Il=(e,t,r)=>{var fu,mu,gu,hu,xu,yu,bu,vu,Cu,wu,Su,Au,Mu,Tu,Eu,ku,Lu,Pu,Ru,Iu,Wu,Hu,Bu,Du,Fu,Nu,Ou,_u,Uu,qu,Vu,$u,zu,ju,Gu,Ku,Xu,Qu,Ju,Yu,Zu,ef,tf,rf,of,nf,af,sf,lf,df;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Ji(t),n=zs.getForInstance(o.plugins);o.components&&dn.registerAll(o.components);let a=Yh(),i=o.persistState===!1?null:(fu=o.storageAdapter)!=null?fu:Al(),c={},d=null,u=!1,g=l=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(l);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:v}=f;return v&&(u=!0),h}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l.then(f=>{let h=f!=null?f:{messages:[],metadata:{}};return g(h)});else{let f=l!=null?l:{messages:[],metadata:{}},h=g(f);h.metadata&&(c=Ip(h.metadata)),(mu=h.messages)!=null&&mu.length&&(o={...o,initialMessages:h.messages}),(gu=h.artifacts)!=null&&gu.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(hu=h.selectedArtifactId)!=null?hu:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=g({messages:[],metadata:{}});(xu=l.messages)!=null&&xu.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>c,m=l=>{var h;c=(h=l({...c}))!=null?h:{},wa()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[js],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ma.message,ma.messageAndClick],T=Gs({parsers:x,handlers:C,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let E=(bu=(yu=o.launcher)==null?void 0:yu.enabled)!=null?bu:!0,M=(Cu=(vu=o.launcher)==null?void 0:vu.autoExpand)!=null?Cu:!1,P=(wu=o.autoFocusInput)!=null?wu:!1,y=M,w=E,b=(Au=(Su=o.layout)==null?void 0:Su.header)==null?void 0:Au.layout,A=!1,H=()=>Dn(o),W=()=>E||H(),k=H()?!1:E?M:!0,N=!1,q=null,Z=()=>{N=!0,q&&clearTimeout(q),q=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},me=nx(o,T,Z),Ke=(Tu=(Mu=o.features)==null?void 0:Mu.showReasoning)!=null?Tu:!0,Ce=(ku=(Eu=o.features)==null?void 0:Eu.showToolCalls)!=null?ku:!0,Ie=(Pu=(Lu=o.features)==null?void 0:Lu.showEventStreamToggle)!=null?Pu:!1,Ue=(Iu=(Ru=o.features)==null?void 0:Ru.scrollToBottom)!=null?Iu:{},Te=(Hu=(Wu=o.features)==null?void 0:Wu.scrollBehavior)!=null?Hu:{},de=`${(Du=typeof o.persistState=="object"?(Bu=o.persistState)==null?void 0:Bu.keyPrefix:void 0)!=null?Du:"persona-"}event-stream`,J=Ie?new Vs(de):null,le=(Ou=(Nu=(Fu=o.features)==null?void 0:Fu.eventStream)==null?void 0:Nu.maxEvents)!=null?Ou:2e3,ge=Ie?new qs(le,J):null,ue=Ie?new $s:null,G=null,ce=!1,Be=null,ne=0;J==null||J.open().then(()=>ge==null?void 0:ge.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ee={onCopy:l=>{var f,h;a.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(v=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",v)}),(h=(f=o.messageActions)==null?void 0:f.onCopy)==null||h.call(f,l)},onFeedback:l=>{var f,h;a.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(v=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",v)}),(h=(f=o.messageActions)==null?void 0:f.onFeedback)==null||h.call(f,l)}},ie=(_u=o.statusIndicator)!=null?_u:{},vt=l=>{var f,h,v,R;return l==="idle"?(f=ie.idleText)!=null?f:kr.idle:l==="connecting"?(h=ie.connectingText)!=null?h:kr.connecting:l==="connected"?(v=ie.connectedText)!=null?v:kr.connected:l==="error"?(R=ie.errorText)!=null?R:kr.error:kr[l]};function Lt(l,f,h,v){if(v==="idle"&&h.idleLink){l.textContent="";let R=document.createElement("a");R.href=h.idleLink,R.target="_blank",R.rel="noopener noreferrer",R.textContent=f,R.style.color="inherit",R.style.textDecoration="none",l.appendChild(R)}else l.textContent=f}let gt=kh({config:o,showClose:W()}),{wrapper:_e,panel:be,pillRoot:Ze}=gt.shell,Y=gt.panelElements,{container:pe,body:Me,messagesWrapper:Je,suggestions:Ge,textarea:ke,sendButton:je,sendButtonWrapper:Cr,composerForm:Wt,statusText:ur,introTitle:Eo,introSubtitle:V,closeButton:j,iconHolder:he,headerTitle:Xe,headerSubtitle:et,header:qe,footer:Ne,actionsRow:Pt,leftActions:Gt,rightActions:Jt}=Y,Pr=Y.setSendButtonMode,z=Y.micButton,Ht=Y.micButtonWrapper,oe=Y.attachmentButton,we=Y.attachmentButtonWrapper,De=Y.attachmentInput,At=Y.attachmentPreviewsContainer;pe.classList.add("persona-relative"),Me.classList.add("persona-relative");let ar=12,sr=()=>{var l;return(l=Ue.label)!=null?l:""},wr=()=>{var l;return(l=Ue.iconName)!=null?l:"arrow-down"},Ft=()=>Ue.enabled!==!1,ot=()=>{var l;return(l=Te.mode)!=null?l:"follow"},Dt=()=>{var l;return(l=Te.anchorTopOffset)!=null?l:16},lt=S("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");lt.type="button",lt.style.display="none",lt.setAttribute("data-persona-scroll-to-bottom","true");let Yt=S("span","persona-flex persona-items-center"),so=S("span",""),Rr=S("span","");Rr.setAttribute("data-persona-scroll-to-bottom-count",""),Rr.style.display="none",lt.append(Yt,so,Rr),pe.appendChild(lt);let ir=S("div","persona-stream-anchor-spacer");ir.setAttribute("aria-hidden","true"),ir.setAttribute("data-persona-anchor-spacer",""),ir.style.flexShrink="0",ir.style.pointerEvents="none",ir.style.height="0px",Me.appendChild(ir);let Ur=()=>{let f=Ne.style.display==="none"?0:Ne.offsetHeight;lt.style.bottom=`${f+ar}px`};Ur();let ko=()=>{let l=!!sr();lt.setAttribute("aria-label",sr()||"Jump to latest"),lt.title=sr(),lt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Yt.innerHTML="";let f=ve(wr(),"14px","currentColor",2);f?(Yt.appendChild(f),Yt.style.display=""):Yt.style.display="none",so.textContent=sr(),so.style.display=l?"":"none"};ko();let yt=null,jr=null,Lo=n.find(l=>l.renderHeader);if(Lo!=null&&Lo.renderHeader){let l=Lo.renderHeader({config:o,defaultRenderer:()=>{let f=ln({config:o,showClose:W()});return pa(pe,f,o),f.header},onClose:()=>I(!1,"user")});if(l){let f=pe.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),qe=l,gt.header.element=l)}}let zo=()=>{var f,h,v,R;if(!ge)return;if(ce=!0,!G&&ge&&(G=qh({buffer:ge,getFullHistory:()=>ge.getAllFromStore(),onClose:()=>yo(),config:o,plugins:n,getThroughput:()=>{var F;return(F=ue==null?void 0:ue.getMetric())!=null?F:{status:"idle"}}})),G&&(Me.style.display="none",(f=Ne.parentNode)==null||f.insertBefore(G.element,Ne),G.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${_r.actionIconColor}`;let F=(R=(v=(h=o.features)==null?void 0:h.eventStream)==null?void 0:v.classNames)==null?void 0:R.toggleButtonActive;F&&F.split(/\s+/).forEach($=>$&&ht.classList.add($))}let l=()=>{if(!ce)return;let F=Date.now();F-ne>=200&&(G==null||G.update(),ne=F),Be=requestAnimationFrame(l)};ne=0,Be=requestAnimationFrame(l),$r(),a.emit("eventStream:opened",{timestamp:Date.now()})},yo=()=>{var l,f,h;if(ce){if(ce=!1,G&&G.element.remove(),Me.style.display="",ht){ht.style.boxShadow="";let v=(h=(f=(l=o.features)==null?void 0:l.eventStream)==null?void 0:f.classNames)==null?void 0:h.toggleButtonActive;v&&v.split(/\s+/).forEach(R=>R&&ht.classList.remove(R))}Be!==null&&(cancelAnimationFrame(Be),Be=null),$r(),a.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(Ie){let l=(qu=(Uu=o.features)==null?void 0:Uu.eventStream)==null?void 0:qu.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");ht=S("button",f),ht.style.width="28px",ht.style.height="28px",ht.style.color=_r.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let h=ve("activity","18px","currentColor",1.5);h&&ht.appendChild(h);let v=Y.clearChatButtonWrapper,R=Y.closeButtonWrapper,F=v||R;F&&F.parentNode===qe?qe.insertBefore(ht,F):qe.appendChild(ht),ht.addEventListener("click",()=>{ce?yo():zo()})}let Nn=l=>{var R,F,$,O,D;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=(R=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?R:l.querySelector(".persona-attachment-previews");if(!h){h=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let ae=l.querySelector("[data-persona-composer-form]");ae!=null&&ae.parentNode?ae.parentNode.insertBefore(h,ae):l.insertBefore(h,l.firstChild)}if(!((F=l.querySelector("[data-persona-composer-attachment-input]"))!=null?F:l.querySelector('input[type="file"]'))){let ae=S("input");ae.type="file",ae.setAttribute("data-persona-composer-attachment-input",""),ae.accept=(($=f.allowedTypes)!=null?$:an).join(","),ae.multiple=((O=f.maxFiles)!=null?O:4)>1,ae.style.display="none",ae.setAttribute("aria-label",(D=f.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(ae)}},Po=n.find(l=>l.renderComposer);if(Po!=null&&Po.renderComposer){let l=o.composer,f=Po.renderComposer({config:o,defaultRenderer:()=>ja({config:o}).footer,onSubmit:h=>{var $;if(!_||_.isStreaming())return;let v=h.trim(),R=($=yt==null?void 0:yt.hasAttachments())!=null?$:!1;if(!v&&!R)return;tt();let F;R&&(F=[],F.push(...yt.getContentParts()),v&&F.push(ks(v))),_.sendMessage(v,{contentParts:F}),R&&yt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{De==null||De.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Vu=o.voiceRecognition)==null?void 0:Vu.enabled)===!0?()=>{jr==null||jr()}:void 0});f&&(gt.replaceComposer(f),Ne=gt.composer.footer)}let On=l=>{let f=(...se)=>{for(let Q of se){let ye=l.querySelector(Q);if(ye)return ye}return null},h=l.querySelector("[data-persona-composer-form]"),v=l.querySelector("[data-persona-composer-input]"),R=l.querySelector("[data-persona-composer-submit]"),F=l.querySelector("[data-persona-composer-mic]"),$=l.querySelector("[data-persona-composer-status]");h&&(Wt=h),v&&(ke=v),R&&(je=R),F&&(z=F,Ht=F.parentElement),$&&(ur=$);let O=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Ge=O);let D=f("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(oe=D,we=D.parentElement),De=f("[data-persona-composer-attachment-input]",'input[type="file"]'),At=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(Pt=ae)};Nn(Ne),On(Ne);let qr=(Ku=($u=o.layout)==null?void 0:$u.contentMaxWidth)!=null?Ku:H()?(Gu=(ju=(zu=o.launcher)==null?void 0:zu.composerBar)==null?void 0:ju.contentMaxWidth)!=null?Gu:"720px":void 0;if(qr&&(Je.style.maxWidth=qr,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%"),qr&&Wt&&!H()&&(Wt.style.maxWidth=qr,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),qr&&Ge&&!H()&&(Ge.style.maxWidth=qr,Ge.style.marginLeft="auto",Ge.style.marginRight="auto"),qr&&At&&!H()&&(At.style.maxWidth=qr,At.style.marginLeft="auto",At.style.marginRight="auto"),(Xu=o.attachments)!=null&&Xu.enabled&&De&&At){yt=la.fromConfig(o.attachments),yt.setPreviewsContainer(At),De.addEventListener("change",h=>{let v=h.target;yt==null||yt.handleFileSelect(v.files),v.value=""});let l=o.attachments.dropOverlay,f=ax(l);pe.appendChild(f)}(()=>{var v,R;let l=(R=(v=o.layout)==null?void 0:v.slots)!=null?R:{},f=F=>{switch(F){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Je;case"footer-top":return Ge;case"composer":return Wt;case"footer-bottom":return ur;default:return null}},h=(F,$)=>{var O;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")qe.insertBefore($,qe.firstChild);else if(F==="header-right")qe.appendChild($);else{let D=qe.querySelector(".persona-flex-col");D?(O=D.parentNode)==null||O.insertBefore($,D.nextSibling):qe.appendChild($)}break;case"body-top":{let D=Me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith($):Me.insertBefore($,Me.firstChild);break}case"body-bottom":Me.appendChild($);break;case"footer-top":Ge.replaceWith($);break;case"footer-bottom":ur.replaceWith($);break;default:break}};for(let[F,$]of Object.entries(l))if($)try{let O=$({config:o,defaultContent:()=>f(F)});O&&h(F,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,O)}})();let cn=l=>{var $,O;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let v=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let R=v.getAttribute("data-message-id");if(!R)return;let F=h.getAttribute("data-bubble-type");if(F==="reasoning")Ka.has(R)?Ka.delete(R):Ka.add(R),Ih(R,v);else if(F==="tool")Xa.has(R)?Xa.delete(R):Xa.add(R),Wh(R,v,o);else if(F==="approval"){let D=o.approval!==!1?o.approval:void 0,ae=(($=D==null?void 0:D.detailsDisplay)!=null?$:"collapsed")==="expanded",se=(O=bl.get(R))!=null?O:ae;bl.set(R,!se),Fh(R,v,o)}Bo.delete(R)};Je.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))}),Je.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))});let jo=new Map,pn=null,un="idle",_n={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Un=(l,f)=>{let{icon:h,label:v}=_n[f];l.setAttribute("aria-label",v),l.title=v,l.setAttribute("aria-pressed",f==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",f!=="idle"),l.classList.toggle("persona-message-action-loading",f==="loading");let R=ve(h,14,"currentColor",2);R&&(l.innerHTML="",l.appendChild(R))},fn=()=>{Je.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{var F;let h=f.closest("[data-actions-for]"),v=(F=h==null?void 0:h.getAttribute("data-actions-for"))!=null?F:null;Un(f,v&&v===pn?un:"idle")})};Je.addEventListener("click",l=>{var $;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.closest("[data-actions-for]");if(!v)return;let R=v.getAttribute("data-actions-for");if(!R)return;let F=h.getAttribute("data-action");if(F==="copy"){let D=_.getMessages().find(ae=>ae.id===R);if(D&&ee.onCopy){let ae=D.content||"";navigator.clipboard.writeText(ae).then(()=>{h.classList.add("persona-message-action-success");let se=ve("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Q=ve("copy",14,"currentColor",2);Q&&(h.innerHTML="",h.appendChild(Q))},2e3)}).catch(se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",se)}),ee.onCopy(D)}}else if(F==="read-aloud")_.toggleReadAloud(R);else if(F==="upvote"||F==="downvote"){let D=(($=jo.get(R))!=null?$:null)===F,ae=F==="upvote"?"thumbs-up":"thumbs-down";if(D){jo.delete(R),h.classList.remove("persona-message-action-active");let se=ve(ae,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=F==="upvote"?"downvote":"upvote",Q=v.querySelector(`[data-action="${se}"]`);if(Q){Q.classList.remove("persona-message-action-active");let $e=ve(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);$e&&(Q.innerHTML="",Q.appendChild($e))}jo.set(R,F),h.classList.add("persona-message-action-active");let ye=ve(ae,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ye)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Se=_.getMessages().find(nt=>nt.id===R);Se&&ee.onFeedback&&ee.onFeedback({type:F,messageId:Se.id,message:Se})}}}),Je.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.closest(".persona-approval-bubble");if(!v)return;let R=v.getAttribute("data-message-id");if(!R)return;let F=h.getAttribute("data-approval-action");if(!F)return;let $=F==="approve"?"approved":"denied",D=_.getMessages().find(se=>se.id===R);if(!(D!=null&&D.approval))return;let ae=v.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(Q=>{Q.disabled=!0,Q.style.opacity="0.5",Q.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?_.resolveWebMcpApproval(R,$):_.resolveApproval(D.approval,$)});let Ct=null,Gr=null,Kr={artifacts:[],selectedId:null},Ir=!1,Mt={current:null};Je.addEventListener("click",l=>{var Q,ye,He,Se,nt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let v=h.getAttribute("data-download-artifact");if(!v||((He=(ye=(Q=o.features)==null?void 0:Q.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:He.call(ye,{type:"download",artifactId:v}))===!0)return;let F=_.getArtifactById(v),$=F==null?void 0:F.markdown,O=(F==null?void 0:F.title)||"artifact";if(!$){let $e=h.closest("[data-open-artifact]"),ut=$e==null?void 0:$e.closest("[data-message-id]"),st=ut==null?void 0:ut.getAttribute("data-message-id");if(st){let Ee=_.getMessages().find(ze=>ze.id===st);if(Ee!=null&&Ee.rawContent)try{let ze=JSON.parse(Ee.rawContent);$=(Se=ze==null?void 0:ze.props)==null?void 0:Se.markdown,O=((nt=ze==null?void 0:ze.props)==null?void 0:nt.title)||O}catch{}}}if(!$)return;let D=new Blob([$],{type:"text/markdown"}),ae=URL.createObjectURL(D),se=document.createElement("a");se.href=ae,se.download=`${O}.md`,se.click(),URL.revokeObjectURL(ae)}),Je.addEventListener("click",l=>{var F,$,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let v=h.getAttribute("data-open-artifact");!v||((O=($=(F=o.features)==null?void 0:F.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:O.call($,{type:"open",artifactId:v}))===!0||(l.preventDefault(),l.stopPropagation(),Ir=!1,_.selectArtifact(v),Jr())}),Je.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;f.hasAttribute("data-open-artifact")&&(l.preventDefault(),f.click())});let io=Y.composerOverlay,lo=(l,f,h)=>{var O,D,ae,se;let v=f.trim();if(!v||!Mt.current)return;let R=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",F=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:R,answer:v,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?v.split(", "):[v],isFreeText:F,source:h.source},bubbles:!0,composed:!0})),Ln(io,R);let $=Mt.current.getMessages().find(Q=>{var ye;return((ye=Q.toolCall)==null?void 0:ye.id)===R});(ae=$==null?void 0:$.agentMetadata)!=null&&ae.awaitingLocalTool?Mt.current.resolveAskUserQuestion($,(se=h.structured)!=null?se:v):Mt.current.sendMessage(v)},Xr=l=>{var R;let f=Mt.current;if(!f)return;let h=(R=l.getAttribute("data-tool-call-id"))!=null?R:"",v=f.getMessages().find(F=>{var $;return(($=F.toolCall)==null?void 0:$.id)===h});v&&f.persistAskUserQuestionProgress(v,{answers:Ci(l,v),currentIndex:ho(l)})},mn=l=>Object.entries(l).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Go=l=>{var R,F,$;if(((F=(R=o.features)==null?void 0:R.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let f=ho(l),h=Da(l);if(f>=h-1)return;let v=($=Mt.current)==null?void 0:$.getMessages().find(O=>{var D;return((D=O.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});v&&(wi(l,v,o,f+1),Xr(l))};io.addEventListener("click",l=>{var F,$,O,D,ae,se,Q,ye,He,Se,nt,$e,ut,st;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;let R=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),R==="dismiss"){let Le=(F=v.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Ln(io,Le);let Ee=($=Mt.current)==null?void 0:$.getMessages().find(ze=>{var Qe;return((Qe=ze.toolCall)==null?void 0:Qe.id)===Le});(O=Ee==null?void 0:Ee.agentMetadata)!=null&&O.awaitingLocalTool&&((D=Mt.current)==null||D.markAskUserQuestionResolved(Ee),(ae=Mt.current)==null||ae.resolveAskUserQuestion(Ee,"(dismissed)"));return}if(R==="pick"){let Le=h.getAttribute("data-option-label");if(!Le)return;let Ee=v.getAttribute("data-multi-select")==="true",ze=kn(v);if(ze&&Ee){let Qe=ta(v)[ho(v)],xt=new Set(Array.isArray(Qe)?Qe:[]);xt.has(Le)?xt.delete(Le):xt.add(Le),Pn(v,Array.from(xt)),Xr(v);return}if(ze){Pn(v,Le),Xr(v),Go(v);return}if(Ee){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let xt=v.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=Jl(v).length===0);return}lo(v,Le,{source:"pick",values:[Le]});return}if(R==="submit-multi"){let Le=Jl(v);if(Le.length===0)return;lo(v,Le.join(", "),{source:"multi",values:Le});return}if(R==="open-free-text"){let Le=v.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let Ee=Le.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus()}return}if(R==="focus-free-text"){let Le=v.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(R==="submit-free-text"){let Le=v.querySelector('[data-ask-free-text-input="true"]'),Ee=(se=Le==null?void 0:Le.value)!=null?se:"";if(!Ee.trim())return;if(kn(v)){Pn(v,Ee.trim()),Xr(v),Go(v);return}lo(v,Ee,{source:"free-text"});return}if(R==="next"||R==="back"){if(!Mt.current)return;let Le=(Q=v.getAttribute("data-tool-call-id"))!=null?Q:"",Ee=Mt.current.getMessages().find(Re=>{var Pe;return((Pe=Re.toolCall)==null?void 0:Pe.id)===Le});if(!Ee)return;let ze=v.querySelector('[data-ask-free-text-input="true"]'),Qe=(He=(ye=ze==null?void 0:ze.value)==null?void 0:ye.trim())!=null?He:"";if(Qe){let Re=ta(v)[ho(v)];(typeof Re!="string"||Re!==Qe)&&Pn(v,Qe)}let xt=R==="next"?1:-1,B=ho(v)+xt;wi(v,Ee,o,B),Xr(v);return}if(R==="submit-all"){if(!Mt.current)return;let Le=(Se=v.getAttribute("data-tool-call-id"))!=null?Se:"",Ee=Mt.current.getMessages().find(Re=>{var Pe;return((Pe=Re.toolCall)==null?void 0:Pe.id)===Le});if(!Ee)return;let ze=v.querySelector('[data-ask-free-text-input="true"]'),Qe=($e=(nt=ze==null?void 0:ze.value)==null?void 0:nt.trim())!=null?$e:"";Qe&&Pn(v,Qe);let xt=Ci(v,Ee);Mt.current.persistAskUserQuestionProgress(Ee,{answers:xt,currentIndex:ho(v)});let B=mn(xt);lo(v,B||"(submitted)",{source:"submit-all",structured:xt});return}if(R==="skip"){if(!Mt.current)return;let Le=(ut=v.getAttribute("data-tool-call-id"))!=null?ut:"",Ee=Mt.current.getMessages().find(Pe=>{var fe;return((fe=Pe.toolCall)==null?void 0:fe.id)===Le});if(!Ee)return;let ze=kn(v),Qe=ho(v),xt=Da(v),B=Qe>=xt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Ln(io,Le),(st=Ee.agentMetadata)!=null&&st.awaitingLocalTool&&(Mt.current.markAskUserQuestionResolved(Ee),Mt.current.resolveAskUserQuestion(Ee,"(dismissed)"));return}Pn(v,"");let Re=v.querySelector('[data-ask-free-text-input="true"]');if(Re&&(Re.value=""),B){let Pe=Ci(v,Ee),fe=mn(Pe);lo(v,fe||"(skipped)",{source:"submit-all",structured:Pe});return}wi(v,Ee,o,Qe+1),Xr(v);return}}),io.addEventListener("keydown",l=>{var F;if(l.key!=="Enter")return;let h=l.target;if(!((F=h.matches)!=null&&F.call(h,'[data-ask-free-text-input="true"]')))return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;l.preventDefault();let R=h.value;if(R.trim()){if(kn(v)){Pn(v,R.trim()),Xr(v),Go(v);return}lo(v,R,{source:"free-text"})}});let gn=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let f=l.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let h=io.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let v=Number(l.key),F=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];F&&(l.preventDefault(),F.click())};document.addEventListener("keydown",gn);let Qr=null,Nt=null,Wr=null,co=null,hn=()=>{};function Ko(){co==null||co(),co=null}let xn=()=>{var $;if(!Qr||!Nt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=(($=e.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Nt.style.removeProperty("position"),Nt.style.removeProperty("left"),Nt.style.removeProperty("top"),Nt.style.removeProperty("bottom"),Nt.style.removeProperty("width"),Nt.style.removeProperty("z-index");return}let v=Qr.firstElementChild;if(!v||v===Nt)return;let R=10;Nt.style.position="absolute",Nt.style.top="0",Nt.style.bottom="0",Nt.style.width=`${R}px`,Nt.style.zIndex="5";let F=v.offsetWidth-R/2;Nt.style.left=`${Math.max(0,F)}px`},Ro=()=>{},Jr=()=>{var h,v,R,F,$;if(!Ct||!xo(o))return;wl(e,o),Sl(e,o),Ro();let l=(F=(R=(v=(h=o.features)==null?void 0:h.artifacts)==null?void 0:v.layout)==null?void 0:R.narrowHostMaxWidth)!=null?F:520,f=be.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l),Ct.update(Kr),Ir?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),($=Ct.backdrop)==null||$.classList.add("persona-hidden")):Kr.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),hn()};if(xo(o)){be.style.position="relative";let l=S("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=S("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(pe),Ct=zh(o,{onSelect:h=>{var v;return(v=Mt.current)==null?void 0:v.selectArtifact(h)},onDismiss:()=>{Ir=!0,Jr()}}),Ct.element.classList.add("persona-hidden"),Qr=f,f.appendChild(l),f.appendChild(Ct.element),Ct.backdrop&&be.appendChild(Ct.backdrop),be.appendChild(f),hn=()=>{var v,R,F,$;if(!Qr||!Ct)return;if(!(((F=(R=(v=o.features)==null?void 0:v.artifacts)==null?void 0:R.layout)==null?void 0:F.resizable)===!0)){Wr==null||Wr(),Wr=null,Ko(),Nt&&(Nt.remove(),Nt=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Nt){let O=S("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let D=e.ownerDocument,ae=($=D.defaultView)!=null?$:window,se=Q=>{var ut,st;if(!Ct||Q.button!==0||e.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;Q.preventDefault(),Ko();let ye=Q.clientX,He=Ct.element.getBoundingClientRect().width,Se=(st=(ut=o.features)==null?void 0:ut.artifacts)==null?void 0:st.layout,nt=Le=>{let Ee=Qr.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Qe=ze?0:Xh(Qr,ae),xt=ze?0:O.getBoundingClientRect().width||6,B=He-(Le.clientX-ye),Re=Qh(B,Ee,Qe,xt,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);Ct.element.style.width=`${Re}px`,Ct.element.style.maxWidth="none",xn()},$e=()=>{D.removeEventListener("pointermove",nt),D.removeEventListener("pointerup",$e),D.removeEventListener("pointercancel",$e),co=null;try{O.releasePointerCapture(Q.pointerId)}catch{}};co=$e,D.addEventListener("pointermove",nt),D.addEventListener("pointerup",$e),D.addEventListener("pointercancel",$e);try{O.setPointerCapture(Q.pointerId)}catch{}};O.addEventListener("pointerdown",se),Nt=O,Qr.insertBefore(O,Ct.element),Wr=()=>{O.removeEventListener("pointerdown",se)}}if(Nt){let O=Kr.artifacts.length>0&&!Ir;Nt.classList.toggle("persona-hidden",!O),xn()}},Ro=()=>{var ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee,ze,Qe;if(!E||!Ct||((se=(ae=o.launcher)==null?void 0:ae.sidebarMode)!=null?se:!1)||pr(o)&&no(o).reveal==="emerge")return;let v=(Q=e.ownerDocument.defaultView)!=null?Q:window,R=(He=(ye=o.launcher)==null?void 0:ye.mobileFullscreen)!=null?He:!0,F=(nt=(Se=o.launcher)==null?void 0:Se.mobileBreakpoint)!=null?nt:640;if(R&&v.innerWidth<=F||!Kh(o,E))return;let $=(st=(ut=($e=o.launcher)==null?void 0:$e.width)!=null?ut:o.launcherWidth)!=null?st:oo,O=(Qe=(ze=(Ee=(Le=o.features)==null?void 0:Le.artifacts)==null?void 0:Ee.layout)==null?void 0:ze.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Kr.artifacts.length>0&&!Ir?(be.style.width=O,be.style.maxWidth=O):(be.style.width=$,be.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Gr=new ResizeObserver(()=>{Jr()}),Gr.observe(be))}else be.appendChild(pe),H()&&Ze&&(Y.peekBanner&&Ze.appendChild(Y.peekBanner),Ze.appendChild(Ne));e.appendChild(_e),Ze&&e.appendChild(Ze);let xe=()=>{var Re,Pe,fe,Ut,Ot,Kt,bt,zt,eo,or,Ye,Rt,cr,go,to,jn,Gn,ka,La,Xt,Kn,Mn,Tn,en,Xn,wo,rt,gr;if(H()){be.style.width="100%",be.style.maxWidth="100%";let Vt=(Pe=(Re=o.launcher)==null?void 0:Re.composerBar)!=null?Pe:{},qt=_e.dataset.state==="expanded",ft=(fe=Vt.expandedSize)!=null?fe:"anchored";if(!(qt&&ft!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let St=(Ot=(Ut=o.theme)==null?void 0:Ut.components)==null?void 0:Ot.panel,Tr=$a(o),Br=(Fr,Qn)=>{var gs;return Fr==null||Fr===""?Qn:(gs=qa(Tr,Fr))!=null?gs:Fr},Uo="1px solid var(--persona-border)",vr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Dr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Br(St==null?void 0:St.border,Uo),pe.style.borderRadius=Br(St==null?void 0:St.borderRadius,Dr),pe.style.boxShadow=Br(St==null?void 0:St.shadow,vr),pe.style.overflow="hidden";return}let l=pr(o),f=(bt=(Kt=o.launcher)==null?void 0:Kt.sidebarMode)!=null?bt:!1,h=l||f||((eo=(zt=o.launcher)==null?void 0:zt.fullHeight)!=null?eo:!1),v=((or=o.launcher)==null?void 0:or.enabled)===!1,R=(Rt=(Ye=o.theme)==null?void 0:Ye.components)==null?void 0:Rt.panel,F=$a(o),$=(Vt,qt)=>{var ft;return Vt==null||Vt===""?qt:(ft=qa(F,Vt))!=null?ft:Vt},O=(cr=e.ownerDocument.defaultView)!=null?cr:window,D=(to=(go=o.launcher)==null?void 0:go.mobileFullscreen)!=null?to:!0,ae=(Gn=(jn=o.launcher)==null?void 0:jn.mobileBreakpoint)!=null?Gn:640,se=O.innerWidth<=ae,Q=D&&se&&E,ye=(La=(ka=o.launcher)==null?void 0:ka.position)!=null?La:"bottom-left",He=ye==="bottom-left"||ye==="top-left",Se=(Kn=(Xt=o.launcher)==null?void 0:Xt.zIndex)!=null?Kn:Lr,nt=f||Q?"none":"1px solid var(--persona-border)",$e=Q?"none":f?He?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Q&&($e="none",nt="none");let ut=f||Q?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=$(R==null?void 0:R.border,nt),Le=$(R==null?void 0:R.shadow,$e),Ee=$(R==null?void 0:R.borderRadius,ut),ze=Me.scrollTop;e.style.cssText="",_e.style.cssText="",be.style.cssText="",pe.style.cssText="",Me.style.cssText="",Ne.style.cssText="";let Qe=()=>{var qt;if(ze<=0)return;((qt=Me.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(Me.scrollTop===ze)return;let ft=Me.scrollHeight-Me.clientHeight;ft<=0||(Me.scrollTop=Math.min(ze,ft))})};if(Q){_e.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),_e.style.cssText=`
34
34
  position: fixed !important;
35
35
  inset: 0 !important;
36
36
  width: 100% !important;
@@ -107,23 +107,23 @@ _Details: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]
107
107
  flex-shrink: 0 !important;
108
108
  border-top: none !important;
109
109
  padding: 8px 16px 12px 16px !important;
110
- `}if(!v&&!l){let Vt="max-height: -moz-available !important; max-height: stretch !important;",qt=f?"":"padding-top: 1.25em !important;",ft=f?"":`z-index: ${(gr=(rt=o.launcher)==null?void 0:rt.zIndex)!=null?gr:Lr} !important;`;_e.style.cssText+=Vt+qt+ft}Qe()};xe(),Wn(e,o),Cl(e,o),wl(e,o);let dt=[];dt.push(()=>{document.removeEventListener("keydown",gn)});let tr=null,fr=null;dt.push(()=>{tr==null||tr(),tr=null,fr==null||fr(),fr=null}),Gr&&dt.push(()=>{Gr==null||Gr.disconnect(),Gr=null}),dt.push(()=>{Wr==null||Wr(),Wr=null,Ko(),Nt&&(Nt.remove(),Nt=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Ie&&dt.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),G==null||G.destroy(),G=null,ge==null||ge.destroy(),ge=null,J=null});let Io=null,Za=()=>{Io&&(Io(),Io=null),o.colorScheme==="auto"&&(Io=Zi(()=>{Wn(e,o)}))};Za(),dt.push(()=>{Io&&(Io(),Io=null)});let Xo=(Xu=o.features)==null?void 0:Xu.streamAnimation;if(Xo!=null&&Xo.type&&Xo.type!=="none"){let l=Bs(Xo.type,Xo.plugins);l&&(pp(l,e),dt.push(()=>vh(e)))}let qn=Dh(Ge),Wo=null,_,ga=l=>{var v,R;if(!_)return;let f=l!=null?l:_.getMessages(),h=((R=(v=o.features)==null?void 0:v.suggestReplies)==null?void 0:R.enabled)!==!1?Si(f):null;h?qn.render(h,_,ke,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(F=>F.role==="user")?qn.render([],_,ke,f):qn.render(o.suggestionChips,_,ke,f,o.suggestionChipsConfig)},Ho=!1,Bo=ph(),Qo=new Map,Do=new Map,bo=new Map,ha=0,Xs=Ra()!==null,Yr=rl(),Zr=0,vo=null,Co=!1,Vn=!1,Jo=0,Mr=null,Fo=null,xa=!1,$n=!1,ya=null,Qs=4,ba=24,Js=80,va=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},es=(Ju=(Qu=o.voiceRecognition)==null?void 0:Qu.autoResume)!=null?Ju:!1,po=l=>{a.emit("voice:state",{active:mt.active,source:l,timestamp:Date.now()})},Vr=()=>{m(l=>({...l,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},Ys=()=>{var v,R;if(((v=o.voiceRecognition)==null?void 0:v.enabled)===!1)return;let l=Rp(c.voiceState),f=!!l.active,h=Number((R=l.timestamp)!=null?R:0);mt.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-h<Lv&&setTimeout(()=>{var F,$;mt.active||(mt.manuallyDeactivated=!1,(($=(F=o.voiceRecognition)==null?void 0:F.provider)==null?void 0:$.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("restore"),_.isVoiceActive()&&Ma()}):li("restore"))},1e3)},Zs=()=>_?tx(_.getMessages()).filter(l=>!l.__skipPersist):[];function Ca(l){if(!(i!=null&&i.save))return;let h={messages:l?tx(l):_?Zs():[],metadata:c,artifacts:Kr.artifacts,selectedArtifactId:Kr.selectedId};try{let v=i.save(h);v instanceof Promise&&v.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",v)}}let Yo=null,ts=()=>_e.querySelector("#persona-scroll-container")||Me,yn=()=>{Yo!==null&&(cancelAnimationFrame(Yo),Yo=null),Co=!1},rs=()=>{vo!==null&&(cancelAnimationFrame(vo),vo=null),Vn=!1,yn()},os=()=>{Jo>0?(Rr.textContent=String(Jo),Rr.style.display="",lt.setAttribute("aria-label",`${sr()||"Jump to latest"} (${Jo} new)`)):(Rr.textContent="",Rr.style.display="none",lt.setAttribute("aria-label",sr()||"Jump to latest"))},ns=()=>{Jo!==0&&(Jo=0,os())},as=()=>ot()==="follow"?!Yr.isFollowing():!la(Me,ba),$r=()=>{if(!Ft()||ce){lt.parentNode&&lt.remove(),lt.style.display="none";return}lt.parentNode!==pe&&pe.appendChild(lt),Ur();let f=sn(Me)>0&&as();f||ns(),lt.style.display=f?"":"none"},wa=()=>{Yr.pause()&&(rs(),$r())},No=()=>{Yr.resume(),ns(),$r()},Oo=(l=!1)=>{ot()==="follow"&&Yr.isFollowing()&&(!l&&!Ho||(vo!==null&&(cancelAnimationFrame(vo),vo=null),Vn=!0,vo=requestAnimationFrame(()=>{vo=null,Vn=!1,Yr.isFollowing()&&ei(ts(),l?220:140)})))},ss=(l,f,h,v=()=>!0)=>{let R=l.scrollTop,F=f(),$=F-R;yn();let O=performance.now();Co=!0;let D=se=>1-Math.pow(1-se,3),ae=se=>{if(!v()){yn();return}let Q=f();Q!==F&&(F=Q,$=F-R);let ye=se-O,He=Math.min(ye/h,1),Se=D(He),nt=R+$*Se;l.scrollTop=nt,Zr=l.scrollTop,He<1?Yo=requestAnimationFrame(ae):(l.scrollTop=F,Zr=l.scrollTop,Yo=null,Co=!1)};Yo=requestAnimationFrame(ae)},ei=(l,f=500)=>{let h=sn(l)-l.scrollTop;if(Math.abs(h)<1){Zr=l.scrollTop;return}if(Math.abs(h)>=Js){yn(),Co=!0,l.scrollTop=sn(l),Zr=l.scrollTop,Co=!1;return}ss(l,()=>sn(l),f,()=>Yr.isFollowing())},is=()=>{let l=ts();Co=!0,l.scrollTop=sn(l),Zr=l.scrollTop,Co=!1,$r()},ls=l=>{ir.style.height=`${Math.max(0,Math.round(l))}px`,Mr&&(Mr.spacerHeight=Math.max(0,l))},zn=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null),yn(),Mr=null,ir.style.height="0px"},ti=l=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=requestAnimationFrame(()=>{var ae;Fo=null;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Me.querySelector(`[data-message-id="${f}"]`);if(!h)return;let v=0,R=h;for(;R&&R!==Me;)v+=R.offsetTop,R=R.offsetParent;let F=(ae=Mr==null?void 0:Mr.spacerHeight)!=null?ae:0,$=Me.scrollHeight-F,{targetScrollTop:O,spacerHeight:D}=hh({anchorOffsetTop:v,topOffset:Dt(),viewportHeight:Me.clientHeight,contentHeight:$});Mr={initialSpacerHeight:D,contentHeightAtAnchor:$,spacerHeight:D},ls(D),ss(Me,()=>O,220)})},ri=()=>{if(ot()==="follow"){if(!Yr.isFollowing()||la(Me,1))return;Oo(!Ho);return}if(Mr&&Mr.initialSpacerHeight>0){let l=Me.scrollHeight-Mr.spacerHeight,f=xh({initialSpacerHeight:Mr.initialSpacerHeight,contentHeightAtAnchor:Mr.contentHeightAtAnchor,currentContentHeight:l});f!==Mr.spacerHeight&&ls(f)}$r()},oi=l=>{let f=ot();f==="follow"?(No(),Oo(!0)):f==="anchor-top"&&ti(l)},ni=l=>{let f=new Map;l.forEach(h=>{let v=va.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!v&&h.role==="assistant"&&(a.emit("assistant:message",h),!$n&&ot()!=="anchor-top"&&as()&&(Jo+=1,os(),$r())),h.role==="assistant"&&(v!=null&&v.streaming)&&h.streaming===!1&&a.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(v?h.approval.status!=="pending"&&a.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):a.emit("approval:requested",{approval:h.approval,message:h}))}),va.clear(),f.forEach((h,v)=>{va.set(v,h)})},ai=(l,f,h)=>{var st,Le,Ee,ze,Qe,xt;let v=document.createElement("div"),F=(()=>{var Re;let B=n.find(Pe=>Pe.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Re=o.loadingIndicator)!=null&&Re.render)return o.loadingIndicator.render})(),$=(B,Re)=>Re==null?!1:typeof Re=="string"?(B.textContent=Re,!0):(B.appendChild(Re),!0),O=new Set,D=new Set,ae=n.some(B=>B.renderAskUserQuestion),se=[],Q=[],ye=o.enableComponentStreaming!==!1,He=n.some(B=>B.renderApproval)&&o.approval!==!1,Se=[];if(f.forEach(B=>{var Ye,Rt,cr,go,to,jn,Gn,Ea,ka,Xt,Kn,Mn,Tn,en,Xn,wo;O.add(B.id);let Re=ae&&rn(B),Pe=He&&B.variant==="approval"&&!!B.approval,fe=!Re&&B.role==="assistant"&&!B.variant&&ye&&Tl(B);if(!Pe&&bo.has(B.id)){let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),bo.delete(B.id)}if(!fe&&Do.has(B.id)){let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),Do.delete(B.id)}let Ut=rn(B)?`:${(Ye=B.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Rt=B.agentMetadata)!=null&&Rt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=ch(B,ha)+Ut,Kt=Re||Pe||fe?null:uh(Bo,B.id,Ot);if(Kt){v.appendChild(Kt.cloneNode(!0)),rn(B)&&((cr=B.toolCall)!=null&&cr.id)&&((go=B.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((to=B.agentMetadata)!=null&&to.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Da(B,o,Y.composerOverlay));return}let bt=null,zt=n.find(rt=>!!(B.variant==="reasoning"&&rt.renderReasoning||B.variant==="tool"&&rt.renderToolCall||!B.variant&&rt.renderMessage)),eo=(jn=o.layout)==null?void 0:jn.messages;if(rn(B)&&((Gn=B.agentMetadata)==null?void 0:Gn.askUserQuestionAnswered)===!0){Qo.delete(B.id);let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(Ss(B)&&((ka=(Ea=o.features)==null?void 0:Ea.suggestReplies)==null?void 0:ka.enabled)!==!1)return;if(rn(B)&&((Kn=(Xt=o.features)==null?void 0:Xt.askUserQuestion)==null?void 0:Kn.enabled)!==!1){let rt=n.find(gr=>typeof gr.renderAskUserQuestion=="function");if(rt&&Mt.current){let gr=Qo.get(B.id),Vt=gr!==Ot,qt=null;if(Vt){let{payload:St,complete:Tr}=on(B),Br=B.id,Uo=()=>{var vr;return(vr=Mt.current)==null?void 0:vr.getMessages().find(Dr=>Dr.id===Br)};qt=rt.renderAskUserQuestion({message:B,payload:St,complete:Tr,resolve:vr=>{var Fr;let Dr=Uo();Dr&&((Fr=Mt.current)==null||Fr.resolveAskUserQuestion(Dr,vr))},dismiss:()=>{var Dr,Fr,Qn;let vr=Uo();(Dr=vr==null?void 0:vr.agentMetadata)!=null&&Dr.awaitingLocalTool&&((Fr=Mt.current)==null||Fr.markAskUserQuestionResolved(vr),(Qn=Mt.current)==null||Qn.resolveAskUserQuestion(vr,"(dismissed)"))},config:o})}let ft=gr!=null;if(Vt&&qt===null&&!ft){((Mn=B.agentMetadata)==null?void 0:Mn.awaitingLocalTool)===!0&&!((Tn=B.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Da(B,o,Y.composerOverlay));return}let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-ask-plugin-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),v.appendChild(Qt),se.push({messageId:B.id,fingerprint:Ot,bubble:qt});return}else{((en=B.agentMetadata)==null?void 0:en.awaitingLocalTool)===!0&&!((Xn=B.agentMetadata)!=null&&Xn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Da(B,o,Y.composerOverlay));return}}else if(Pe){let rt=n.find(ft=>typeof ft.renderApproval=="function"),Vt=bo.get(B.id)!==Ot,qt=null;if(Vt&&(rt!=null&&rt.renderApproval)){let ft=B.id,Qt=(St,Tr)=>{var Uo,vr,Dr;let Br=(Uo=Mt.current)==null?void 0:Uo.getMessages().find(Fr=>Fr.id===ft);Br!=null&&Br.approval&&(Br.approval.toolType==="webmcp"?(vr=Mt.current)==null||vr.resolveWebMcpApproval(Br.id,St):(Dr=Mt.current)==null||Dr.resolveApproval(Br.approval,St,Tr))};qt=rt.renderApproval({message:B,defaultRenderer:()=>bl(B,o),config:o,approve:St=>Qt("approved",St),deny:St=>Qt("denied",St)})}if(Vt&&qt===null){let ft=l.querySelector(`#wrapper-${B.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),bo.delete(B.id),bt=bl(B,o)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${B.id}`,ft.setAttribute("data-wrapper-id",B.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),v.appendChild(ft),Se.push({messageId:B.id,fingerprint:Ot,bubble:qt});return}}else if(zt)if(B.variant==="reasoning"&&B.reasoning&&zt.renderReasoning){if(!Ke)return;bt=zt.renderReasoning({message:B,defaultRenderer:()=>Sp(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&zt.renderToolCall){if(!Ce)return;bt=zt.renderToolCall({message:B,defaultRenderer:()=>Ap(B,o),config:o})}else zt.renderMessage&&(bt=zt.renderMessage({message:B,defaultRenderer:()=>{let rt=ja(B,h,eo,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o});return B.role!=="user"&&kp(rt,B,o,_),rt},config:o}));if(!bt&&fe){let rt=El(B);if(rt){let gr=Do.get(B.id),Vt=gr!==Ot,qt=o.wrapComponentDirectiveInBubble!==!1,ft=null;if(Vt){let Qt=Ml(rt,{config:o,message:B,transform:h});if(Qt)if(qt){let St=document.createElement("div");if(St.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),St.id=`bubble-${B.id}`,St.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let Tr=document.createElement("div");Tr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Tr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),St.appendChild(Tr)}St.appendChild(Qt),ft=St}else{let St=document.createElement("div");if(St.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",St.id=`bubble-${B.id}`,St.setAttribute("data-message-id",B.id),St.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let Tr=document.createElement("div");Tr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Tr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),St.appendChild(Tr)}St.appendChild(Qt),ft=St}}if(ft||gr!=null){let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-component-directive-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),qt||Qt.classList.add("persona-w-full"),v.appendChild(Qt),Q.push({messageId:B.id,fingerprint:Ot,bubble:ft});return}}}if(!bt)if(B.variant==="reasoning"&&B.reasoning){if(!Ke)return;bt=Sp(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!Ce)return;bt=Ap(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;bt=bl(B,o)}else{let rt=(wo=o.layout)==null?void 0:wo.messages;rt!=null&&rt.renderUserMessage&&B.role==="user"?bt=rt.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):rt!=null&&rt.renderAssistantMessage&&B.role==="assistant"?bt=rt.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):bt=ja(B,h,rt,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o}),B.role!=="user"&&bt&&kp(bt,B,o,_)}let or=document.createElement("div");or.className="persona-flex",or.id=`wrapper-${B.id}`,or.setAttribute("data-wrapper-id",B.id),B.role==="user"&&or.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&or.classList.add("persona-w-full"),or.appendChild(bt),fh(Bo,B.id,Ot,or),v.appendChild(or)}),Y.composerOverlay&&Y.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Pe=Re.getAttribute("data-persona-ask-sheet-for");Pe&&!D.has(Pe)&&Ln(Y.composerOverlay,Pe)}),(Le=(st=o.features)==null?void 0:st.toolCallDisplay)!=null&&Le.grouped){let B=[],Re=[];f.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ce){Re.push(Pe);return}Re.length>1&&B.push(Re),Re=[]}),Re.length>1&&B.push(Re),B.forEach((Pe,fe)=>{var Ye,Rt;let Ut=Pe.map(cr=>Array.from(v.children).find(go=>go instanceof HTMLElement&&go.getAttribute("data-wrapper-id")===cr.id)).filter(cr=>!!cr);if(Ut.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${fe}-${Pe[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${fe}-${Pe[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let bt=document.createElement("div");bt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Pe.length} tools`,eo=(Rt=(Ye=o.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Rt.call(Ye,{messages:Pe,toolCalls:Pe.map(cr=>cr.toolCall).filter(cr=>!!cr),defaultSummary:zt,config:o});$(bt,eo)||(bt.textContent=zt);let or=document.createElement("div");or.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(bt,or),Ot.appendChild(Kt),Ut[0].before(Ot),Ut.forEach((cr,go)=>{let to=document.createElement("div");to.className="persona-tool-group-item persona-relative",to.setAttribute("data-persona-tool-group-item","true"),go<Ut.length-1&&to.setAttribute("data-persona-tool-group-connector","true"),to.appendChild(cr),or.appendChild(to)})})}mh(Bo,O);let nt=f.some(B=>B.role==="assistant"&&B.streaming),$e=f[f.length-1],ut=($e==null?void 0:$e.role)==="assistant"&&!$e.streaming&&$e.variant!=="approval";if(Ho&&f.some(B=>B.role==="user")&&!nt&&!ut){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:pa},Re=n.find(fe=>fe.renderLoadingIndicator),Pe=null;if(Re!=null&&Re.renderLoadingIndicator&&(Pe=Re.renderLoadingIndicator(B)),Pe===null&&((Ee=o.loadingIndicator)!=null&&Ee.render)&&(Pe=o.loadingIndicator.render(B)),Pe===null&&(Pe=pa()),Pe){let fe=document.createElement("div"),Ut=((ze=o.loadingIndicator)==null?void 0:ze.showBubble)!==!1;fe.className=Ut?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Pe);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(fe),v.appendChild(Ot)}}if(!Ho&&f.length>0){let B=f[f.length-1],Re={config:o,lastMessage:B,messageCount:f.length},Pe=n.find(Ut=>Ut.renderIdleIndicator),fe=null;if(Pe!=null&&Pe.renderIdleIndicator&&(fe=Pe.renderIdleIndicator(Re)),fe===null&&((Qe=o.loadingIndicator)!=null&&Qe.renderIdle)&&(fe=o.loadingIndicator.renderIdle(Re)),fe){let Ut=document.createElement("div"),Ot=((xt=o.loadingIndicator)==null?void 0:xt.showBubble)!==!1;Ut.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ut.setAttribute("data-idle-indicator","true"),Ut.appendChild(fe);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Ut),v.appendChild(Kt)}}if(el(l,v),se.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of se){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),Qo.set(B,Re))}if(Qo.size>0)for(let B of Qo.keys())O.has(B)||Qo.delete(B);if(Q.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of Q){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),Do.set(B,Re))}if(Do.size>0)for(let B of Do.keys())O.has(B)||Do.delete(B);if(Se.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of Se){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),bo.set(B,Re))}if(bo.size>0)for(let B of bo.keys())O.has(B)||bo.delete(B)},bn=(l,f,h)=>{ai(l,f,h),fn()},vn=null,si=()=>{var h;if(vn)return;let l=v=>{let R=v.composedPath();R.includes(_e)||Ze&&R.includes(Ze)||I(!1,"user")};vn=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},ds=()=>{var f;if(!vn)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",vn,!0),vn=null};dt.push(()=>ds());let Cn=null,ii=()=>{var h;if(Cn)return;let l=v=>{v.key==="Escape"&&(v.isComposing||I(!1,"user"))};Cn=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},cs=()=>{var f;if(!Cn)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Cn,!0),Cn=null};dt.push(()=>cs());let wn=!1,ps=new Set,Sa=()=>{var f,h,v,R;let l=(v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:v.streamAnimation;return l||((R=o.features)==null?void 0:R.streamAnimation)},Ve=()=>{var ut,st,Le,Ee;if(!H())return;let l=Y.peekBanner,f=Y.peekTextNode;if(!l||!f)return;if(k){l.classList.remove("persona-pill-peek--visible");return}let h=(ut=_==null?void 0:_.getMessages())!=null?ut:[],v;for(let ze=h.length-1;ze>=0;ze--){let Qe=h[ze];if(Qe.role==="assistant"&&Qe.content){v=Qe;break}}if(!v){l.classList.remove("persona-pill-peek--visible");return}let R=v.content,F=!!v.streaming,$=Sa(),O=al($),D=O.type!=="none"?Bs(O.type,$==null?void 0:$.plugins):null,ae=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,v))===!0,se=D!==null&&(F||ae);se&&D&&!ps.has(D.name)&&(pp(D,e),ps.add(D.name));let Q=se&&(D!=null&&D.containerClass)?D.containerClass:null,ye=(Le=f.dataset.personaPeekStreamClass)!=null?Le:null;ye&&ye!==Q&&(f.classList.remove(ye),delete f.dataset.personaPeekStreamClass),Q&&ye!==Q&&(f.classList.add(Q),f.dataset.personaPeekStreamClass=Q),se?(f.style.setProperty("--persona-stream-step",`${O.speed}ms`),f.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let He=se?sl(R,O.buffer,D,v,F):R;if(se&&O.placeholder==="skeleton"&&F&&(!He||!He.trim())){let ze=document.createElement("div"),Qe=Fs();Qe.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Qe),el(f,ze)}else{let ze=Math.max(0,He.length-100),Qe=He.length>100?He.slice(-100):He,xt=qo(Qe);if(!se||!D){let B=He.length>100?`\u2026${Qe}`:Qe;f.textContent!==B&&(f.textContent=B)}else{let B=xt;(D.wrap==="char"||D.wrap==="word")&&(B=Ds(xt,D.wrap,`peek-${v.id}`,{skipTags:D.skipTags,startIndex:ze}));let Re=document.createElement("div");if(Re.innerHTML=B,D.useCaret&&Qe.length>0){let Pe=il(),fe=Re.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ut=fe[fe.length-1];Ut!=null&&Ut.parentNode?Ut.parentNode.insertBefore(Pe,Ut.nextSibling):Re.appendChild(Pe)}el(f,Re),(Ee=D.onAfterRender)==null||Ee.call(D,{container:f,bubble:l,messageId:v.id,message:v,speed:O.speed,duration:O.duration})}}let $e=Ho||wn;l.classList.toggle("persona-pill-peek--visible",$e)};if(H()){let l=Y.peekBanner;if(l){let v=R=>{R.preventDefault(),R.stopPropagation(),I(!0,"user")};l.addEventListener("pointerdown",v),dt.push(()=>{l.removeEventListener("pointerdown",v)})}let f=()=>{wn||(wn=!0,Ve())},h=()=>{wn&&(wn=!1,Ve())};be.addEventListener("pointerenter",f),be.addEventListener("pointerleave",h),dt.push(()=>{be.removeEventListener("pointerenter",f),be.removeEventListener("pointerleave",h)}),Ze&&(Ze.addEventListener("pointerenter",f),Ze.addEventListener("pointerleave",h),dt.push(()=>{Ze.removeEventListener("pointerenter",f),Ze.removeEventListener("pointerleave",h)}))}let L=l=>{var ye,He,Se,nt,$e,ut,st,Le;let f=(He=(ye=o.launcher)==null?void 0:ye.composerBar)!=null?He:{},h=(Se=f.expandedSize)!=null?Se:"anchored",v=(nt=f.bottomOffset)!=null?nt:"16px",R=f.collapsedMaxWidth,F=($e=f.expandedMaxWidth)!=null?$e:"880px",$=(ut=f.expandedTopOffset)!=null?ut:"5vh",O=(st=f.modalMaxWidth)!=null?st:"880px",D=(Le=f.modalMaxHeight)!=null?Le:"min(90vh, 800px)",ae="calc(100vw - 32px)",se="var(--persona-pill-area-height, 80px)",Q=_e.style;if(Q.left="",Q.right="",Q.top="",Q.bottom="",Q.transform="",Q.width="",Q.maxWidth="",Q.height="",Q.maxHeight="",Ze){let Ee=Ze.style;Ee.bottom=v,Ee.width=R!=null?R:""}if(l&&h!=="fullscreen"){if(h==="modal"){Q.top="50%",Q.left="50%",Q.transform="translate(-50%, -50%)",Q.bottom="auto",Q.right="auto",Q.width=O,Q.maxWidth=ae,Q.maxHeight=D,Q.height=D;return}Q.left="50%",Q.transform="translateX(-50%)",Q.bottom=`calc(${v} + ${se})`,Q.top=$,Q.width=F,Q.maxWidth=ae}},U=()=>{var D,ae,se,Q,ye,He,Se,nt;if(!W())return;if(H()){let ut=(se=((ae=(D=o.launcher)==null?void 0:D.composerBar)!=null?ae:{}).expandedSize)!=null?se:"anchored",st=k?"expanded":"collapsed";_e.dataset.state=st,_e.dataset.expandedSize=ut,Ze&&(Ze.dataset.state=st,Ze.dataset.expandedSize=ut),_e.style.removeProperty("display"),_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),L(k),pe.style.display=k?"flex":"none",xe(),k?(si(),ii()):(ds(),cs()),Ve();return}let l=pr(o),f=(Q=e.ownerDocument.defaultView)!=null?Q:window,h=(He=(ye=o.launcher)==null?void 0:ye.mobileBreakpoint)!=null?He:640,v=(nt=(Se=o.launcher)==null?void 0:Se.mobileFullscreen)!=null?nt:!0,R=f.innerWidth<=h,F=v&&R&&E,$=no(o).reveal;k?(_e.style.removeProperty("display"),_e.style.display=l?"flex":"",_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0"),be.classList.add("persona-scale-100","persona-opacity-100"),rr?rr.element.style.display="none":mr&&(mr.style.display="none")):(l?l&&($==="overlay"||$==="push")&&!F?(_e.style.removeProperty("display"),_e.style.display="flex",_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(_e.style.setProperty("display","none","important"),_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(_e.style.display="",_e.classList.add("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100"),be.classList.add("persona-scale-95","persona-opacity-0")),rr?rr.element.style.display=l?"none":"":mr&&(mr.style.display=l?"none":""))},I=(l,f="user")=>{var F,$;if(!W()||k===l)return;let h=k;k=l,U();let v=(()=>{var Se,nt,$e,ut,st,Le,Ee,ze,Qe,xt;let O=(nt=(Se=o.launcher)==null?void 0:Se.sidebarMode)!=null?nt:!1,D=($e=e.ownerDocument.defaultView)!=null?$e:window,ae=(st=(ut=o.launcher)==null?void 0:ut.mobileFullscreen)!=null?st:!0,se=(Ee=(Le=o.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Ee:640,Q=D.innerWidth<=se,ye=pr(o)&&ae&&Q,He=H()&&((xt=(Qe=(ze=o.launcher)==null?void 0:ze.composerBar)==null?void 0:Qe.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return O||ae&&Q&&E||ye||He})();if(k&&v){if(!tr){let O=e.getRootNode(),D=O instanceof ShadowRoot?O.host:e.closest(".persona-host");D&&(tr=up(D,($=(F=o.launcher)==null?void 0:F.zIndex)!=null?$:Lr))}fr||(fr=fp(e.ownerDocument))}else k||(tr==null||tr(),tr=null,fr==null||fr(),fr=null);k&&(us(),ot()==="follow"?Oo(!0):is());let R={open:k,source:f,timestamp:Date.now()};k&&!h?a.emit("widget:opened",R):!k&&h&&a.emit("widget:closed",R),a.emit("widget:state",{open:k,launcherEnabled:E,voiceActive:mt.active,streaming:_.isStreaming()})},X=l=>{Pr(l?"stop":"send"),z&&(z.disabled=l),qn.buttons.forEach(f=>{f.disabled=l}),Ne.dataset.personaComposerStreaming=l?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},re=()=>{mt.active||ke&&ke.focus()};a.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>re(),200)});let K=()=>{var h,v,R,F,$,O,D,ae,se,Q,ye;Eo.textContent=(v=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?v:"Hello \u{1F44B}",V.textContent=(F=(R=o.copy)==null?void 0:R.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",ke.placeholder=(O=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?O:"How can I help...";let l=Me.querySelector("[data-persona-intro-card]");if(l){let He=((D=o.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=He?"":"none",He?(Me.classList.remove("persona-gap-3"),Me.classList.add("persona-gap-6")):(Me.classList.remove("persona-gap-6"),Me.classList.add("persona-gap-3"))}!((se=(ae=o.sendButton)==null?void 0:ae.useIcon)!=null&&se)&&!(_!=null&&_.isStreaming())&&(je.textContent=(ye=(Q=o.copy)==null?void 0:Q.sendButtonLabel)!=null?ye:"Send"),ke.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ke.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{m(f=>({...f,sessionId:l}))}});let Ae=null,Oe=()=>{Ae==null&&(Ae=setInterval(()=>{let l=Je.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Ae),Ae=null;return}let f=Date.now();l.forEach(h=>{let v=Number(h.getAttribute("data-tool-elapsed"));v&&(h.textContent=Mi(f-v))})},100))};_=new _a(o,{onMessagesChanged(l){var v;bn(Je,l,me),Oe(),ga(l),Oo(!Ho),ni(l);let f=[...l].reverse().find(R=>R.role==="user");l.length===0&&zn(),!xa||$n?(xa=!0,ya=(v=f==null?void 0:f.id)!=null?v:null):f&&f.id!==ya&&(ya=f.id,oi(f.id));let h=mt.lastUserMessageId;f&&f.id!==h&&(mt.lastUserMessageId=f.id,a.emit("user:message",f)),mt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Ca(l),Ve()},onStatusChanged(l){var v;let f=(v=o.statusIndicator)!=null?v:{};Lt(ur,(R=>{var F,$,O,D;return R==="idle"?(F=f.idleText)!=null?F:kr.idle:R==="connecting"?($=f.connectingText)!=null?$:kr.connecting:R==="connected"?(O=f.connectedText)!=null?O:kr.connected:R==="error"?(D=f.errorText)!=null?D:kr.error:kr[R]})(l),f,l)},onStreamingChanged(l){Ho=l,X(l),_&&bn(Je,_.getMessages(),me),l||Oo(!0),Ve()},onVoiceStatusChanged(l){var f,h;if(a.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Zo(),Ma();break;case"processing":Zo(),$x();break;case"speaking":Zo(),zx();break;default:l==="idle"&&_.isBargeInActive()?(Zo(),Ma(),z==null||z.setAttribute("aria-label","End voice session")):(mt.active=!1,Zo(),po("system"),Vr());break}},onArtifactsState(l){Kr=l,Jr(),Ca()}}),Mt.current=_;let at=null;if(_.onReadAloudChange((l,f)=>{var R;pn=l,un=f,fn();let h=l!=null?l:at;l&&(at=l);let v=h&&(R=_.getMessages().find(F=>F.id===h))!=null?R:null;a.emit("message:read-aloud",{messageId:h,message:v,state:f,timestamp:Date.now()}),f==="idle"&&(at=null)}),xa=!0,((Zu=(Yu=o.voiceRecognition)==null?void 0:Yu.provider)==null?void 0:Zu.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&_.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(ge||o.onSSEEvent)&&_.setSSEEventCallback((l,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,l,f),ue==null||ue.processEvent(l,f),ge==null||ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(f)})}),d&&d.then(l=>{var f,h,v;if(l){if(l.metadata&&(c=Rp(l.metadata),T.syncFromMetadata()),(f=l.messages)!=null&&f.length){$n=!0;try{_.hydrateMessages(l.messages)}finally{$n=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(v=l.selectedArtifactId)!=null?v:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let tt=()=>{var f,h,v;!H()||k||!((v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||v)||I(!0,"auto")},Bt=l=>{var R;if(l.preventDefault(),_.isStreaming()){_.cancel(),ue==null||ue.reset(),G==null||G.update();return}let f=ke.value.trim(),h=(R=yt==null?void 0:yt.hasAttachments())!=null?R:!1;if(!f&&!h)return;tt();let v;h&&(v=[],v.push(...yt.getContentParts()),f&&v.push(Es(f))),ke.value="",ke.style.height="auto",Tt(),_.sendMessage(f,{contentParts:v}),h&&yt.clearAttachments()},$t=()=>{var l;return((l=o.features)==null?void 0:l.composerHistory)!==!1},lr={...tl},wt=!1,Tt=()=>{lr={...tl}},br=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var f;return(f=l.content)!=null?f:""}).filter(l=>l.length>0),Hr=l=>{if(!ke)return;wt=!0,ke.value=l,ke.dispatchEvent(new Event("input",{bubbles:!0})),wt=!1;let f=ke.value.length;ke.setSelectionRange(f,f)},Sr=()=>{wt||Tt()},Zt=l=>{if(ke){if($t()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=ke.selectionStart===0&&ke.selectionEnd===0,h=dh({direction:l.key==="ArrowUp"?"up":"down",history:br(),currentValue:ke.value,atStart:f,state:lr});if(lr=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Hr(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Tt(),l.preventDefault(),je.click()}}},uo=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(pe)&&(_.cancel(),ue==null||ue.reset(),G==null||G.update(),Tt(),l.preventDefault(),l.stopImmediatePropagation())},Kp=async l=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!yt)return;let f=Rv(l.clipboardData);f.length!==0&&(l.preventDefault(),await yt.handleFiles(f))},fo=null,_o=!1,Aa=null,pt=null,Xp=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,li=(l="user")=>{var F,$,O,D,ae,se,Q;if(_o||_.isStreaming())return;let f=Xp();if(!f)return;fo=new f;let v=($=((F=o.voiceRecognition)!=null?F:{}).pauseDuration)!=null?$:2e3;fo.continuous=!0,fo.interimResults=!0,fo.lang="en-US";let R=ke.value;fo.onresult=ye=>{let He="",Se="";for(let $e=0;$e<ye.results.length;$e++){let ut=ye.results[$e],st=ut[0].transcript;ut.isFinal?He+=st+" ":Se=st}let nt=R+He+Se;ke.value=nt,Aa&&clearTimeout(Aa),(He||Se)&&(Aa=window.setTimeout(()=>{let $e=ke.value.trim();$e&&fo&&_o&&(Sn(),ke.value="",ke.style.height="auto",_.sendMessage($e,{viaVoice:!0}))},v))},fo.onerror=ye=>{ye.error!=="no-speech"&&Sn()},fo.onend=()=>{if(_o){let ye=ke.value.trim();ye&&ye!==R.trim()&&(ke.value="",ke.style.height="auto",_.sendMessage(ye,{viaVoice:!0})),Sn()}};try{if(fo.start(),_o=!0,mt.active=!0,l!=="system"&&(mt.manuallyDeactivated=!1),po(l),Vr(),z){let ye=(O=o.voiceRecognition)!=null?O:{};pt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(D=ye.iconName)!=null?D:"mic",iconSize:parseFloat((Q=(se=ye.iconSize)!=null?se:(ae=o.sendButton)==null?void 0:ae.size)!=null?Q:"40")||24};let He=ye.recordingBackgroundColor,Se=ye.recordingIconColor,nt=ye.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=He!=null?He:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let $e=z.querySelector("svg");$e&&$e.setAttribute("stroke",Se)}nt&&(z.style.borderColor=nt),z.setAttribute("aria-label","Stop voice recognition")}}catch{Sn("system")}},Sn=(l="user")=>{if(_o){if(_o=!1,Aa&&(clearTimeout(Aa),Aa=null),fo){try{fo.stop()}catch{}fo=null}if(mt.active=!1,po(l),Vr(),z){if(z.classList.remove("persona-voice-recording"),pt){z.style.backgroundColor=pt.backgroundColor,z.style.color=pt.color,z.style.borderColor=pt.borderColor;let f=z.querySelector("svg");f&&f.setAttribute("stroke",pt.color||"currentColor"),pt=null}z.setAttribute("aria-label","Start voice recognition")}}},Vx=(l,f)=>{var st,Le,Ee,ze,Qe,xt,B,Re,Pe;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),v=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",R=((Le=l==null?void 0:l.provider)==null?void 0:Le.type)==="custom";if(!(h||v||R))return null;let $=S("div","persona-send-button-wrapper"),O=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let D=(Ee=l==null?void 0:l.iconName)!=null?Ee:"mic",ae=(ze=f==null?void 0:f.size)!=null?ze:"40px",se=(Qe=l==null?void 0:l.iconSize)!=null?Qe:ae,Q=parseFloat(se)||24,ye=(xt=l==null?void 0:l.backgroundColor)!=null?xt:f==null?void 0:f.backgroundColor,He=(B=l==null?void 0:l.iconColor)!=null?B:f==null?void 0:f.textColor;O.style.width=se,O.style.height=se,O.style.minWidth=se,O.style.minHeight=se,O.style.fontSize="18px",O.style.lineHeight="1",He?O.style.color=He:O.style.color="var(--persona-text, #111827)";let nt=ve(D,Q,He||"currentColor",1.5);nt?O.appendChild(nt):O.textContent="\u{1F3A4}",ye?O.style.backgroundColor=ye:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),$.appendChild(O);let $e=(Re=l==null?void 0:l.tooltipText)!=null?Re:"Start voice recognition";if(((Pe=l==null?void 0:l.showTooltip)!=null?Pe:!1)&&$e){let fe=S("div","persona-send-button-tooltip");fe.textContent=$e,$.appendChild(fe)}return{micButton:O,micButtonWrapper:$}},Hl=()=>{var f,h,v,R,F;if(!z||pt)return;let l=(f=o.voiceRecognition)!=null?f:{};pt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((F=(R=l.iconSize)!=null?R:(v=o.sendButton)==null?void 0:v.size)!=null?F:"40")||24}},Bl=(l,f)=>{var F,$,O,D,ae;if(!z)return;let h=z.querySelector("svg");h&&h.remove();let v=(ae=pt==null?void 0:pt.iconSize)!=null?ae:parseFloat((D=(O=(F=o.voiceRecognition)==null?void 0:F.iconSize)!=null?O:($=o.sendButton)==null?void 0:$.size)!=null?D:"40")||24,R=ve(l,v,f,1.5);R&&z.appendChild(R)},di=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ma=()=>{var R;if(!z)return;Hl();let l=(R=o.voiceRecognition)!=null?R:{},f=l.recordingBackgroundColor,h=l.recordingIconColor,v=l.recordingBorderColor;if(di(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let F=z.querySelector("svg");F&&F.setAttribute("stroke",h)}v&&(z.style.borderColor=v),z.setAttribute("aria-label","Stop voice recognition")},$x=()=>{var O,D,ae,se,Q,ye,He,Se;if(!z)return;Hl();let l=(O=o.voiceRecognition)!=null?O:{},f=_.getVoiceInterruptionMode(),h=(D=l.processingIconName)!=null?D:"loader",v=(se=(ae=l.processingIconColor)!=null?ae:pt==null?void 0:pt.color)!=null?se:"",R=(ye=(Q=l.processingBackgroundColor)!=null?Q:pt==null?void 0:pt.backgroundColor)!=null?ye:"",F=(Se=(He=l.processingBorderColor)!=null?He:pt==null?void 0:pt.borderColor)!=null?Se:"";di(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=R,z.style.borderColor=F;let $=v||"currentColor";z.style.color=$,Bl(h,$),z.setAttribute("aria-label","Processing voice input"),f==="none"&&(z.style.cursor="default")},zx=()=>{var ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee;if(!z)return;Hl();let l=(ae=o.voiceRecognition)!=null?ae:{},f=_.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",v=(se=l.speakingIconName)!=null?se:h,R=(Se=l.speakingIconColor)!=null?Se:f==="barge-in"?(ye=(Q=l.recordingIconColor)!=null?Q:pt==null?void 0:pt.color)!=null?ye:"":(He=pt==null?void 0:pt.color)!=null?He:"",F=(ut=l.speakingBackgroundColor)!=null?ut:f==="barge-in"?(nt=l.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":($e=pt==null?void 0:pt.backgroundColor)!=null?$e:"",$=(Ee=l.speakingBorderColor)!=null?Ee:f==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Le=pt==null?void 0:pt.borderColor)!=null?Le:"";di(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=F,z.style.borderColor=$;let O=R||"currentColor";z.style.color=O,Bl(v,O);let D=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",D),f==="none"&&(z.style.cursor="default"),f==="barge-in"&&z.classList.add("persona-voice-recording")},Zo=()=>{var l,f,h;z&&(di(),pt&&(z.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",z.style.color=(f=pt.color)!=null?f:"",z.style.borderColor=(h=pt.borderColor)!=null?h:"",Bl(pt.iconName,pt.color||"currentColor"),pt=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},ci=()=>{var l,f;if(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"){let h=_.getVoiceStatus(),v=_.getVoiceInterruptionMode();if(v==="none"&&(h==="processing"||h==="speaking"))return;if(v==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Vr(),po("user"),Zo()});return}_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),mt.manuallyDeactivated=!_.isVoiceActive(),Vr(),po("user"),_.isVoiceActive()?Ma():Zo()});return}if(_o){let h=ke.value.trim();mt.manuallyDeactivated=!0,Vr(),Sn("user"),h&&(ke.value="",ke.style.height="auto",_.sendMessage(h))}else mt.manuallyDeactivated=!1,Vr(),li("user")};jr=ci,z&&(z.addEventListener("click",ci),dt.push(()=>{var l,f;((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Zo()):Sn("system"),z&&z.removeEventListener("click",ci)}));let jx=a.on("assistant:complete",()=>{es&&(mt.active||mt.manuallyDeactivated||es==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var l,f;!mt.active&&!mt.manuallyDeactivated&&(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("auto"),_.isVoiceActive()&&Ma()}):li("auto"))},600))});dt.push(jx);let Gx=a.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(Gx);let Qp=()=>{I(!k,"user")},rr=null,mr=null;if(E&&!H()){let{instance:l,element:f}=yp({config:o,plugins:n,onToggle:Qp});rr=l,l||(mr=f)}rr?e.appendChild(rr.element):mr&&e.appendChild(mr),U(),ga(),K(),X(_.isStreaming()),ot()==="follow"?Oo(!0):is(),Ys(),P&&(!E||H()?setTimeout(()=>re(),0):k&&setTimeout(()=>re(),200));let us=()=>{var D,ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee,ze,Qe,xt,B,Re,Pe,fe,Ut,Ot;if(H()){Ur(),U();return}let l=pr(o),f=(ae=(D=o.launcher)==null?void 0:D.sidebarMode)!=null?ae:!1,h=l||f||((Q=(se=o.launcher)==null?void 0:se.fullHeight)!=null?Q:!1),v=(ye=e.ownerDocument.defaultView)!=null?ye:window,R=(Se=(He=o.launcher)==null?void 0:He.mobileFullscreen)!=null?Se:!0,F=($e=(nt=o.launcher)==null?void 0:nt.mobileBreakpoint)!=null?$e:640,$=v.innerWidth<=F,O=R&&$&&E;try{if(O){xe(),Wn(e,o);return}if(A&&(A=!1,xe(),Wn(e,o)),!E&&!l){be.style.height="",be.style.width="";return}if(!f&&!l){let Kt=(st=(ut=o==null?void 0:o.launcher)==null?void 0:ut.width)!=null?st:o==null?void 0:o.launcherWidth,bt=Kt!=null?Kt:oo;be.style.width=bt,be.style.maxWidth=bt}if(Ro(),!h){let Kt=v.innerHeight,bt=64,zt=(Ee=(Le=o.launcher)==null?void 0:Le.heightOffset)!=null?Ee:0,eo=Math.max(200,Kt-bt),or=Math.min(640,eo),Ye=Math.max(200,or-zt);be.style.height=`${Ye}px`}}finally{if(Ur(),U(),k&&E){let bt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((xt=(Qe=o.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?xt:640),zt=(Re=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Re:!1,eo=(fe=(Pe=o.launcher)==null?void 0:Pe.mobileFullscreen)!=null?fe:!0,or=pr(o)&&eo&&bt,Ye=zt||eo&&bt&&E||or;if(Ye&&!fr){let Rt=e.getRootNode(),cr=Rt instanceof ShadowRoot?Rt.host:e.closest(".persona-host");cr&&!tr&&(tr=up(cr,(Ot=(Ut=o.launcher)==null?void 0:Ut.zIndex)!=null?Ot:Lr)),fr=fp(e.ownerDocument)}else Ye||(tr==null||tr(),tr=null,fr==null||fr(),fr=null)}}};us();let Jp=(ef=e.ownerDocument.defaultView)!=null?ef:window;if(Jp.addEventListener("resize",us),dt.push(()=>Jp.removeEventListener("resize",us)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ur()});l.observe(Ne),dt.push(()=>l.disconnect())}Zr=Me.scrollTop;let Yp=sn(Me),Kx=()=>{let l=Me.getRootNode(),f=typeof l.getSelection=="function"?l.getSelection():null;return f!=null?f:Me.ownerDocument.getSelection()},Dl=()=>gh(Kx(),Me),Zp=()=>{let l=Me.scrollTop,f=sn(Me),h=f<Yp;if(Yp=f,ot()!=="follow"){Zr=l,$r();return}let{action:v,nextLastScrollTop:R}=ol({following:Yr.isFollowing(),currentScrollTop:l,lastScrollTop:Zr,nearBottom:la(Me,ba),userScrollThreshold:Qs,isAutoScrolling:Co||Vn||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Zr=R,v==="resume"){Dl()||No();return}v==="pause"&&wa()};if(Me.addEventListener("scroll",Zp,{passive:!0}),dt.push(()=>Me.removeEventListener("scroll",Zp)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{ri()});l.observe(Je),l.observe(Me),dt.push(()=>l.disconnect())}let eu=()=>{ot()==="follow"&&Yr.isFollowing()&&Dl()&&wa()},tu=Me.ownerDocument;tu.addEventListener("selectionchange",eu),dt.push(()=>{tu.removeEventListener("selectionchange",eu)});let ru=l=>{if(ot()!=="follow")return;let f=nl({following:Yr.isFollowing(),deltaY:l.deltaY,nearBottom:la(Me,ba),resumeWhenNearBottom:!0});f==="pause"?wa():f==="resume"&&!Dl()&&No()};Me.addEventListener("wheel",ru,{passive:!0}),dt.push(()=>Me.removeEventListener("wheel",ru)),lt.addEventListener("click",()=>{zn(),Me.scrollTop=Me.scrollHeight,Zr=Me.scrollTop,No(),Oo(!0),$r()}),dt.push(()=>lt.remove()),dt.push(()=>{rs(),zn()});let ou=()=>{j&&(Wo&&(j.removeEventListener("click",Wo),Wo=null),W()?(j.style.display="",Wo=()=>{I(!1,"user")},j.addEventListener("click",Wo)):j.style.display="none")};ou(),(()=>{let{clearChatButton:l}=Y;l&&l.addEventListener("click",()=>{_.clearMessages(),Bo.clear(),No(),Ln(Y.composerOverlay);try{localStorage.removeItem(Ja),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ja}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ja)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(v=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",v)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}c={},T.syncFromMetadata(),ge==null||ge.clear(),ue==null||ue.reset(),G==null||G.update()})})(),Wt&&Wt.addEventListener("submit",Bt),ke==null||ke.addEventListener("keydown",Zt),ke==null||ke.addEventListener("input",Sr),ke==null||ke.addEventListener("paste",Kp);let nu=(tf=e.ownerDocument)!=null?tf:document;nu.addEventListener("keydown",uo,!0);let au="persona-attachment-drop-active",fs=0,Fl=()=>{fs=0,pe.classList.remove(au)},Ta=()=>{var l;return((l=o.attachments)==null?void 0:l.enabled)===!0&&yt!==null},su=l=>{!Pl(l.dataTransfer)||!Ta()||(fs++,fs===1&&pe.classList.add(au))},iu=l=>{!Pl(l.dataTransfer)||!Ta()||(fs--,fs<=0&&Fl())},lu=l=>{!Pl(l.dataTransfer)||!Ta()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},du=l=>{var h;if(!Pl(l.dataTransfer)||!Ta())return;l.preventDefault(),l.stopPropagation(),Fl();let f=Array.from((h=l.dataTransfer.files)!=null?h:[]);f.length!==0&&yt.handleFiles(f)},An=!0;pe.addEventListener("dragenter",su,An),pe.addEventListener("dragleave",iu,An),e.addEventListener("dragover",lu,An),e.addEventListener("drop",du,An);let pi=e.ownerDocument,cu=l=>{Ta()&&l.preventDefault()},pu=l=>{Ta()&&l.preventDefault()};pi.addEventListener("dragover",cu),pi.addEventListener("drop",pu),dt.push(()=>{Wt&&Wt.removeEventListener("submit",Bt),ke==null||ke.removeEventListener("keydown",Zt),ke==null||ke.removeEventListener("input",Sr),ke==null||ke.removeEventListener("paste",Kp),nu.removeEventListener("keydown",uo,!0)}),dt.push(()=>{pe.removeEventListener("dragenter",su,An),pe.removeEventListener("dragleave",iu,An),e.removeEventListener("dragover",lu,An),e.removeEventListener("drop",du,An),pi.removeEventListener("dragover",cu),pi.removeEventListener("drop",pu),Fl()}),dt.push(()=>{_.cancel()}),rr?dt.push(()=>{rr==null||rr.destroy()}):mr&&dt.push(()=>{mr==null||mr.remove()});let dr={update(l){var Tr,Br,Uo,vr,Dr,Fr,Qn,ms,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,vf,Cf,wf,Sf,Af,Mf,Tf,Ef,kf,Lf,Pf,Rf,If,Wf,Hf,Bf,Df,Ff,Nf,Of,_f,Uf,qf,Vf,$f,zf,jf,Gf,Kf,Xf,Qf,Jf,Yf,Zf,em,tm,rm,om,nm,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,vm,Cm,wm,Sm,Am,Mm,Tm,Em,km,Lm,Pm,Rm,Im,Wm,Hm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,Vm,$m,zm,jm,Gm,Km,Xm,Qm,Jm,Ym,Zm,eg,tg,rg,og,ng,ag,sg,ig;let f=o.toolCall,h=o.messageActions,v=(Tr=o.layout)==null?void 0:Tr.messages,R=o.colorScheme,F=o.loadingIndicator,$=o.iterationDisplay,O=(Br=o.features)==null?void 0:Br.showReasoning,D=(Uo=o.features)==null?void 0:Uo.showToolCalls,ae=(vr=o.features)==null?void 0:vr.toolCallDisplay,se=(Dr=o.features)==null?void 0:Dr.reasoningDisplay;o={...o,...l},xe(),Wn(e,o),Cl(e,o),wl(e,o),Jr(),o.colorScheme!==R&&Za();let Q=$s.getForInstance(o.plugins);n.length=0,n.push(...Q),E=(Qn=(Fr=o.launcher)==null?void 0:Fr.enabled)!=null?Qn:!0,M=(df=(ms=o.launcher)==null?void 0:ms.autoExpand)!=null?df:!1,Ke=(pf=(cf=o.features)==null?void 0:cf.showReasoning)!=null?pf:!0,Ce=(ff=(uf=o.features)==null?void 0:uf.showToolCalls)!=null?ff:!0,Ue=(gf=(mf=o.features)==null?void 0:mf.scrollToBottom)!=null?gf:{};let ye=ot();Te=(xf=(hf=o.features)==null?void 0:hf.scrollBehavior)!=null?xf:{},ye!==ot()&&(zn(),No()),ko(),$r();let He=Ie;if(Ie=(bf=(yf=o.features)==null?void 0:yf.showEventStreamToggle)!=null?bf:!1,Ie&&!He){if(ge||(J=new qs(de),ge=new Us(le,J),ue=ue!=null?ue:new Vs,J.open().then(()=>ge==null?void 0:ge.restore()).catch(()=>{}),_.setSSEEventCallback((te,Et)=>{var jt;(jt=o.onSSEEvent)==null||jt.call(o,te,Et),ue==null||ue.processEvent(te,Et),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!ht&&qe){let te=(Cf=(vf=o.features)==null?void 0:vf.eventStream)==null?void 0:Cf.classNames,Et="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");ht=S("button",Et),ht.style.width="28px",ht.style.height="28px",ht.style.color=_r.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let jt=ve("activity","18px","currentColor",1.5);jt&&ht.appendChild(jt);let it=Y.clearChatButtonWrapper,It=Y.closeButtonWrapper,hr=it||It;hr&&hr.parentNode===qe?qe.insertBefore(ht,hr):qe.appendChild(ht),ht.addEventListener("click",()=>{ce?yo():zo()})}}else!Ie&&He&&(yo(),ht&&(ht.remove(),ht=null),ge==null||ge.clear(),J==null||J.destroy(),ge=null,J=null,ue==null||ue.reset(),ue=null);if(((wf=o.launcher)==null?void 0:wf.enabled)===!1&&rr&&(rr.destroy(),rr=null),((Sf=o.launcher)==null?void 0:Sf.enabled)===!1&&mr&&(mr.remove(),mr=null),((Af=o.launcher)==null?void 0:Af.enabled)!==!1&&!rr&&!mr){let{instance:te,element:Et}=yp({config:o,plugins:n,onToggle:Qp});rr=te,te||(mr=Et),e.appendChild(Et)}rr&&rr.update(o),Xe&&((Mf=o.launcher)==null?void 0:Mf.title)!==void 0&&(Xe.textContent=o.launcher.title),et&&((Tf=o.launcher)==null?void 0:Tf.subtitle)!==void 0&&(et.textContent=o.launcher.subtitle);let Se=(Ef=o.layout)==null?void 0:Ef.header;if((Se==null?void 0:Se.layout)!==b&&qe){let te=Se?$a(o,Se,{showClose:W(),onClose:()=>I(!1,"user")}):ln({config:o,showClose:W(),onClose:()=>I(!1,"user")});gt.replaceHeader(te),qe=gt.header.element,he=gt.header.iconHolder,Xe=gt.header.headerTitle,et=gt.header.headerSubtitle,j=gt.header.closeButton,b=Se==null?void 0:Se.layout}else if(Se&&(he&&(he.style.display=Se.showIcon===!1?"none":""),Xe&&(Xe.style.display=Se.showTitle===!1?"none":""),et&&(et.style.display=Se.showSubtitle===!1?"none":""),j&&(j.style.display=Se.showCloseButton===!1?"none":""),Y.clearChatButtonWrapper)){let te=Se.showClearChat;if(te!==void 0){Y.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Et}=Y;Et&&!Et.classList.contains("persona-absolute")&&(te?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let $e=((kf=o.layout)==null?void 0:kf.showHeader)!==!1;qe&&(qe.style.display=$e?"":"none");let ut=((Lf=o.layout)==null?void 0:Lf.showFooter)!==!1;Ne&&(Ne.style.display=ut?"":"none"),Ur(),$r(),E!==w?E?I(M,"auto"):(k=!0,U()):M!==y&&I(M,"auto"),y=M,w=E,us(),ou();let Ee=JSON.stringify(l.toolCall)!==JSON.stringify(f),ze=JSON.stringify(o.messageActions)!==JSON.stringify(h),Qe=JSON.stringify((Pf=o.layout)==null?void 0:Pf.messages)!==JSON.stringify(v),xt=((Rf=o.loadingIndicator)==null?void 0:Rf.render)!==(F==null?void 0:F.render)||((If=o.loadingIndicator)==null?void 0:If.renderIdle)!==(F==null?void 0:F.renderIdle)||((Wf=o.loadingIndicator)==null?void 0:Wf.showBubble)!==(F==null?void 0:F.showBubble),B=o.iterationDisplay!==$,Re=((Bf=(Hf=o.features)==null?void 0:Hf.showReasoning)!=null?Bf:!0)!==(O!=null?O:!0)||((Ff=(Df=o.features)==null?void 0:Df.showToolCalls)!=null?Ff:!0)!==(D!=null?D:!0)||JSON.stringify((Nf=o.features)==null?void 0:Nf.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify((Of=o.features)==null?void 0:Of.reasoningDisplay)!==JSON.stringify(se);(Ee||ze||Qe||xt||B||Re)&&_&&(ha++,bn(Je,_.getMessages(),me));let fe=(_f=o.launcher)!=null?_f:{},Ut=(Uf=fe.headerIconHidden)!=null?Uf:!1,Ot=(Vf=(qf=o.layout)==null?void 0:qf.header)==null?void 0:Vf.showIcon,Kt=Ut||Ot===!1,bt=fe.headerIconName,zt=($f=fe.headerIconSize)!=null?$f:"48px";if(he){let te=pe.querySelector(".persona-border-b-persona-divider"),Et=te==null?void 0:te.querySelector(".persona-flex-col");if(Kt)he.style.display="none",te&&Et&&!te.contains(Et)&&te.insertBefore(Et,te.firstChild);else{if(he.style.display="",he.style.height=zt,he.style.width=zt,te&&Et&&(te.contains(he)?he.nextSibling!==Et&&(he.remove(),te.insertBefore(he,Et)):te.insertBefore(he,Et)),bt){let it=parseFloat(zt)||24,It=ve(bt,it*.6,"currentColor",1);It?he.replaceChildren(It):he.textContent=(zf=fe.agentIconText)!=null?zf:"\u{1F4AC}"}else if(fe.iconUrl){let it=he.querySelector("img");if(it)it.src=fe.iconUrl,it.style.height=zt,it.style.width=zt;else{let It=document.createElement("img");It.src=fe.iconUrl,It.alt="",It.className="persona-rounded-xl persona-object-cover",It.style.height=zt,It.style.width=zt,he.replaceChildren(It)}}else{let it=he.querySelector("svg"),It=he.querySelector("img");(it||It)&&he.replaceChildren(),he.textContent=(jf=fe.agentIconText)!=null?jf:"\u{1F4AC}"}let jt=he.querySelector("img");jt&&(jt.style.height=zt,jt.style.width=zt)}}let eo=(Kf=(Gf=o.layout)==null?void 0:Gf.header)==null?void 0:Kf.showTitle,or=(Qf=(Xf=o.layout)==null?void 0:Xf.header)==null?void 0:Qf.showSubtitle;if(Xe&&(Xe.style.display=eo===!1?"none":""),et&&(et.style.display=or===!1?"none":""),j){((Yf=(Jf=o.layout)==null?void 0:Jf.header)==null?void 0:Yf.showCloseButton)===!1?j.style.display="none":j.style.display="";let Et=(Zf=fe.closeButtonSize)!=null?Zf:"32px",jt=(em=fe.closeButtonPlacement)!=null?em:"inline";j.style.height=Et,j.style.width=Et;let{closeButtonWrapper:it}=Y,It=jt==="top-right",hr=it==null?void 0:it.classList.contains("persona-absolute");if(it&&It!==hr)if(it.remove(),It)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(it);else{let ct=(rm=(tm=fe.clearChat)==null?void 0:tm.placement)!=null?rm:"inline",xr=(nm=(om=fe.clearChat)==null?void 0:om.enabled)!=null?nm:!0;it.className=xr&&ct==="inline"?"":"persona-ml-auto";let zr=pe.querySelector(".persona-border-b-persona-divider");zr&&zr.appendChild(it)}if(j.style.color=fe.closeButtonColor||_r.actionIconColor,fe.closeButtonBackgroundColor?(j.style.backgroundColor=fe.closeButtonBackgroundColor,j.classList.remove("hover:persona-bg-gray-100")):(j.style.backgroundColor="",j.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let ct=fe.closeButtonBorderWidth||"0px",xr=fe.closeButtonBorderColor||"transparent";j.style.border=`${ct} solid ${xr}`,j.classList.remove("persona-border-none")}else j.style.border="",j.classList.add("persona-border-none");fe.closeButtonBorderRadius?(j.style.borderRadius=fe.closeButtonBorderRadius,j.classList.remove("persona-rounded-full")):(j.style.borderRadius="",j.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(j.style.paddingLeft=fe.closeButtonPaddingX,j.style.paddingRight=fe.closeButtonPaddingX):(j.style.paddingLeft="",j.style.paddingRight=""),fe.closeButtonPaddingY?(j.style.paddingTop=fe.closeButtonPaddingY,j.style.paddingBottom=fe.closeButtonPaddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Er=(am=fe.closeButtonIconName)!=null?am:"x",So=(sm=fe.closeButtonIconText)!=null?sm:"\xD7";j.innerHTML="";let Nr=ve(Er,"28px","currentColor",1);Nr?j.appendChild(Nr):j.textContent=So;let er=(im=fe.closeButtonTooltipText)!=null?im:"Close chat",ro=(lm=fe.closeButtonShowTooltip)!=null?lm:!0;if(j.setAttribute("aria-label",er),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),ro&&er)){let ct=null,xr=()=>{if(ct||!j)return;let Jn=j.ownerDocument,gs=Jn.body;if(!gs)return;ct=Vo(Jn,"div","persona-clear-chat-tooltip"),ct.textContent=er;let hs=Vo(Jn,"div");hs.className="persona-clear-chat-tooltip-arrow",ct.appendChild(hs);let Yn=j.getBoundingClientRect();ct.style.position="fixed",ct.style.zIndex=String(Hn),ct.style.left=`${Yn.left+Yn.width/2}px`,ct.style.top=`${Yn.top-8}px`,ct.style.transform="translate(-50%, -100%)",gs.appendChild(ct)},zr=()=>{ct&&ct.parentNode&&(ct.parentNode.removeChild(ct),ct=null)};it.addEventListener("mouseenter",xr),it.addEventListener("mouseleave",zr),j.addEventListener("focus",xr),j.addEventListener("blur",zr),it._cleanupTooltip=()=>{zr(),it&&(it.removeEventListener("mouseenter",xr),it.removeEventListener("mouseleave",zr)),j&&(j.removeEventListener("focus",xr),j.removeEventListener("blur",zr))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Rt}=Y;if(Ye){let te=(dm=fe.clearChat)!=null?dm:{},Et=(cm=te.enabled)!=null?cm:!0,jt=(um=(pm=o.layout)==null?void 0:pm.header)==null?void 0:um.showClearChat,it=jt!==void 0?jt:Et,It=(fm=te.placement)!=null?fm:"inline";if(Rt){Rt.style.display=it?"":"none";let{closeButtonWrapper:hr}=Y;!H()&&hr&&!hr.classList.contains("persona-absolute")&&(it?hr.classList.remove("persona-ml-auto"):hr.classList.add("persona-ml-auto"));let Er=It==="top-right",So=Rt.classList.contains("persona-absolute");if(!H()&&Er!==So&&it){if(Rt.remove(),Er)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",pe.style.position="relative",pe.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let er=pe.querySelector(".persona-border-b-persona-divider"),ro=Y.closeButtonWrapper;er&&ro&&ro.parentElement===er?er.insertBefore(Rt,ro):er&&er.appendChild(Rt)}let Nr=Y.closeButtonWrapper;Nr&&!Nr.classList.contains("persona-absolute")&&(Er?Nr.classList.add("persona-ml-auto"):Nr.classList.remove("persona-ml-auto"))}}if(it){if(!H()){let ct=(mm=te.size)!=null?mm:"32px";Ye.style.height=ct,Ye.style.width=ct}let hr=(gm=te.iconName)!=null?gm:"refresh-cw",Er=(hm=te.iconColor)!=null?hm:"";Ye.style.color=Er||_r.actionIconColor,Ye.innerHTML="";let So=H()?"14px":"20px",Nr=ve(hr,So,"currentColor",2);if(Nr&&Ye.appendChild(Nr),te.backgroundColor?(Ye.style.backgroundColor=te.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let ct=te.borderWidth||"0px",xr=te.borderColor||"transparent";Ye.style.border=`${ct} solid ${xr}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");te.borderRadius?(Ye.style.borderRadius=te.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),te.paddingX?(Ye.style.paddingLeft=te.paddingX,Ye.style.paddingRight=te.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),te.paddingY?(Ye.style.paddingTop=te.paddingY,Ye.style.paddingBottom=te.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let er=(xm=te.tooltipText)!=null?xm:"Clear chat",ro=(ym=te.showTooltip)!=null?ym:!0;if(Ye.setAttribute("aria-label",er),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),ro&&er)){let ct=null,xr=()=>{if(ct||!Ye)return;let Jn=Ye.ownerDocument,gs=Jn.body;if(!gs)return;ct=Vo(Jn,"div","persona-clear-chat-tooltip"),ct.textContent=er;let hs=Vo(Jn,"div");hs.className="persona-clear-chat-tooltip-arrow",ct.appendChild(hs);let Yn=Ye.getBoundingClientRect();ct.style.position="fixed",ct.style.zIndex=String(Hn),ct.style.left=`${Yn.left+Yn.width/2}px`,ct.style.top=`${Yn.top-8}px`,ct.style.transform="translate(-50%, -100%)",gs.appendChild(ct)},zr=()=>{ct&&ct.parentNode&&(ct.parentNode.removeChild(ct),ct=null)};Rt.addEventListener("mouseenter",xr),Rt.addEventListener("mouseleave",zr),Ye.addEventListener("focus",xr),Ye.addEventListener("blur",zr),Rt._cleanupTooltip=()=>{zr(),Rt&&(Rt.removeEventListener("mouseenter",xr),Rt.removeEventListener("mouseleave",zr)),Ye&&(Ye.removeEventListener("focus",xr),Ye.removeEventListener("blur",zr))}}}}let cr=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zs],go=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[fa.message,fa.messageAndClick];T=js({parsers:cr,handlers:go,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),me=rx(o,T,Z),_.updateConfig(o),bn(Je,_.getMessages(),me),ga(),K(),X(_.isStreaming());let to=((bm=o.voiceRecognition)==null?void 0:bm.enabled)===!0,jn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Gn=((Cm=(vm=o.voiceRecognition)==null?void 0:vm.provider)==null?void 0:Cm.type)==="runtype";if(to&&(jn||Gn))if(!z||!Ht){let te=Vx(o.voiceRecognition,o.sendButton);te&&(z=te.micButton,Ht=te.micButtonWrapper,Jt.insertBefore(Ht,Cr),z.addEventListener("click",ci),z.disabled=_.isStreaming())}else{let te=(wm=o.voiceRecognition)!=null?wm:{},Et=(Sm=o.sendButton)!=null?Sm:{},jt=(Am=te.iconName)!=null?Am:"mic",it=(Mm=Et.size)!=null?Mm:"40px",It=(Tm=te.iconSize)!=null?Tm:it,hr=parseFloat(It)||24;z.style.width=It,z.style.height=It,z.style.minWidth=It,z.style.minHeight=It;let Er=(km=(Em=te.iconColor)!=null?Em:Et.textColor)!=null?km:"currentColor";z.innerHTML="";let So=ve(jt,hr,Er,2);So?z.appendChild(So):z.textContent="\u{1F3A4}";let Nr=(Lm=te.backgroundColor)!=null?Lm:Et.backgroundColor;Nr?z.style.backgroundColor=Nr:z.style.backgroundColor="",Er?z.style.color=Er:z.style.color="var(--persona-text, #111827)",te.borderWidth?(z.style.borderWidth=te.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),te.borderColor?z.style.borderColor=te.borderColor:z.style.borderColor="",te.paddingX?(z.style.paddingLeft=te.paddingX,z.style.paddingRight=te.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),te.paddingY?(z.style.paddingTop=te.paddingY,z.style.paddingBottom=te.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let er=Ht==null?void 0:Ht.querySelector(".persona-send-button-tooltip"),ro=(Pm=te.tooltipText)!=null?Pm:"Start voice recognition";if(((Rm=te.showTooltip)!=null?Rm:!1)&&ro)if(er)er.textContent=ro,er.style.display="";else{let xr=document.createElement("div");xr.className="persona-send-button-tooltip",xr.textContent=ro,Ht==null||Ht.insertBefore(xr,z)}else er&&(er.style.display="none");Ht.style.display="",z.disabled=_.isStreaming()}else z&&Ht&&(Ht.style.display="none",((Wm=(Im=o.voiceRecognition)==null?void 0:Im.provider)==null?void 0:Wm.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():_o&&Sn());if(((Hm=o.attachments)==null?void 0:Hm.enabled)===!0)if(!we||!oe){let te=(Bm=o.attachments)!=null?Bm:{},jt=(Fm=((Dm=o.sendButton)!=null?Dm:{}).size)!=null?Fm:"40px";At||(At=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),At.style.display="none",Wt.insertBefore(At,ke)),De||(De=document.createElement("input"),De.type="file",De.accept=((Nm=te.allowedTypes)!=null?Nm:an).join(","),De.multiple=((Om=te.maxFiles)!=null?Om:4)>1,De.style.display="none",De.setAttribute("aria-label","Attach files"),Wt.insertBefore(De,ke)),we=S("div","persona-send-button-wrapper"),oe=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),oe.type="button",oe.setAttribute("aria-label",(_m=te.buttonTooltipText)!=null?_m:"Attach file");let it=(Um=te.buttonIconName)!=null?Um:"paperclip",It=jt,hr=parseFloat(It)||40,Er=Math.round(hr*.6);oe.style.width=It,oe.style.height=It,oe.style.minWidth=It,oe.style.minHeight=It,oe.style.fontSize="18px",oe.style.lineHeight="1",oe.style.backgroundColor="transparent",oe.style.color="var(--persona-primary, #111827)",oe.style.border="none",oe.style.borderRadius="6px",oe.style.transition="background-color 0.15s ease",oe.addEventListener("mouseenter",()=>{oe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),oe.addEventListener("mouseleave",()=>{oe.style.backgroundColor="transparent"});let So=ve(it,Er,"currentColor",1.5);So?oe.appendChild(So):oe.textContent="\u{1F4CE}",oe.addEventListener("click",ro=>{ro.preventDefault(),De==null||De.click()}),we.appendChild(oe);let Nr=(qm=te.buttonTooltipText)!=null?qm:"Attach file",er=S("div","persona-send-button-tooltip");er.textContent=Nr,we.appendChild(er),Gt.append(we),!yt&&De&&At&&(yt=ia.fromConfig(te),yt.setPreviewsContainer(At),De.addEventListener("change",async()=>{yt&&(De!=null&&De.files)&&(await yt.handleFileSelect(De.files),De.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(ox(te.dropOverlay))}else{we.style.display="";let te=(Vm=o.attachments)!=null?Vm:{};De&&(De.accept=(($m=te.allowedTypes)!=null?$m:an).join(","),De.multiple=((zm=te.maxFiles)!=null?zm:4)>1),yt&&yt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else we&&(we.style.display="none"),yt&&yt.clearAttachments(),(jm=pe.querySelector(".persona-attachment-drop-overlay"))==null||jm.remove();let Xt=(Gm=o.sendButton)!=null?Gm:{},Kn=(Km=Xt.useIcon)!=null?Km:!1,Mn=(Xm=Xt.iconText)!=null?Xm:"\u2191",Tn=Xt.iconName,en=(Qm=Xt.tooltipText)!=null?Qm:"Send message",Xn=(Jm=Xt.showTooltip)!=null?Jm:!1,wo=(Ym=Xt.size)!=null?Ym:"40px",rt=Xt.backgroundColor,gr=Xt.textColor;if(Kn){if(je.style.width=wo,je.style.height=wo,je.style.minWidth=wo,je.style.minHeight=wo,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",gr?je.style.color=gr:je.style.color="var(--persona-button-primary-fg, #ffffff)",Tn){let te=parseFloat(wo)||24,Et=(gr==null?void 0:gr.trim())||"currentColor",jt=ve(Tn,te,Et,2);jt?je.appendChild(jt):je.textContent=Mn}else je.textContent=Mn;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rt?(je.style.backgroundColor=rt,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(eg=(Zm=o.copy)==null?void 0:Zm.sendButtonLabel)!=null?eg:"Send",je.style.width="",je.style.height="",je.style.minWidth="",je.style.minHeight="",je.style.fontSize="",je.style.lineHeight="",je.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",rt?(je.style.backgroundColor=rt,je.classList.remove("persona-bg-persona-accent")):je.classList.add("persona-bg-persona-accent"),gr?je.style.color=gr:je.classList.add("persona-text-white");Xt.borderWidth?(je.style.borderWidth=Xt.borderWidth,je.style.borderStyle="solid"):(je.style.borderWidth="",je.style.borderStyle=""),Xt.borderColor?je.style.borderColor=Xt.borderColor:je.style.borderColor="",Xt.paddingX?(je.style.paddingLeft=Xt.paddingX,je.style.paddingRight=Xt.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Xt.paddingY?(je.style.paddingTop=Xt.paddingY,je.style.paddingBottom=Xt.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let Vt=Cr==null?void 0:Cr.querySelector(".persona-send-button-tooltip");if(Xn&&en)if(Vt)Vt.textContent=en,Vt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=en,Cr==null||Cr.insertBefore(te,je)}else Vt&&(Vt.style.display="none");let qt=(ag=(tg=o.layout)==null?void 0:tg.contentMaxWidth)!=null?ag:H()?(ng=(og=(rg=o.launcher)==null?void 0:rg.composerBar)==null?void 0:og.contentMaxWidth)!=null?ng:"720px":void 0;qt?(Je.style.maxWidth=qt,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%",Wt&&(Wt.style.maxWidth=qt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Ge&&(Ge.style.maxWidth=qt,Ge.style.marginLeft="auto",Ge.style.marginRight="auto")):(Je.style.maxWidth="",Je.style.marginLeft="",Je.style.marginRight="",Je.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Ge&&(Ge.style.maxWidth="",Ge.style.marginLeft="",Ge.style.marginRight=""));let ft=(sg=o.statusIndicator)!=null?sg:{},Qt=(ig=ft.visible)!=null?ig:!0;if(ur.style.display=Qt?"":"none",_){let te=_.getStatus();Lt(ur,(jt=>{var it,It,hr,Er;return jt==="idle"?(it=ft.idleText)!=null?it:kr.idle:jt==="connecting"?(It=ft.connectingText)!=null?It:kr.connecting:jt==="connected"?(hr=ft.connectedText)!=null?hr:kr.connected:jt==="error"?(Er=ft.errorText)!=null?Er:kr.error:kr[jt]})(te),ft,te)}ur.classList.remove("persona-text-left","persona-text-center","persona-text-right");let St=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";ur.classList.add(St)},open(){W()&&I(!0,"api")},close(){W()&&I(!1,"api")},toggle(){W()&&I(!k,"api")},clearChat(){Ir=!1,_.clearMessages(),Bo.clear(),No();try{localStorage.removeItem(Ja),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ja}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ja)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}c={},T.syncFromMetadata(),ge==null||ge.clear(),ue==null||ue.reset(),G==null||G.update()},setMessage(l){return!ke||_.isStreaming()?!1:(!k&&W()&&I(!0,"system"),ke.value=l,ke.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let f=(l==null?void 0:l.trim())||ke.value.trim();return f?(!k&&W()&&I(!0,"system"),ke.value="",ke.style.height="auto",_.sendMessage(f),!0):!1},startVoiceRecognition(){var f,h;return _.isStreaming()?!1:((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!k&&W()&&I(!0,"system"),mt.manuallyDeactivated=!1,Vr(),_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("user"),_.isVoiceActive()&&Ma()})),!0):_o?!0:Xp()?(!k&&W()&&I(!0,"system"),mt.manuallyDeactivated=!1,Vr(),li("user"),!0):!1},stopVoiceRecognition(){var l,f;return((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Vr(),po("user"),Zo()}),!0):!1:_o?(mt.manuallyDeactivated=!0,Vr(),Sn("user"),!0):!1},injectMessage(l){return!k&&W()&&I(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!k&&W()&&I(!0,"system");let f=_.injectAssistantMessage(l);return N&&(N=!1,q&&(clearTimeout(q),q=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),f},injectUserMessage(l){return!k&&W()&&I(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!k&&W()&&I(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!k&&W()&&I(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!k&&W()&&I(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!k&&W()&&I(!0,"system"),_.injectTestEvent(l)},async connectStream(l,f){return _.connectStream(l,f)},__pushEventStreamEvent(l){ge&&(ue==null||ue.processEvent(l.type,l.payload),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Ie||!ge||zo()},hideEventStream(){ce&&yo()},isEventStreamVisible(){return ce},showArtifacts(){xo(o)&&(Ir=!1,Jr(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){xo(o)&&(Ir=!0,Jr())},upsertArtifact(l){return xo(o)?(Ir=!1,_.upsertArtifact(l)):null},selectArtifact(l){xo(o)&&_.selectArtifact(l)},clearArtifacts(){xo(o)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return E&&!k&&!H()||!ke?!1:(ke.focus(),!0)},async resolveApproval(l,f,h){let R=_.getMessages().find(F=>{var $;return F.variant==="approval"&&(($=F.approval)==null?void 0:$.id)===l});if(!(R!=null&&R.approval))throw new Error(`Approval not found: ${l}`);if(R.approval.toolType==="webmcp"){_.resolveWebMcpApproval(R.id,f);return}return _.resolveApproval(R.approval,f,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){m(l)},on(l,f){return a.on(l,f)},off(l,f){a.off(l,f)},isOpen(){return W()&&k},isVoiceActive(){return mt.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:W()&&k,launcherEnabled:E,voiceActive:mt.active,streaming:_.isStreaming()}},showCSATFeedback(l){!k&&W()&&I(!0,"system");let f=Je.querySelector(".persona-feedback-container");f&&f.remove();let h=kl({onSubmit:async(v,R)=>{var F;_.isClientTokenMode()&&await _.submitCSATFeedback(v,R),(F=l==null?void 0:l.onSubmit)==null||F.call(l,v,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&W()&&I(!0,"system");let f=Je.querySelector(".persona-feedback-container");f&&f.remove();let h=Ll({onSubmit:async(v,R)=>{var F;_.isClientTokenMode()&&await _.submitNPSFeedback(v,R),(F=l==null?void 0:l.onSubmit)==null||F.call(l,v,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,f){return _.submitCSATFeedback(l,f)},async submitNPSFeedback(l,f){return _.submitNPSFeedback(l,f)},destroy(){Ae!=null&&(clearInterval(Ae),Ae=null),dt.forEach(l=>l()),_e.remove(),Ze==null||Ze.remove(),rr==null||rr.destroy(),mr==null||mr.remove(),Wo&&j.removeEventListener("click",Wo)}};if((((rf=r==null?void 0:r.debugTools)!=null?rf:!1)||!!o.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,f={controller:dr,getMessages:dr.getMessages,getStatus:dr.getStatus,getMetadata:dr.getPersistentMetadata,updateMetadata:dr.updatePersistentMetadata,clearHistory:()=>dr.clearChat(),setVoiceActive:h=>h?dr.startVoiceRecognition():dr.stopVoiceRecognition()};window.AgentWidgetBrowser=f,dt.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.focusInput()};if(window.addEventListener("persona:focusInput",f),dt.push(()=>{window.removeEventListener("persona:focusInput",f)}),Ie){let O=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&dr.showEventStream()},D=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&dr.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",D),dt.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",D)})}let h=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.showArtifacts()},v=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.hideArtifacts()},R=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&dr.upsertArtifact(D.artifact)},F=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&dr.selectArtifact(D.id)},$=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",$),dt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",$)})}let mo=Iv(o.persistState);if(mo&&W()){let l=Wv(mo.storage),f=`${mo.keyPrefix}widget-open`,h=`${mo.keyPrefix}widget-voice`,v=`${mo.keyPrefix}widget-voice-mode`;if(l){let R=((of=mo.persist)==null?void 0:of.openState)&&l.getItem(f)==="true",F=((nf=mo.persist)==null?void 0:nf.voiceState)&&l.getItem(h)==="true",$=((af=mo.persist)==null?void 0:af.voiceState)&&l.getItem(v)==="true";if(R&&setTimeout(()=>{dr.open(),setTimeout(()=>{var O;if(F||$)dr.startVoiceRecognition();else if((O=mo.persist)!=null&&O.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(sf=mo.persist)!=null&&sf.openState&&(a.on("widget:opened",()=>{l.setItem(f,"true")}),a.on("widget:closed",()=>{l.setItem(f,"false")})),(lf=mo.persist)!=null&&lf.voiceState&&(a.on("voice:state",O=>{l.setItem(h,O.active?"true":"false")}),a.on("user:message",O=>{l.setItem(v,O.viaVoice?"true":"false")})),mo.clearOnChatClear){let O=()=>{l.removeItem(f),l.removeItem(h),l.removeItem(v)},D=()=>O();window.addEventListener("persona:clear-chat",D),dt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return u&&W()&&setTimeout(()=>{dr.open()},0),Ve(),Xs||fi().then(()=>{_&&(ha++,Bo.clear(),bn(Je,_.getMessages(),me))}).catch(()=>{}),dr};var Hv=(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},Bv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Dv=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Fv=(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.")},nx=(e,t)=>{var o,n;let r=(n=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?n:!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0"},Bp=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},ax=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Bp(e)},Ip=e=>{e.style.transition=""},Wp=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=""},Hp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Il=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Nv=(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))},Ov=(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)},sx=(e,t,r,o,n,a,s)=>{var x,C,T,E,M,P;let i=no(a),c=i.reveal==="push";Nv(e,t,r,o,c),Ov(e,t,r,o,i.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let d=e.ownerDocument.defaultView,u=(C=(x=a==null?void 0:a.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,g=(E=(T=a==null?void 0:a.launcher)==null?void 0:T.mobileBreakpoint)!=null?E:640,p=d!=null?d.innerWidth<=g:!1;if(u&&p&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Wp(t),Ip(o),ax(o),Hp(r),Il(n,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((P=(M=a==null?void 0:a.launcher)==null?void 0:M.zIndex)!=null?P:Lr),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),ax(o),Bv(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",Wp(t),Ip(o),Hp(r),Il(n,o);let y=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",b=s?"translateX(0)":w;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=y,o.style.transform=b,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Ip(o),Bp(o),Il(n,o);let y=Hv(i.width,e.clientWidth),w=Math.max(0,e.clientWidth),b=i.animate?"margin-left 180ms ease":"none",A=i.side==="right"?s?-y:0:s?0:-y;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${w+y}px`,t.style.transition=b,t.style.marginLeft=`${A}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${w}px`,r.style.maxWidth=`${w}px`,r.style.minWidth=`${w}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Wp(t),Bp(o),Hp(r),Il(n,o);let y=i.reveal==="emerge";y?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let w=s?i.width:"0px",b=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",A=!s;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${w}`,o.style.width=w,o.style.maxWidth=w,o.style.minWidth=w,o.style.minHeight="0",Dv(o,i.maxHeight),o.style.overflow=y||A?"hidden":"visible",o.style.transition=b,y&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.boxSizing="border-box")}},_v=(e,t)=>{let r=e.ownerDocument.createElement("div");return nx(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){nx(r,o)},destroy(){r.remove()}}},Uv=(e,t)=>{var P,y,w,b;let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),c=r.createElement("div"),d=r.createElement("aside"),u=r.createElement("div"),g=(y=(P=t==null?void 0:t.launcher)==null?void 0:P.enabled)==null||y?(b=(w=t==null?void 0:t.launcher)==null?void 0:w.autoExpand)!=null?b:!1:!0;i.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",d.appendChild(u),o.insertBefore(s,e),c.appendChild(e);let p=null,m=()=>{p==null||p.disconnect(),p=null},x=()=>{m(),no(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(p=new ResizeObserver(()=>{sx(s,i,c,d,u,t,g)}),p.observe(s))},C=!1,T=()=>{sx(s,i,c,d,u,t,g),x(),g&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,Fv(s,no(t)))},E=s.ownerDocument.defaultView,M=()=>{T()};return E==null||E.addEventListener("resize",M),no(t).reveal==="push"?(i.appendChild(c),i.appendChild(d),s.appendChild(i)):(s.appendChild(c),s.appendChild(d)),T(),{mode:"docked",host:u,shell:s,syncWidgetState(A){let H=A.launcherEnabled?A.open:!0;g!==H&&(g=H,T())},updateConfig(A){var H,W;t=A,((W=(H=t==null?void 0:t.launcher)==null?void 0:H.enabled)!=null?W:!0)===!1&&(g=!0),T()},destroy(){E==null||E.removeEventListener("resize",M),m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Gs=(e,t)=>pr(t)?Uv(e,t):_v(e,t);var Dp={},ix=!1,qv=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},Vv=()=>{try{if(typeof Dp!="undefined"&&Dp.url)return new URL("../widget.css",Dp.url).href}catch{}return null},lx=(e,t)=>{let r=Vv(),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)}},dx=e=>{let t=qv(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Gs(t,n),s,i=[],c=(T,E)=>{var w,b;let P=!((b=(w=E==null?void 0:E.launcher)==null?void 0:w.enabled)!=null?b:!0)||pr(E),y=o.createElement("div");if(y.setAttribute("data-persona-root","true"),P&&(y.style.height="100%",y.style.display="flex",y.style.flexDirection="column",y.style.flex="1",y.style.minHeight="0"),r){let A=T.attachShadow({mode:"open"});A.appendChild(y),lx(A,o)}else T.appendChild(y),lx(T,o);return t.id&&y.setAttribute("data-persona-instance",t.id),y},d=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},g=()=>{let T=c(a.host,n);s=Rl(T,n,{debugTools:e.debugTools}),u()},p=()=>{i.forEach(T=>T()),i=[],s.destroy()};g(),e.onChatReady?e.onChatReady():e.onReady&&(ix||(ix=!0,console.warn("[Persona] `onReady` is deprecated: use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let m=T=>{p(),a.destroy(),a=Gs(t,T),n=T,g()},x={update(T){var b,A,H,W,k,N;let E={...n,...T,launcher:{...(b=n==null?void 0:n.launcher)!=null?b:{},...(A=T==null?void 0:T.launcher)!=null?A:{},dock:{...(W=(H=n==null?void 0:n.launcher)==null?void 0:H.dock)!=null?W:{},...(N=(k=T==null?void 0:T.launcher)==null?void 0:k.dock)!=null?N:{}}}},M=pr(n),P=pr(E),y=Dn(n),w=Dn(E);if(M!==P||y!==w){m(E);return}n=E,a.updateConfig(n),s.update(T),d()},destroy(){p(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},C=new Proxy(x,{get(T,E,M){if(E==="host")return a.host;if(E in T)return Reflect.get(T,E,M);let P=s[E];return typeof P=="function"?P.bind(s):P}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=C),C};var mx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),$v=new Set(["button","a","input","select","textarea","details","summary"]),zv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Fp=/\b(product|card|item|listing|result)\b/i,Op=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,jv=3e3,Gv=100;function gx(e){let t=typeof e.className=="string"?e.className:"";if(Fp.test(t)||e.id&&Fp.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&Fp.test(o.value))return!0}return!1}function hx(e){var t;return Op.test(((t=e.textContent)!=null?t:"").trim())}function xx(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 Kv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function cx(e){let t=e.match(Op);return t?t[0]:null}function px(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 Xv(e){let t=[],r=o=>{let n=o.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll("button").forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('[role="button"]').forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{var n;r((n=o.value)!=null?n:"")}),t.slice(0,6)}var Qv="commerce-card",Jv="result-card";function ux(e){return!gx(e)||!hx(e)||!xx(e)&&!Kv(e)?0:5200}function fx(e){var o;return!gx(e)||hx(e)||!xx(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 _p=[{id:Qv,scoreElement(e){return ux(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||Op.test(o)&&o.length<32)}return!0},formatSummary(e,t){var c,d,u;if(ux(e)===0)return null;let{title:r,href:o}=px(e),n=(u=(d=cx(((c=e.textContent)!=null?c:"").trim()))!=null?d:cx(t.text))!=null?u:"",a=Xv(e);return[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
111
- `)}},{id:Jv,scoreElement(e){return fx(e)},formatSummary(e,t){if(fx(e)===0)return null;let{title:r,href:o}=px(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
112
- `)}}];function Yv(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Zv(e){var u,g,p,m,x,C,T,E,M,P,y,w,b;let t=(u=e.options)!=null?u:{},r=(p=(g=t.maxElements)!=null?g:e.maxElements)!=null?p:80,o=(x=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",n=(T=(C=t.maxTextLength)!=null?C:e.maxTextLength)!=null?T:200,a=(M=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?M:!0,s=(P=t.root)!=null?P:e.root,i=(y=t.mode)!=null?y:"structured",c=(w=t.maxCandidates)!=null?w:Math.max(500,r*10),d=(b=e.rules)!=null?b:_p;return i==="simple"&&e.rules&&e.rules.length>0?(Yv(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:r,maxCandidates:c,excludeSelector:o,maxTextLength:n,visibleOnly:a,root:s,rules:d}}function Np(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 t0(e){let t=e.tagName.toLowerCase(),r=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||r==="textbox"||r==="combobox"||r==="listbox"||r==="spinbutton"?"input":t==="button"||r==="button"||$v.has(t)||r&&zv.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function yx(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 r0(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let c=e.getAttribute("role");c&&(t.role=c);for(let d=0;d<e.attributes.length;d++){let u=e.attributes[d];u.name.startsWith("data-")&&(t[u.name]=u.value)}return t}function Up(e){let t=e.tagName.toLowerCase();if(e.id){let n=`#${Np(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}="${Np(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=>Np(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 o0(e){return e==="static"?Gv:jv}function bx(e,t){var n;let r=e.tagName.toLowerCase(),o=((n=e.textContent)!=null?n:"").trim().substring(0,t);return{selector:Up(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:t0(e),attributes:r0(e)}}function n0(e,t,r,o){let n=o0(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 a0(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 s0(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,u=d.tagName.toLowerCase();if(mx.has(u)){i=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!yx(d)){i=s.nextNode();continue}let g=bx(d,e.maxTextLength),p=g.text.length>0,m=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(T=>T==="role");if(!p&&!m){i=s.nextNode();continue}if(o.has(g.selector)){i=s.nextNode();continue}o.add(g.selector);let{score:x,formattingRule:C}=n0(d,g,e.rules,r);n.push({el:d,domIndex:a,enriched:g,score:x,formattingRule:C}),a+=1}i=s.nextNode()}n.sort((d,u)=>{let g=d.enriched.interactivity==="static"?1:0,p=u.enriched.interactivity==="static"?1:0;return g!==p?g-p:u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex});let c=[];for(let d of n){if(c.length>=e.maxElements)break;a0(c,d)||c.push(d)}return c.sort((d,u)=>{let g=d.enriched.interactivity==="static"?1:0,p=u.enriched.interactivity==="static"?1:0;return g!==p?g-p:g===1&&u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex}),c.map(d=>{var p;let u;if((p=d.formattingRule)!=null&&p.formatSummary){let m=d.formattingRule.formatSummary(d.el,d.enriched,r);m&&(u=m)}let g={...d.enriched};return u&&(g.formattedSummary=u),g})}function i0(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,d=c.tagName.toLowerCase();if(mx.has(d)){a=n.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!yx(c)){a=n.nextNode();continue}let u=bx(c,e.maxTextLength),g=u.text.length>0,p=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!g&&!p){a=n.nextNode();continue}o.has(u.selector)||(o.add(u.selector),r.push(u))}a=n.nextNode()}let s=[],i=[];for(let c of r)c.interactivity!=="static"?s.push(c):i.push(c);return[...s,...i].slice(0,e.maxElements)}function vx(e={}){var o;let t=Zv(e),r=(o=t.root)!=null?o:document.body;return r?t.mode==="simple"?i0(t,r):s0(t,r):[]}var Wl=100;function Cx(e,t={}){var a;if(e.length===0)return"No page elements found.";let r=(a=t.mode)!=null?a:"structured",o=[];if(r==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
110
+ `}if(!v&&!l){let Vt="max-height: -moz-available !important; max-height: stretch !important;",qt=f?"":"padding-top: 1.25em !important;",ft=f?"":`z-index: ${(gr=(rt=o.launcher)==null?void 0:rt.zIndex)!=null?gr:Lr} !important;`;_e.style.cssText+=Vt+qt+ft}Qe()};xe(),Wn(e,o),wl(e,o),Sl(e,o);let dt=[];dt.push(()=>{document.removeEventListener("keydown",gn)});let tr=null,fr=null;dt.push(()=>{tr==null||tr(),tr=null,fr==null||fr(),fr=null}),Gr&&dt.push(()=>{Gr==null||Gr.disconnect(),Gr=null}),dt.push(()=>{Wr==null||Wr(),Wr=null,Ko(),Nt&&(Nt.remove(),Nt=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Ie&&dt.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),G==null||G.destroy(),G=null,ge==null||ge.destroy(),ge=null,J=null});let Io=null,es=()=>{Io&&(Io(),Io=null),o.colorScheme==="auto"&&(Io=el(()=>{Wn(e,o)}))};es(),dt.push(()=>{Io&&(Io(),Io=null)});let Xo=(Qu=o.features)==null?void 0:Qu.streamAnimation;if(Xo!=null&&Xo.type&&Xo.type!=="none"){let l=Ds(Xo.type,Xo.plugins);l&&(up(l,e),dt.push(()=>wh(e)))}let qn=Nh(Ge),Wo=null,_,ha=l=>{var v,R;if(!_)return;let f=l!=null?l:_.getMessages(),h=((R=(v=o.features)==null?void 0:v.suggestReplies)==null?void 0:R.enabled)!==!1?Ai(f):null;h?qn.render(h,_,ke,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(F=>F.role==="user")?qn.render([],_,ke,f):qn.render(o.suggestionChips,_,ke,f,o.suggestionChipsConfig)},Ho=!1,Bo=fh(),Qo=new Map,Do=new Map,bo=new Map,xa=0,Qs=Ia()!==null,Yr=ol(),Zr=0,vo=null,Co=!1,Vn=!1,Jo=0,Mr=null,Fo=null,ya=!1,$n=!1,ba=null,Js=4,va=24,Ys=80,Ca=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ts=(Yu=(Ju=o.voiceRecognition)==null?void 0:Ju.autoResume)!=null?Yu:!1,po=l=>{a.emit("voice:state",{active:mt.active,source:l,timestamp:Date.now()})},Vr=()=>{m(l=>({...l,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},Zs=()=>{var v,R;if(((v=o.voiceRecognition)==null?void 0:v.enabled)===!1)return;let l=Ip(c.voiceState),f=!!l.active,h=Number((R=l.timestamp)!=null?R:0);mt.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-h<Pv&&setTimeout(()=>{var F,$;mt.active||(mt.manuallyDeactivated=!1,(($=(F=o.voiceRecognition)==null?void 0:F.provider)==null?void 0:$.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("restore"),_.isVoiceActive()&&Ta()}):di("restore"))},1e3)},ei=()=>_?ox(_.getMessages()).filter(l=>!l.__skipPersist):[];function wa(l){if(!(i!=null&&i.save))return;let h={messages:l?ox(l):_?ei():[],metadata:c,artifacts:Kr.artifacts,selectedArtifactId:Kr.selectedId};try{let v=i.save(h);v instanceof Promise&&v.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",v)}}let Yo=null,rs=()=>_e.querySelector("#persona-scroll-container")||Me,yn=()=>{Yo!==null&&(cancelAnimationFrame(Yo),Yo=null),Co=!1},os=()=>{vo!==null&&(cancelAnimationFrame(vo),vo=null),Vn=!1,yn()},ns=()=>{Jo>0?(Rr.textContent=String(Jo),Rr.style.display="",lt.setAttribute("aria-label",`${sr()||"Jump to latest"} (${Jo} new)`)):(Rr.textContent="",Rr.style.display="none",lt.setAttribute("aria-label",sr()||"Jump to latest"))},as=()=>{Jo!==0&&(Jo=0,ns())},ss=()=>ot()==="follow"?!Yr.isFollowing():!da(Me,va),$r=()=>{if(!Ft()||ce){lt.parentNode&&lt.remove(),lt.style.display="none";return}lt.parentNode!==pe&&pe.appendChild(lt),Ur();let f=sn(Me)>0&&ss();f||as(),lt.style.display=f?"":"none"},Sa=()=>{Yr.pause()&&(os(),$r())},No=()=>{Yr.resume(),as(),$r()},Oo=(l=!1)=>{ot()==="follow"&&Yr.isFollowing()&&(!l&&!Ho||(vo!==null&&(cancelAnimationFrame(vo),vo=null),Vn=!0,vo=requestAnimationFrame(()=>{vo=null,Vn=!1,Yr.isFollowing()&&ti(rs(),l?220:140)})))},is=(l,f,h,v=()=>!0)=>{let R=l.scrollTop,F=f(),$=F-R;yn();let O=performance.now();Co=!0;let D=se=>1-Math.pow(1-se,3),ae=se=>{if(!v()){yn();return}let Q=f();Q!==F&&(F=Q,$=F-R);let ye=se-O,He=Math.min(ye/h,1),Se=D(He),nt=R+$*Se;l.scrollTop=nt,Zr=l.scrollTop,He<1?Yo=requestAnimationFrame(ae):(l.scrollTop=F,Zr=l.scrollTop,Yo=null,Co=!1)};Yo=requestAnimationFrame(ae)},ti=(l,f=500)=>{let h=sn(l)-l.scrollTop;if(Math.abs(h)<1){Zr=l.scrollTop;return}if(Math.abs(h)>=Ys){yn(),Co=!0,l.scrollTop=sn(l),Zr=l.scrollTop,Co=!1;return}is(l,()=>sn(l),f,()=>Yr.isFollowing())},ls=()=>{let l=rs();Co=!0,l.scrollTop=sn(l),Zr=l.scrollTop,Co=!1,$r()},ds=l=>{ir.style.height=`${Math.max(0,Math.round(l))}px`,Mr&&(Mr.spacerHeight=Math.max(0,l))},zn=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null),yn(),Mr=null,ir.style.height="0px"},ri=l=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=requestAnimationFrame(()=>{var ae;Fo=null;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Me.querySelector(`[data-message-id="${f}"]`);if(!h)return;let v=0,R=h;for(;R&&R!==Me;)v+=R.offsetTop,R=R.offsetParent;let F=(ae=Mr==null?void 0:Mr.spacerHeight)!=null?ae:0,$=Me.scrollHeight-F,{targetScrollTop:O,spacerHeight:D}=yh({anchorOffsetTop:v,topOffset:Dt(),viewportHeight:Me.clientHeight,contentHeight:$});Mr={initialSpacerHeight:D,contentHeightAtAnchor:$,spacerHeight:D},ds(D),is(Me,()=>O,220)})},oi=()=>{if(ot()==="follow"){if(!Yr.isFollowing()||da(Me,1))return;Oo(!Ho);return}if(Mr&&Mr.initialSpacerHeight>0){let l=Me.scrollHeight-Mr.spacerHeight,f=bh({initialSpacerHeight:Mr.initialSpacerHeight,contentHeightAtAnchor:Mr.contentHeightAtAnchor,currentContentHeight:l});f!==Mr.spacerHeight&&ds(f)}$r()},ni=l=>{let f=ot();f==="follow"?(No(),Oo(!0)):f==="anchor-top"&&ri(l)},ai=l=>{let f=new Map;l.forEach(h=>{let v=Ca.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!v&&h.role==="assistant"&&(a.emit("assistant:message",h),!$n&&ot()!=="anchor-top"&&ss()&&(Jo+=1,ns(),$r())),h.role==="assistant"&&(v!=null&&v.streaming)&&h.streaming===!1&&a.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(v?h.approval.status!=="pending"&&a.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):a.emit("approval:requested",{approval:h.approval,message:h}))}),Ca.clear(),f.forEach((h,v)=>{Ca.set(v,h)})},si=(l,f,h)=>{var st,Le,Ee,ze,Qe,xt;let v=document.createElement("div"),F=(()=>{var Re;let B=n.find(Pe=>Pe.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Re=o.loadingIndicator)!=null&&Re.render)return o.loadingIndicator.render})(),$=(B,Re)=>Re==null?!1:typeof Re=="string"?(B.textContent=Re,!0):(B.appendChild(Re),!0),O=new Set,D=new Set,ae=n.some(B=>B.renderAskUserQuestion),se=[],Q=[],ye=o.enableComponentStreaming!==!1,He=n.some(B=>B.renderApproval)&&o.approval!==!1,Se=[];if(f.forEach(B=>{var Ye,Rt,cr,go,to,jn,Gn,ka,La,Xt,Kn,Mn,Tn,en,Xn,wo;O.add(B.id);let Re=ae&&rn(B),Pe=He&&B.variant==="approval"&&!!B.approval,fe=!Re&&B.role==="assistant"&&!B.variant&&ye&&El(B);if(!Pe&&bo.has(B.id)){let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),bo.delete(B.id)}if(!fe&&Do.has(B.id)){let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),Do.delete(B.id)}let Ut=rn(B)?`:${(Ye=B.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Rt=B.agentMetadata)!=null&&Rt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=uh(B,xa)+Ut,Kt=Re||Pe||fe?null:mh(Bo,B.id,Ot);if(Kt){v.appendChild(Kt.cloneNode(!0)),rn(B)&&((cr=B.toolCall)!=null&&cr.id)&&((go=B.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((to=B.agentMetadata)!=null&&to.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Fa(B,o,Y.composerOverlay));return}let bt=null,zt=n.find(rt=>!!(B.variant==="reasoning"&&rt.renderReasoning||B.variant==="tool"&&rt.renderToolCall||!B.variant&&rt.renderMessage)),eo=(jn=o.layout)==null?void 0:jn.messages;if(rn(B)&&((Gn=B.agentMetadata)==null?void 0:Gn.askUserQuestionAnswered)===!0){Qo.delete(B.id);let rt=l.querySelector(`#wrapper-${B.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(As(B)&&((La=(ka=o.features)==null?void 0:ka.suggestReplies)==null?void 0:La.enabled)!==!1)return;if(rn(B)&&((Kn=(Xt=o.features)==null?void 0:Xt.askUserQuestion)==null?void 0:Kn.enabled)!==!1){let rt=n.find(gr=>typeof gr.renderAskUserQuestion=="function");if(rt&&Mt.current){let gr=Qo.get(B.id),Vt=gr!==Ot,qt=null;if(Vt){let{payload:St,complete:Tr}=on(B),Br=B.id,Uo=()=>{var vr;return(vr=Mt.current)==null?void 0:vr.getMessages().find(Dr=>Dr.id===Br)};qt=rt.renderAskUserQuestion({message:B,payload:St,complete:Tr,resolve:vr=>{var Fr;let Dr=Uo();Dr&&((Fr=Mt.current)==null||Fr.resolveAskUserQuestion(Dr,vr))},dismiss:()=>{var Dr,Fr,Qn;let vr=Uo();(Dr=vr==null?void 0:vr.agentMetadata)!=null&&Dr.awaitingLocalTool&&((Fr=Mt.current)==null||Fr.markAskUserQuestionResolved(vr),(Qn=Mt.current)==null||Qn.resolveAskUserQuestion(vr,"(dismissed)"))},config:o})}let ft=gr!=null;if(Vt&&qt===null&&!ft){((Mn=B.agentMetadata)==null?void 0:Mn.awaitingLocalTool)===!0&&!((Tn=B.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Fa(B,o,Y.composerOverlay));return}let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-ask-plugin-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),v.appendChild(Qt),se.push({messageId:B.id,fingerprint:Ot,bubble:qt});return}else{((en=B.agentMetadata)==null?void 0:en.awaitingLocalTool)===!0&&!((Xn=B.agentMetadata)!=null&&Xn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),Fa(B,o,Y.composerOverlay));return}}else if(Pe){let rt=n.find(ft=>typeof ft.renderApproval=="function"),Vt=bo.get(B.id)!==Ot,qt=null;if(Vt&&(rt!=null&&rt.renderApproval)){let ft=B.id,Qt=(St,Tr)=>{var Uo,vr,Dr;let Br=(Uo=Mt.current)==null?void 0:Uo.getMessages().find(Fr=>Fr.id===ft);Br!=null&&Br.approval&&(Br.approval.toolType==="webmcp"?(vr=Mt.current)==null||vr.resolveWebMcpApproval(Br.id,St):(Dr=Mt.current)==null||Dr.resolveApproval(Br.approval,St,Tr))};qt=rt.renderApproval({message:B,defaultRenderer:()=>vl(B,o),config:o,approve:St=>Qt("approved",St),deny:St=>Qt("denied",St)})}if(Vt&&qt===null){let ft=l.querySelector(`#wrapper-${B.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),bo.delete(B.id),bt=vl(B,o)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${B.id}`,ft.setAttribute("data-wrapper-id",B.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),v.appendChild(ft),Se.push({messageId:B.id,fingerprint:Ot,bubble:qt});return}}else if(zt)if(B.variant==="reasoning"&&B.reasoning&&zt.renderReasoning){if(!Ke)return;bt=zt.renderReasoning({message:B,defaultRenderer:()=>Ap(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&zt.renderToolCall){if(!Ce)return;bt=zt.renderToolCall({message:B,defaultRenderer:()=>Mp(B,o),config:o})}else zt.renderMessage&&(bt=zt.renderMessage({message:B,defaultRenderer:()=>{let rt=Ga(B,h,eo,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o});return B.role!=="user"&&Lp(rt,B,o,_),rt},config:o}));if(!bt&&fe){let rt=kl(B);if(rt){let gr=Do.get(B.id),Vt=gr!==Ot,qt=o.wrapComponentDirectiveInBubble!==!1,ft=null;if(Vt){let Qt=Tl(rt,{config:o,message:B,transform:h});if(Qt)if(qt){let St=document.createElement("div");if(St.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),St.id=`bubble-${B.id}`,St.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let Tr=document.createElement("div");Tr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Tr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),St.appendChild(Tr)}St.appendChild(Qt),ft=St}else{let St=document.createElement("div");if(St.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",St.id=`bubble-${B.id}`,St.setAttribute("data-message-id",B.id),St.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let Tr=document.createElement("div");Tr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Tr.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),St.appendChild(Tr)}St.appendChild(Qt),ft=St}}if(ft||gr!=null){let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-component-directive-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),qt||Qt.classList.add("persona-w-full"),v.appendChild(Qt),Q.push({messageId:B.id,fingerprint:Ot,bubble:ft});return}}}if(!bt)if(B.variant==="reasoning"&&B.reasoning){if(!Ke)return;bt=Ap(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!Ce)return;bt=Mp(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;bt=vl(B,o)}else{let rt=(wo=o.layout)==null?void 0:wo.messages;rt!=null&&rt.renderUserMessage&&B.role==="user"?bt=rt.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):rt!=null&&rt.renderAssistantMessage&&B.role==="assistant"?bt=rt.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):bt=Ga(B,h,rt,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o}),B.role!=="user"&&bt&&Lp(bt,B,o,_)}let or=document.createElement("div");or.className="persona-flex",or.id=`wrapper-${B.id}`,or.setAttribute("data-wrapper-id",B.id),B.role==="user"&&or.classList.add("persona-justify-end"),(bt==null?void 0:bt.getAttribute("data-persona-component-directive"))==="true"&&or.classList.add("persona-w-full"),or.appendChild(bt),gh(Bo,B.id,Ot,or),v.appendChild(or)}),Y.composerOverlay&&Y.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Pe=Re.getAttribute("data-persona-ask-sheet-for");Pe&&!D.has(Pe)&&Ln(Y.composerOverlay,Pe)}),(Le=(st=o.features)==null?void 0:st.toolCallDisplay)!=null&&Le.grouped){let B=[],Re=[];f.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ce){Re.push(Pe);return}Re.length>1&&B.push(Re),Re=[]}),Re.length>1&&B.push(Re),B.forEach((Pe,fe)=>{var Ye,Rt;let Ut=Pe.map(cr=>Array.from(v.children).find(go=>go instanceof HTMLElement&&go.getAttribute("data-wrapper-id")===cr.id)).filter(cr=>!!cr);if(Ut.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${fe}-${Pe[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${fe}-${Pe[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let bt=document.createElement("div");bt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Pe.length} tools`,eo=(Rt=(Ye=o.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Rt.call(Ye,{messages:Pe,toolCalls:Pe.map(cr=>cr.toolCall).filter(cr=>!!cr),defaultSummary:zt,config:o});$(bt,eo)||(bt.textContent=zt);let or=document.createElement("div");or.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(bt,or),Ot.appendChild(Kt),Ut[0].before(Ot),Ut.forEach((cr,go)=>{let to=document.createElement("div");to.className="persona-tool-group-item persona-relative",to.setAttribute("data-persona-tool-group-item","true"),go<Ut.length-1&&to.setAttribute("data-persona-tool-group-connector","true"),to.appendChild(cr),or.appendChild(to)})})}hh(Bo,O);let nt=f.some(B=>B.role==="assistant"&&B.streaming),$e=f[f.length-1],ut=($e==null?void 0:$e.role)==="assistant"&&!$e.streaming&&$e.variant!=="approval";if(Ho&&f.some(B=>B.role==="user")&&!nt&&!ut){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ua},Re=n.find(fe=>fe.renderLoadingIndicator),Pe=null;if(Re!=null&&Re.renderLoadingIndicator&&(Pe=Re.renderLoadingIndicator(B)),Pe===null&&((Ee=o.loadingIndicator)!=null&&Ee.render)&&(Pe=o.loadingIndicator.render(B)),Pe===null&&(Pe=ua()),Pe){let fe=document.createElement("div"),Ut=((ze=o.loadingIndicator)==null?void 0:ze.showBubble)!==!1;fe.className=Ut?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Pe);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(fe),v.appendChild(Ot)}}if(!Ho&&f.length>0){let B=f[f.length-1],Re={config:o,lastMessage:B,messageCount:f.length},Pe=n.find(Ut=>Ut.renderIdleIndicator),fe=null;if(Pe!=null&&Pe.renderIdleIndicator&&(fe=Pe.renderIdleIndicator(Re)),fe===null&&((Qe=o.loadingIndicator)!=null&&Qe.renderIdle)&&(fe=o.loadingIndicator.renderIdle(Re)),fe){let Ut=document.createElement("div"),Ot=((xt=o.loadingIndicator)==null?void 0:xt.showBubble)!==!1;Ut.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ut.setAttribute("data-idle-indicator","true"),Ut.appendChild(fe);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Ut),v.appendChild(Kt)}}if(tl(l,v),se.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of se){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),Qo.set(B,Re))}if(Qo.size>0)for(let B of Qo.keys())O.has(B)||Qo.delete(B);if(Q.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of Q){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),Do.set(B,Re))}if(Do.size>0)for(let B of Do.keys())O.has(B)||Do.delete(B);if(Se.length>0)for(let{messageId:B,fingerprint:Re,bubble:Pe}of Se){let fe=l.querySelector(`#wrapper-${B}`);fe&&Pe!==null&&(fe.replaceChildren(Pe),fe.setAttribute("data-bubble-fp",Re),bo.set(B,Re))}if(bo.size>0)for(let B of bo.keys())O.has(B)||bo.delete(B)},bn=(l,f,h)=>{si(l,f,h),fn()},vn=null,ii=()=>{var h;if(vn)return;let l=v=>{let R=v.composedPath();R.includes(_e)||Ze&&R.includes(Ze)||I(!1,"user")};vn=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},cs=()=>{var f;if(!vn)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",vn,!0),vn=null};dt.push(()=>cs());let Cn=null,li=()=>{var h;if(Cn)return;let l=v=>{v.key==="Escape"&&(v.isComposing||I(!1,"user"))};Cn=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},ps=()=>{var f;if(!Cn)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Cn,!0),Cn=null};dt.push(()=>ps());let wn=!1,us=new Set,Aa=()=>{var f,h,v,R;let l=(v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:v.streamAnimation;return l||((R=o.features)==null?void 0:R.streamAnimation)},Ve=()=>{var ut,st,Le,Ee;if(!H())return;let l=Y.peekBanner,f=Y.peekTextNode;if(!l||!f)return;if(k){l.classList.remove("persona-pill-peek--visible");return}let h=(ut=_==null?void 0:_.getMessages())!=null?ut:[],v;for(let ze=h.length-1;ze>=0;ze--){let Qe=h[ze];if(Qe.role==="assistant"&&Qe.content){v=Qe;break}}if(!v){l.classList.remove("persona-pill-peek--visible");return}let R=v.content,F=!!v.streaming,$=Aa(),O=sl($),D=O.type!=="none"?Ds(O.type,$==null?void 0:$.plugins):null,ae=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,v))===!0,se=D!==null&&(F||ae);se&&D&&!us.has(D.name)&&(up(D,e),us.add(D.name));let Q=se&&(D!=null&&D.containerClass)?D.containerClass:null,ye=(Le=f.dataset.personaPeekStreamClass)!=null?Le:null;ye&&ye!==Q&&(f.classList.remove(ye),delete f.dataset.personaPeekStreamClass),Q&&ye!==Q&&(f.classList.add(Q),f.dataset.personaPeekStreamClass=Q),se?(f.style.setProperty("--persona-stream-step",`${O.speed}ms`),f.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let He=se?il(R,O.buffer,D,v,F):R;if(se&&O.placeholder==="skeleton"&&F&&(!He||!He.trim())){let ze=document.createElement("div"),Qe=Ns();Qe.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Qe),tl(f,ze)}else{let ze=Math.max(0,He.length-100),Qe=He.length>100?He.slice(-100):He,xt=qo(Qe);if(!se||!D){let B=He.length>100?`\u2026${Qe}`:Qe;f.textContent!==B&&(f.textContent=B)}else{let B=xt;(D.wrap==="char"||D.wrap==="word")&&(B=Fs(xt,D.wrap,`peek-${v.id}`,{skipTags:D.skipTags,startIndex:ze}));let Re=document.createElement("div");if(Re.innerHTML=B,D.useCaret&&Qe.length>0){let Pe=ll(),fe=Re.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ut=fe[fe.length-1];Ut!=null&&Ut.parentNode?Ut.parentNode.insertBefore(Pe,Ut.nextSibling):Re.appendChild(Pe)}tl(f,Re),(Ee=D.onAfterRender)==null||Ee.call(D,{container:f,bubble:l,messageId:v.id,message:v,speed:O.speed,duration:O.duration})}}let $e=Ho||wn;l.classList.toggle("persona-pill-peek--visible",$e)};if(H()){let l=Y.peekBanner;if(l){let v=R=>{R.preventDefault(),R.stopPropagation(),I(!0,"user")};l.addEventListener("pointerdown",v),dt.push(()=>{l.removeEventListener("pointerdown",v)})}let f=()=>{wn||(wn=!0,Ve())},h=()=>{wn&&(wn=!1,Ve())};be.addEventListener("pointerenter",f),be.addEventListener("pointerleave",h),dt.push(()=>{be.removeEventListener("pointerenter",f),be.removeEventListener("pointerleave",h)}),Ze&&(Ze.addEventListener("pointerenter",f),Ze.addEventListener("pointerleave",h),dt.push(()=>{Ze.removeEventListener("pointerenter",f),Ze.removeEventListener("pointerleave",h)}))}let L=l=>{var ye,He,Se,nt,$e,ut,st,Le;let f=(He=(ye=o.launcher)==null?void 0:ye.composerBar)!=null?He:{},h=(Se=f.expandedSize)!=null?Se:"anchored",v=(nt=f.bottomOffset)!=null?nt:"16px",R=f.collapsedMaxWidth,F=($e=f.expandedMaxWidth)!=null?$e:"880px",$=(ut=f.expandedTopOffset)!=null?ut:"5vh",O=(st=f.modalMaxWidth)!=null?st:"880px",D=(Le=f.modalMaxHeight)!=null?Le:"min(90vh, 800px)",ae="calc(100vw - 32px)",se="var(--persona-pill-area-height, 80px)",Q=_e.style;if(Q.left="",Q.right="",Q.top="",Q.bottom="",Q.transform="",Q.width="",Q.maxWidth="",Q.height="",Q.maxHeight="",Ze){let Ee=Ze.style;Ee.bottom=v,Ee.width=R!=null?R:""}if(l&&h!=="fullscreen"){if(h==="modal"){Q.top="50%",Q.left="50%",Q.transform="translate(-50%, -50%)",Q.bottom="auto",Q.right="auto",Q.width=O,Q.maxWidth=ae,Q.maxHeight=D,Q.height=D;return}Q.left="50%",Q.transform="translateX(-50%)",Q.bottom=`calc(${v} + ${se})`,Q.top=$,Q.width=F,Q.maxWidth=ae}},U=()=>{var D,ae,se,Q,ye,He,Se,nt;if(!W())return;if(H()){let ut=(se=((ae=(D=o.launcher)==null?void 0:D.composerBar)!=null?ae:{}).expandedSize)!=null?se:"anchored",st=k?"expanded":"collapsed";_e.dataset.state=st,_e.dataset.expandedSize=ut,Ze&&(Ze.dataset.state=st,Ze.dataset.expandedSize=ut),_e.style.removeProperty("display"),_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),L(k),pe.style.display=k?"flex":"none",xe(),k?(ii(),li()):(cs(),ps()),Ve();return}let l=pr(o),f=(Q=e.ownerDocument.defaultView)!=null?Q:window,h=(He=(ye=o.launcher)==null?void 0:ye.mobileBreakpoint)!=null?He:640,v=(nt=(Se=o.launcher)==null?void 0:Se.mobileFullscreen)!=null?nt:!0,R=f.innerWidth<=h,F=v&&R&&E,$=no(o).reveal;k?(_e.style.removeProperty("display"),_e.style.display=l?"flex":"",_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0"),be.classList.add("persona-scale-100","persona-opacity-100"),rr?rr.element.style.display="none":mr&&(mr.style.display="none")):(l?l&&($==="overlay"||$==="push")&&!F?(_e.style.removeProperty("display"),_e.style.display="flex",_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(_e.style.setProperty("display","none","important"),_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(_e.style.display="",_e.classList.add("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100"),be.classList.add("persona-scale-95","persona-opacity-0")),rr?rr.element.style.display=l?"none":"":mr&&(mr.style.display=l?"none":""))},I=(l,f="user")=>{var F,$;if(!W()||k===l)return;let h=k;k=l,U();let v=(()=>{var Se,nt,$e,ut,st,Le,Ee,ze,Qe,xt;let O=(nt=(Se=o.launcher)==null?void 0:Se.sidebarMode)!=null?nt:!1,D=($e=e.ownerDocument.defaultView)!=null?$e:window,ae=(st=(ut=o.launcher)==null?void 0:ut.mobileFullscreen)!=null?st:!0,se=(Ee=(Le=o.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Ee:640,Q=D.innerWidth<=se,ye=pr(o)&&ae&&Q,He=H()&&((xt=(Qe=(ze=o.launcher)==null?void 0:ze.composerBar)==null?void 0:Qe.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return O||ae&&Q&&E||ye||He})();if(k&&v){if(!tr){let O=e.getRootNode(),D=O instanceof ShadowRoot?O.host:e.closest(".persona-host");D&&(tr=fp(D,($=(F=o.launcher)==null?void 0:F.zIndex)!=null?$:Lr))}fr||(fr=mp(e.ownerDocument))}else k||(tr==null||tr(),tr=null,fr==null||fr(),fr=null);k&&(fs(),ot()==="follow"?Oo(!0):ls());let R={open:k,source:f,timestamp:Date.now()};k&&!h?a.emit("widget:opened",R):!k&&h&&a.emit("widget:closed",R),a.emit("widget:state",{open:k,launcherEnabled:E,voiceActive:mt.active,streaming:_.isStreaming()})},X=l=>{Pr(l?"stop":"send"),z&&(z.disabled=l),qn.buttons.forEach(f=>{f.disabled=l}),Ne.dataset.personaComposerStreaming=l?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},re=()=>{mt.active||ke&&ke.focus()};a.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>re(),200)});let K=()=>{var h,v,R,F,$,O,D,ae,se,Q,ye;Eo.textContent=(v=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?v:"Hello \u{1F44B}",V.textContent=(F=(R=o.copy)==null?void 0:R.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",ke.placeholder=(O=($=o.copy)==null?void 0:$.inputPlaceholder)!=null?O:"How can I help...";let l=Me.querySelector("[data-persona-intro-card]");if(l){let He=((D=o.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=He?"":"none",He?(Me.classList.remove("persona-gap-3"),Me.classList.add("persona-gap-6")):(Me.classList.remove("persona-gap-6"),Me.classList.add("persona-gap-3"))}!((se=(ae=o.sendButton)==null?void 0:ae.useIcon)!=null&&se)&&!(_!=null&&_.isStreaming())&&(je.textContent=(ye=(Q=o.copy)==null?void 0:Q.sendButtonLabel)!=null?ye:"Send"),ke.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ke.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{m(f=>({...f,sessionId:l}))}});let Ae=null,Oe=()=>{Ae==null&&(Ae=setInterval(()=>{let l=Je.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Ae),Ae=null;return}let f=Date.now();l.forEach(h=>{let v=Number(h.getAttribute("data-tool-elapsed"));v&&(h.textContent=Ti(f-v))})},100))};_=new Ua(o,{onMessagesChanged(l){var v;bn(Je,l,me),Oe(),ha(l),Oo(!Ho),ai(l);let f=[...l].reverse().find(R=>R.role==="user");l.length===0&&zn(),!ya||$n?(ya=!0,ba=(v=f==null?void 0:f.id)!=null?v:null):f&&f.id!==ba&&(ba=f.id,ni(f.id));let h=mt.lastUserMessageId;f&&f.id!==h&&(mt.lastUserMessageId=f.id,a.emit("user:message",f)),mt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),wa(l),Ve()},onStatusChanged(l){var v;let f=(v=o.statusIndicator)!=null?v:{};Lt(ur,(R=>{var F,$,O,D;return R==="idle"?(F=f.idleText)!=null?F:kr.idle:R==="connecting"?($=f.connectingText)!=null?$:kr.connecting:R==="connected"?(O=f.connectedText)!=null?O:kr.connected:R==="error"?(D=f.errorText)!=null?D:kr.error:kr[R]})(l),f,l)},onStreamingChanged(l){Ho=l,X(l),_&&bn(Je,_.getMessages(),me),l||Oo(!0),Ve()},onVoiceStatusChanged(l){var f,h;if(a.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Zo(),Ta();break;case"processing":Zo(),$x();break;case"speaking":Zo(),zx();break;default:l==="idle"&&_.isBargeInActive()?(Zo(),Ta(),z==null||z.setAttribute("aria-label","End voice session")):(mt.active=!1,Zo(),po("system"),Vr());break}},onArtifactsState(l){Kr=l,Jr(),wa()}}),Mt.current=_;let at=null;if(_.onReadAloudChange((l,f)=>{var R;pn=l,un=f,fn();let h=l!=null?l:at;l&&(at=l);let v=h&&(R=_.getMessages().find(F=>F.id===h))!=null?R:null;a.emit("message:read-aloud",{messageId:h,message:v,state:f,timestamp:Date.now()}),f==="idle"&&(at=null)}),ya=!0,((ef=(Zu=o.voiceRecognition)==null?void 0:Zu.provider)==null?void 0:ef.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&_.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(ge||o.onSSEEvent)&&_.setSSEEventCallback((l,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,l,f),ue==null||ue.processEvent(l,f),ge==null||ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(f)})}),d&&d.then(l=>{var f,h,v;if(l){if(l.metadata&&(c=Ip(l.metadata),T.syncFromMetadata()),(f=l.messages)!=null&&f.length){$n=!0;try{_.hydrateMessages(l.messages)}finally{$n=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(v=l.selectedArtifactId)!=null?v:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let tt=()=>{var f,h,v;!H()||k||!((v=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||v)||I(!0,"auto")},Bt=l=>{var R;if(l.preventDefault(),_.isStreaming()){_.cancel(),ue==null||ue.reset(),G==null||G.update();return}let f=ke.value.trim(),h=(R=yt==null?void 0:yt.hasAttachments())!=null?R:!1;if(!f&&!h)return;tt();let v;h&&(v=[],v.push(...yt.getContentParts()),f&&v.push(ks(f))),ke.value="",ke.style.height="auto",Tt(),_.sendMessage(f,{contentParts:v}),h&&yt.clearAttachments()},$t=()=>{var l;return((l=o.features)==null?void 0:l.composerHistory)!==!1},lr={...rl},wt=!1,Tt=()=>{lr={...rl}},br=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var f;return(f=l.content)!=null?f:""}).filter(l=>l.length>0),Hr=l=>{if(!ke)return;wt=!0,ke.value=l,ke.dispatchEvent(new Event("input",{bubbles:!0})),wt=!1;let f=ke.value.length;ke.setSelectionRange(f,f)},Sr=()=>{wt||Tt()},Zt=l=>{if(ke){if($t()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=ke.selectionStart===0&&ke.selectionEnd===0,h=ph({direction:l.key==="ArrowUp"?"up":"down",history:br(),currentValue:ke.value,atStart:f,state:lr});if(lr=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Hr(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Tt(),l.preventDefault(),je.click()}}},uo=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(pe)&&(_.cancel(),ue==null||ue.reset(),G==null||G.update(),Tt(),l.preventDefault(),l.stopImmediatePropagation())},Xp=async l=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!yt)return;let f=Iv(l.clipboardData);f.length!==0&&(l.preventDefault(),await yt.handleFiles(f))},fo=null,_o=!1,Ma=null,pt=null,Qp=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,di=(l="user")=>{var F,$,O,D,ae,se,Q;if(_o||_.isStreaming())return;let f=Qp();if(!f)return;fo=new f;let v=($=((F=o.voiceRecognition)!=null?F:{}).pauseDuration)!=null?$:2e3;fo.continuous=!0,fo.interimResults=!0,fo.lang="en-US";let R=ke.value;fo.onresult=ye=>{let He="",Se="";for(let $e=0;$e<ye.results.length;$e++){let ut=ye.results[$e],st=ut[0].transcript;ut.isFinal?He+=st+" ":Se=st}let nt=R+He+Se;ke.value=nt,Ma&&clearTimeout(Ma),(He||Se)&&(Ma=window.setTimeout(()=>{let $e=ke.value.trim();$e&&fo&&_o&&(Sn(),ke.value="",ke.style.height="auto",_.sendMessage($e,{viaVoice:!0}))},v))},fo.onerror=ye=>{ye.error!=="no-speech"&&Sn()},fo.onend=()=>{if(_o){let ye=ke.value.trim();ye&&ye!==R.trim()&&(ke.value="",ke.style.height="auto",_.sendMessage(ye,{viaVoice:!0})),Sn()}};try{if(fo.start(),_o=!0,mt.active=!0,l!=="system"&&(mt.manuallyDeactivated=!1),po(l),Vr(),z){let ye=(O=o.voiceRecognition)!=null?O:{};pt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(D=ye.iconName)!=null?D:"mic",iconSize:parseFloat((Q=(se=ye.iconSize)!=null?se:(ae=o.sendButton)==null?void 0:ae.size)!=null?Q:"40")||24};let He=ye.recordingBackgroundColor,Se=ye.recordingIconColor,nt=ye.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=He!=null?He:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let $e=z.querySelector("svg");$e&&$e.setAttribute("stroke",Se)}nt&&(z.style.borderColor=nt),z.setAttribute("aria-label","Stop voice recognition")}}catch{Sn("system")}},Sn=(l="user")=>{if(_o){if(_o=!1,Ma&&(clearTimeout(Ma),Ma=null),fo){try{fo.stop()}catch{}fo=null}if(mt.active=!1,po(l),Vr(),z){if(z.classList.remove("persona-voice-recording"),pt){z.style.backgroundColor=pt.backgroundColor,z.style.color=pt.color,z.style.borderColor=pt.borderColor;let f=z.querySelector("svg");f&&f.setAttribute("stroke",pt.color||"currentColor"),pt=null}z.setAttribute("aria-label","Start voice recognition")}}},Vx=(l,f)=>{var st,Le,Ee,ze,Qe,xt,B,Re,Pe;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),v=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",R=((Le=l==null?void 0:l.provider)==null?void 0:Le.type)==="custom";if(!(h||v||R))return null;let $=S("div","persona-send-button-wrapper"),O=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let D=(Ee=l==null?void 0:l.iconName)!=null?Ee:"mic",ae=(ze=f==null?void 0:f.size)!=null?ze:"40px",se=(Qe=l==null?void 0:l.iconSize)!=null?Qe:ae,Q=parseFloat(se)||24,ye=(xt=l==null?void 0:l.backgroundColor)!=null?xt:f==null?void 0:f.backgroundColor,He=(B=l==null?void 0:l.iconColor)!=null?B:f==null?void 0:f.textColor;O.style.width=se,O.style.height=se,O.style.minWidth=se,O.style.minHeight=se,O.style.fontSize="18px",O.style.lineHeight="1",He?O.style.color=He:O.style.color="var(--persona-text, #111827)";let nt=ve(D,Q,He||"currentColor",1.5);nt?O.appendChild(nt):O.textContent="\u{1F3A4}",ye?O.style.backgroundColor=ye:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),$.appendChild(O);let $e=(Re=l==null?void 0:l.tooltipText)!=null?Re:"Start voice recognition";if(((Pe=l==null?void 0:l.showTooltip)!=null?Pe:!1)&&$e){let fe=S("div","persona-send-button-tooltip");fe.textContent=$e,$.appendChild(fe)}return{micButton:O,micButtonWrapper:$}},Bl=()=>{var f,h,v,R,F;if(!z||pt)return;let l=(f=o.voiceRecognition)!=null?f:{};pt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((F=(R=l.iconSize)!=null?R:(v=o.sendButton)==null?void 0:v.size)!=null?F:"40")||24}},Dl=(l,f)=>{var F,$,O,D,ae;if(!z)return;let h=z.querySelector("svg");h&&h.remove();let v=(ae=pt==null?void 0:pt.iconSize)!=null?ae:parseFloat((D=(O=(F=o.voiceRecognition)==null?void 0:F.iconSize)!=null?O:($=o.sendButton)==null?void 0:$.size)!=null?D:"40")||24,R=ve(l,v,f,1.5);R&&z.appendChild(R)},ci=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ta=()=>{var R;if(!z)return;Bl();let l=(R=o.voiceRecognition)!=null?R:{},f=l.recordingBackgroundColor,h=l.recordingIconColor,v=l.recordingBorderColor;if(ci(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let F=z.querySelector("svg");F&&F.setAttribute("stroke",h)}v&&(z.style.borderColor=v),z.setAttribute("aria-label","Stop voice recognition")},$x=()=>{var O,D,ae,se,Q,ye,He,Se;if(!z)return;Bl();let l=(O=o.voiceRecognition)!=null?O:{},f=_.getVoiceInterruptionMode(),h=(D=l.processingIconName)!=null?D:"loader",v=(se=(ae=l.processingIconColor)!=null?ae:pt==null?void 0:pt.color)!=null?se:"",R=(ye=(Q=l.processingBackgroundColor)!=null?Q:pt==null?void 0:pt.backgroundColor)!=null?ye:"",F=(Se=(He=l.processingBorderColor)!=null?He:pt==null?void 0:pt.borderColor)!=null?Se:"";ci(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=R,z.style.borderColor=F;let $=v||"currentColor";z.style.color=$,Dl(h,$),z.setAttribute("aria-label","Processing voice input"),f==="none"&&(z.style.cursor="default")},zx=()=>{var ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee;if(!z)return;Bl();let l=(ae=o.voiceRecognition)!=null?ae:{},f=_.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",v=(se=l.speakingIconName)!=null?se:h,R=(Se=l.speakingIconColor)!=null?Se:f==="barge-in"?(ye=(Q=l.recordingIconColor)!=null?Q:pt==null?void 0:pt.color)!=null?ye:"":(He=pt==null?void 0:pt.color)!=null?He:"",F=(ut=l.speakingBackgroundColor)!=null?ut:f==="barge-in"?(nt=l.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":($e=pt==null?void 0:pt.backgroundColor)!=null?$e:"",$=(Ee=l.speakingBorderColor)!=null?Ee:f==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Le=pt==null?void 0:pt.borderColor)!=null?Le:"";ci(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=F,z.style.borderColor=$;let O=R||"currentColor";z.style.color=O,Dl(v,O);let D=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",D),f==="none"&&(z.style.cursor="default"),f==="barge-in"&&z.classList.add("persona-voice-recording")},Zo=()=>{var l,f,h;z&&(ci(),pt&&(z.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",z.style.color=(f=pt.color)!=null?f:"",z.style.borderColor=(h=pt.borderColor)!=null?h:"",Dl(pt.iconName,pt.color||"currentColor"),pt=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},pi=()=>{var l,f;if(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"){let h=_.getVoiceStatus(),v=_.getVoiceInterruptionMode();if(v==="none"&&(h==="processing"||h==="speaking"))return;if(v==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Vr(),po("user"),Zo()});return}_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),mt.manuallyDeactivated=!_.isVoiceActive(),Vr(),po("user"),_.isVoiceActive()?Ta():Zo()});return}if(_o){let h=ke.value.trim();mt.manuallyDeactivated=!0,Vr(),Sn("user"),h&&(ke.value="",ke.style.height="auto",_.sendMessage(h))}else mt.manuallyDeactivated=!1,Vr(),di("user")};jr=pi,z&&(z.addEventListener("click",pi),dt.push(()=>{var l,f;((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Zo()):Sn("system"),z&&z.removeEventListener("click",pi)}));let jx=a.on("assistant:complete",()=>{ts&&(mt.active||mt.manuallyDeactivated||ts==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var l,f;!mt.active&&!mt.manuallyDeactivated&&(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("auto"),_.isVoiceActive()&&Ta()}):di("auto"))},600))});dt.push(jx);let Gx=a.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(Gx);let Jp=()=>{I(!k,"user")},rr=null,mr=null;if(E&&!H()){let{instance:l,element:f}=bp({config:o,plugins:n,onToggle:Jp});rr=l,l||(mr=f)}rr?e.appendChild(rr.element):mr&&e.appendChild(mr),U(),ha(),K(),X(_.isStreaming()),ot()==="follow"?Oo(!0):ls(),Zs(),P&&(!E||H()?setTimeout(()=>re(),0):k&&setTimeout(()=>re(),200));let fs=()=>{var D,ae,se,Q,ye,He,Se,nt,$e,ut,st,Le,Ee,ze,Qe,xt,B,Re,Pe,fe,Ut,Ot;if(H()){Ur(),U();return}let l=pr(o),f=(ae=(D=o.launcher)==null?void 0:D.sidebarMode)!=null?ae:!1,h=l||f||((Q=(se=o.launcher)==null?void 0:se.fullHeight)!=null?Q:!1),v=(ye=e.ownerDocument.defaultView)!=null?ye:window,R=(Se=(He=o.launcher)==null?void 0:He.mobileFullscreen)!=null?Se:!0,F=($e=(nt=o.launcher)==null?void 0:nt.mobileBreakpoint)!=null?$e:640,$=v.innerWidth<=F,O=R&&$&&E;try{if(O){xe(),Wn(e,o);return}if(A&&(A=!1,xe(),Wn(e,o)),!E&&!l){be.style.height="",be.style.width="";return}if(!f&&!l){let Kt=(st=(ut=o==null?void 0:o.launcher)==null?void 0:ut.width)!=null?st:o==null?void 0:o.launcherWidth,bt=Kt!=null?Kt:oo;be.style.width=bt,be.style.maxWidth=bt}if(Ro(),!h){let Kt=v.innerHeight,bt=64,zt=(Ee=(Le=o.launcher)==null?void 0:Le.heightOffset)!=null?Ee:0,eo=Math.max(200,Kt-bt),or=Math.min(640,eo),Ye=Math.max(200,or-zt);be.style.height=`${Ye}px`}}finally{if(Ur(),U(),k&&E){let bt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((xt=(Qe=o.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?xt:640),zt=(Re=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Re:!1,eo=(fe=(Pe=o.launcher)==null?void 0:Pe.mobileFullscreen)!=null?fe:!0,or=pr(o)&&eo&&bt,Ye=zt||eo&&bt&&E||or;if(Ye&&!fr){let Rt=e.getRootNode(),cr=Rt instanceof ShadowRoot?Rt.host:e.closest(".persona-host");cr&&!tr&&(tr=fp(cr,(Ot=(Ut=o.launcher)==null?void 0:Ut.zIndex)!=null?Ot:Lr)),fr=mp(e.ownerDocument)}else Ye||(tr==null||tr(),tr=null,fr==null||fr(),fr=null)}}};fs();let Yp=(tf=e.ownerDocument.defaultView)!=null?tf:window;if(Yp.addEventListener("resize",fs),dt.push(()=>Yp.removeEventListener("resize",fs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ur()});l.observe(Ne),dt.push(()=>l.disconnect())}Zr=Me.scrollTop;let Zp=sn(Me),Kx=()=>{let l=Me.getRootNode(),f=typeof l.getSelection=="function"?l.getSelection():null;return f!=null?f:Me.ownerDocument.getSelection()},Fl=()=>xh(Kx(),Me),eu=()=>{let l=Me.scrollTop,f=sn(Me),h=f<Zp;if(Zp=f,ot()!=="follow"){Zr=l,$r();return}let{action:v,nextLastScrollTop:R}=nl({following:Yr.isFollowing(),currentScrollTop:l,lastScrollTop:Zr,nearBottom:da(Me,va),userScrollThreshold:Js,isAutoScrolling:Co||Vn||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Zr=R,v==="resume"){Fl()||No();return}v==="pause"&&Sa()};if(Me.addEventListener("scroll",eu,{passive:!0}),dt.push(()=>Me.removeEventListener("scroll",eu)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{oi()});l.observe(Je),l.observe(Me),dt.push(()=>l.disconnect())}let tu=()=>{ot()==="follow"&&Yr.isFollowing()&&Fl()&&Sa()},ru=Me.ownerDocument;ru.addEventListener("selectionchange",tu),dt.push(()=>{ru.removeEventListener("selectionchange",tu)});let ou=l=>{if(ot()!=="follow")return;let f=al({following:Yr.isFollowing(),deltaY:l.deltaY,nearBottom:da(Me,va),resumeWhenNearBottom:!0});f==="pause"?Sa():f==="resume"&&!Fl()&&No()};Me.addEventListener("wheel",ou,{passive:!0}),dt.push(()=>Me.removeEventListener("wheel",ou)),lt.addEventListener("click",()=>{zn(),Me.scrollTop=Me.scrollHeight,Zr=Me.scrollTop,No(),Oo(!0),$r()}),dt.push(()=>lt.remove()),dt.push(()=>{os(),zn()});let nu=()=>{j&&(Wo&&(j.removeEventListener("click",Wo),Wo=null),W()?(j.style.display="",Wo=()=>{I(!1,"user")},j.addEventListener("click",Wo)):j.style.display="none")};nu(),(()=>{let{clearChatButton:l}=Y;l&&l.addEventListener("click",()=>{_.clearMessages(),Bo.clear(),No(),Ln(Y.composerOverlay);try{localStorage.removeItem(Ya),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ya}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ya)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(v=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",v)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}c={},T.syncFromMetadata(),ge==null||ge.clear(),ue==null||ue.reset(),G==null||G.update()})})(),Wt&&Wt.addEventListener("submit",Bt),ke==null||ke.addEventListener("keydown",Zt),ke==null||ke.addEventListener("input",Sr),ke==null||ke.addEventListener("paste",Xp);let au=(rf=e.ownerDocument)!=null?rf:document;au.addEventListener("keydown",uo,!0);let su="persona-attachment-drop-active",ms=0,Nl=()=>{ms=0,pe.classList.remove(su)},Ea=()=>{var l;return((l=o.attachments)==null?void 0:l.enabled)===!0&&yt!==null},iu=l=>{!Rl(l.dataTransfer)||!Ea()||(ms++,ms===1&&pe.classList.add(su))},lu=l=>{!Rl(l.dataTransfer)||!Ea()||(ms--,ms<=0&&Nl())},du=l=>{!Rl(l.dataTransfer)||!Ea()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},cu=l=>{var h;if(!Rl(l.dataTransfer)||!Ea())return;l.preventDefault(),l.stopPropagation(),Nl();let f=Array.from((h=l.dataTransfer.files)!=null?h:[]);f.length!==0&&yt.handleFiles(f)},An=!0;pe.addEventListener("dragenter",iu,An),pe.addEventListener("dragleave",lu,An),e.addEventListener("dragover",du,An),e.addEventListener("drop",cu,An);let ui=e.ownerDocument,pu=l=>{Ea()&&l.preventDefault()},uu=l=>{Ea()&&l.preventDefault()};ui.addEventListener("dragover",pu),ui.addEventListener("drop",uu),dt.push(()=>{Wt&&Wt.removeEventListener("submit",Bt),ke==null||ke.removeEventListener("keydown",Zt),ke==null||ke.removeEventListener("input",Sr),ke==null||ke.removeEventListener("paste",Xp),au.removeEventListener("keydown",uo,!0)}),dt.push(()=>{pe.removeEventListener("dragenter",iu,An),pe.removeEventListener("dragleave",lu,An),e.removeEventListener("dragover",du,An),e.removeEventListener("drop",cu,An),ui.removeEventListener("dragover",pu),ui.removeEventListener("drop",uu),Nl()}),dt.push(()=>{_.cancel()}),rr?dt.push(()=>{rr==null||rr.destroy()}):mr&&dt.push(()=>{mr==null||mr.remove()});let dr={update(l){var Tr,Br,Uo,vr,Dr,Fr,Qn,gs,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,vf,Cf,wf,Sf,Af,Mf,Tf,Ef,kf,Lf,Pf,Rf,If,Wf,Hf,Bf,Df,Ff,Nf,Of,_f,Uf,qf,Vf,$f,zf,jf,Gf,Kf,Xf,Qf,Jf,Yf,Zf,em,tm,rm,om,nm,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,vm,Cm,wm,Sm,Am,Mm,Tm,Em,km,Lm,Pm,Rm,Im,Wm,Hm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,Vm,$m,zm,jm,Gm,Km,Xm,Qm,Jm,Ym,Zm,eg,tg,rg,og,ng,ag,sg,ig,lg;let f=o.toolCall,h=o.messageActions,v=(Tr=o.layout)==null?void 0:Tr.messages,R=o.colorScheme,F=o.loadingIndicator,$=o.iterationDisplay,O=(Br=o.features)==null?void 0:Br.showReasoning,D=(Uo=o.features)==null?void 0:Uo.showToolCalls,ae=(vr=o.features)==null?void 0:vr.toolCallDisplay,se=(Dr=o.features)==null?void 0:Dr.reasoningDisplay;o={...o,...l},xe(),Wn(e,o),wl(e,o),Sl(e,o),Jr(),o.colorScheme!==R&&es();let Q=zs.getForInstance(o.plugins);n.length=0,n.push(...Q),E=(Qn=(Fr=o.launcher)==null?void 0:Fr.enabled)!=null?Qn:!0,M=(cf=(gs=o.launcher)==null?void 0:gs.autoExpand)!=null?cf:!1,Ke=(uf=(pf=o.features)==null?void 0:pf.showReasoning)!=null?uf:!0,Ce=(mf=(ff=o.features)==null?void 0:ff.showToolCalls)!=null?mf:!0,Ue=(hf=(gf=o.features)==null?void 0:gf.scrollToBottom)!=null?hf:{};let ye=ot();Te=(yf=(xf=o.features)==null?void 0:xf.scrollBehavior)!=null?yf:{},ye!==ot()&&(zn(),No()),ko(),$r();let He=Ie;if(Ie=(vf=(bf=o.features)==null?void 0:bf.showEventStreamToggle)!=null?vf:!1,Ie&&!He){if(ge||(J=new Vs(de),ge=new qs(le,J),ue=ue!=null?ue:new $s,J.open().then(()=>ge==null?void 0:ge.restore()).catch(()=>{}),_.setSSEEventCallback((te,Et)=>{var jt;(jt=o.onSSEEvent)==null||jt.call(o,te,Et),ue==null||ue.processEvent(te,Et),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!ht&&qe){let te=(wf=(Cf=o.features)==null?void 0:Cf.eventStream)==null?void 0:wf.classNames,Et="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");ht=S("button",Et),ht.style.width="28px",ht.style.height="28px",ht.style.color=_r.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let jt=ve("activity","18px","currentColor",1.5);jt&&ht.appendChild(jt);let it=Y.clearChatButtonWrapper,It=Y.closeButtonWrapper,hr=it||It;hr&&hr.parentNode===qe?qe.insertBefore(ht,hr):qe.appendChild(ht),ht.addEventListener("click",()=>{ce?yo():zo()})}}else!Ie&&He&&(yo(),ht&&(ht.remove(),ht=null),ge==null||ge.clear(),J==null||J.destroy(),ge=null,J=null,ue==null||ue.reset(),ue=null);if(((Sf=o.launcher)==null?void 0:Sf.enabled)===!1&&rr&&(rr.destroy(),rr=null),((Af=o.launcher)==null?void 0:Af.enabled)===!1&&mr&&(mr.remove(),mr=null),((Mf=o.launcher)==null?void 0:Mf.enabled)!==!1&&!rr&&!mr){let{instance:te,element:Et}=bp({config:o,plugins:n,onToggle:Jp});rr=te,te||(mr=Et),e.appendChild(Et)}rr&&rr.update(o),Xe&&((Tf=o.launcher)==null?void 0:Tf.title)!==void 0&&(Xe.textContent=o.launcher.title),et&&((Ef=o.launcher)==null?void 0:Ef.subtitle)!==void 0&&(et.textContent=o.launcher.subtitle);let Se=(kf=o.layout)==null?void 0:kf.header;if((Se==null?void 0:Se.layout)!==b&&qe){let te=Se?za(o,Se,{showClose:W(),onClose:()=>I(!1,"user")}):ln({config:o,showClose:W(),onClose:()=>I(!1,"user")});gt.replaceHeader(te),qe=gt.header.element,he=gt.header.iconHolder,Xe=gt.header.headerTitle,et=gt.header.headerSubtitle,j=gt.header.closeButton,b=Se==null?void 0:Se.layout}else if(Se&&(he&&(he.style.display=Se.showIcon===!1?"none":""),Xe&&(Xe.style.display=Se.showTitle===!1?"none":""),et&&(et.style.display=Se.showSubtitle===!1?"none":""),j&&(j.style.display=Se.showCloseButton===!1?"none":""),Y.clearChatButtonWrapper)){let te=Se.showClearChat;if(te!==void 0){Y.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Et}=Y;Et&&!Et.classList.contains("persona-absolute")&&(te?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let $e=((Lf=o.layout)==null?void 0:Lf.showHeader)!==!1;qe&&(qe.style.display=$e?"":"none");let ut=((Pf=o.layout)==null?void 0:Pf.showFooter)!==!1;Ne&&(Ne.style.display=ut?"":"none"),Ur(),$r(),E!==w?E?I(M,"auto"):(k=!0,U()):M!==y&&I(M,"auto"),y=M,w=E,fs(),nu();let Ee=JSON.stringify(l.toolCall)!==JSON.stringify(f),ze=JSON.stringify(o.messageActions)!==JSON.stringify(h),Qe=JSON.stringify((Rf=o.layout)==null?void 0:Rf.messages)!==JSON.stringify(v),xt=((If=o.loadingIndicator)==null?void 0:If.render)!==(F==null?void 0:F.render)||((Wf=o.loadingIndicator)==null?void 0:Wf.renderIdle)!==(F==null?void 0:F.renderIdle)||((Hf=o.loadingIndicator)==null?void 0:Hf.showBubble)!==(F==null?void 0:F.showBubble),B=o.iterationDisplay!==$,Re=((Df=(Bf=o.features)==null?void 0:Bf.showReasoning)!=null?Df:!0)!==(O!=null?O:!0)||((Nf=(Ff=o.features)==null?void 0:Ff.showToolCalls)!=null?Nf:!0)!==(D!=null?D:!0)||JSON.stringify((Of=o.features)==null?void 0:Of.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify((_f=o.features)==null?void 0:_f.reasoningDisplay)!==JSON.stringify(se);(Ee||ze||Qe||xt||B||Re)&&_&&(xa++,bn(Je,_.getMessages(),me));let fe=(Uf=o.launcher)!=null?Uf:{},Ut=(qf=fe.headerIconHidden)!=null?qf:!1,Ot=($f=(Vf=o.layout)==null?void 0:Vf.header)==null?void 0:$f.showIcon,Kt=Ut||Ot===!1,bt=fe.headerIconName,zt=(zf=fe.headerIconSize)!=null?zf:"48px";if(he){let te=pe.querySelector(".persona-border-b-persona-divider"),Et=te==null?void 0:te.querySelector(".persona-flex-col");if(Kt)he.style.display="none",te&&Et&&!te.contains(Et)&&te.insertBefore(Et,te.firstChild);else{if(he.style.display="",he.style.height=zt,he.style.width=zt,te&&Et&&(te.contains(he)?he.nextSibling!==Et&&(he.remove(),te.insertBefore(he,Et)):te.insertBefore(he,Et)),bt){let it=parseFloat(zt)||24,It=ve(bt,it*.6,"currentColor",1);It?he.replaceChildren(It):he.textContent=(jf=fe.agentIconText)!=null?jf:"\u{1F4AC}"}else if(fe.iconUrl){let it=he.querySelector("img");if(it)it.src=fe.iconUrl,it.style.height=zt,it.style.width=zt;else{let It=document.createElement("img");It.src=fe.iconUrl,It.alt="",It.className="persona-rounded-xl persona-object-cover",It.style.height=zt,It.style.width=zt,he.replaceChildren(It)}}else{let it=he.querySelector("svg"),It=he.querySelector("img");(it||It)&&he.replaceChildren(),he.textContent=(Gf=fe.agentIconText)!=null?Gf:"\u{1F4AC}"}let jt=he.querySelector("img");jt&&(jt.style.height=zt,jt.style.width=zt)}}let eo=(Xf=(Kf=o.layout)==null?void 0:Kf.header)==null?void 0:Xf.showTitle,or=(Jf=(Qf=o.layout)==null?void 0:Qf.header)==null?void 0:Jf.showSubtitle;if(Xe&&(Xe.style.display=eo===!1?"none":""),et&&(et.style.display=or===!1?"none":""),j){((Zf=(Yf=o.layout)==null?void 0:Yf.header)==null?void 0:Zf.showCloseButton)===!1?j.style.display="none":j.style.display="";let Et=(em=fe.closeButtonSize)!=null?em:"32px",jt=(tm=fe.closeButtonPlacement)!=null?tm:"inline";j.style.height=Et,j.style.width=Et;let{closeButtonWrapper:it}=Y,It=jt==="top-right",hr=it==null?void 0:it.classList.contains("persona-absolute");if(it&&It!==hr)if(it.remove(),It)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(it);else{let ct=(om=(rm=fe.clearChat)==null?void 0:rm.placement)!=null?om:"inline",xr=(am=(nm=fe.clearChat)==null?void 0:nm.enabled)!=null?am:!0;it.className=xr&&ct==="inline"?"":"persona-ml-auto";let zr=pe.querySelector(".persona-border-b-persona-divider");zr&&zr.appendChild(it)}if(j.style.color=fe.closeButtonColor||_r.actionIconColor,fe.closeButtonBackgroundColor?(j.style.backgroundColor=fe.closeButtonBackgroundColor,j.classList.remove("hover:persona-bg-gray-100")):(j.style.backgroundColor="",j.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let ct=fe.closeButtonBorderWidth||"0px",xr=fe.closeButtonBorderColor||"transparent";j.style.border=`${ct} solid ${xr}`,j.classList.remove("persona-border-none")}else j.style.border="",j.classList.add("persona-border-none");fe.closeButtonBorderRadius?(j.style.borderRadius=fe.closeButtonBorderRadius,j.classList.remove("persona-rounded-full")):(j.style.borderRadius="",j.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(j.style.paddingLeft=fe.closeButtonPaddingX,j.style.paddingRight=fe.closeButtonPaddingX):(j.style.paddingLeft="",j.style.paddingRight=""),fe.closeButtonPaddingY?(j.style.paddingTop=fe.closeButtonPaddingY,j.style.paddingBottom=fe.closeButtonPaddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Er=(sm=fe.closeButtonIconName)!=null?sm:"x",So=(im=fe.closeButtonIconText)!=null?im:"\xD7";j.innerHTML="";let Nr=ve(Er,"28px","currentColor",1);Nr?j.appendChild(Nr):j.textContent=So;let er=(lm=fe.closeButtonTooltipText)!=null?lm:"Close chat",ro=(dm=fe.closeButtonShowTooltip)!=null?dm:!0;if(j.setAttribute("aria-label",er),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),ro&&er)){let ct=null,xr=()=>{if(ct||!j)return;let Jn=j.ownerDocument,hs=Jn.body;if(!hs)return;ct=Vo(Jn,"div","persona-clear-chat-tooltip"),ct.textContent=er;let xs=Vo(Jn,"div");xs.className="persona-clear-chat-tooltip-arrow",ct.appendChild(xs);let Yn=j.getBoundingClientRect();ct.style.position="fixed",ct.style.zIndex=String(Hn),ct.style.left=`${Yn.left+Yn.width/2}px`,ct.style.top=`${Yn.top-8}px`,ct.style.transform="translate(-50%, -100%)",hs.appendChild(ct)},zr=()=>{ct&&ct.parentNode&&(ct.parentNode.removeChild(ct),ct=null)};it.addEventListener("mouseenter",xr),it.addEventListener("mouseleave",zr),j.addEventListener("focus",xr),j.addEventListener("blur",zr),it._cleanupTooltip=()=>{zr(),it&&(it.removeEventListener("mouseenter",xr),it.removeEventListener("mouseleave",zr)),j&&(j.removeEventListener("focus",xr),j.removeEventListener("blur",zr))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Rt}=Y;if(Ye){let te=(cm=fe.clearChat)!=null?cm:{},Et=(pm=te.enabled)!=null?pm:!0,jt=(fm=(um=o.layout)==null?void 0:um.header)==null?void 0:fm.showClearChat,it=jt!==void 0?jt:Et,It=(mm=te.placement)!=null?mm:"inline";if(Rt){Rt.style.display=it?"":"none";let{closeButtonWrapper:hr}=Y;!H()&&hr&&!hr.classList.contains("persona-absolute")&&(it?hr.classList.remove("persona-ml-auto"):hr.classList.add("persona-ml-auto"));let Er=It==="top-right",So=Rt.classList.contains("persona-absolute");if(!H()&&Er!==So&&it){if(Rt.remove(),Er)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",pe.style.position="relative",pe.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let er=pe.querySelector(".persona-border-b-persona-divider"),ro=Y.closeButtonWrapper;er&&ro&&ro.parentElement===er?er.insertBefore(Rt,ro):er&&er.appendChild(Rt)}let Nr=Y.closeButtonWrapper;Nr&&!Nr.classList.contains("persona-absolute")&&(Er?Nr.classList.add("persona-ml-auto"):Nr.classList.remove("persona-ml-auto"))}}if(it){if(!H()){let ct=(gm=te.size)!=null?gm:"32px";Ye.style.height=ct,Ye.style.width=ct}let hr=(hm=te.iconName)!=null?hm:"refresh-cw",Er=(xm=te.iconColor)!=null?xm:"";Ye.style.color=Er||_r.actionIconColor,Ye.innerHTML="";let So=H()?"14px":"20px",Nr=ve(hr,So,"currentColor",2);if(Nr&&Ye.appendChild(Nr),te.backgroundColor?(Ye.style.backgroundColor=te.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let ct=te.borderWidth||"0px",xr=te.borderColor||"transparent";Ye.style.border=`${ct} solid ${xr}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");te.borderRadius?(Ye.style.borderRadius=te.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),te.paddingX?(Ye.style.paddingLeft=te.paddingX,Ye.style.paddingRight=te.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),te.paddingY?(Ye.style.paddingTop=te.paddingY,Ye.style.paddingBottom=te.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let er=(ym=te.tooltipText)!=null?ym:"Clear chat",ro=(bm=te.showTooltip)!=null?bm:!0;if(Ye.setAttribute("aria-label",er),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),ro&&er)){let ct=null,xr=()=>{if(ct||!Ye)return;let Jn=Ye.ownerDocument,hs=Jn.body;if(!hs)return;ct=Vo(Jn,"div","persona-clear-chat-tooltip"),ct.textContent=er;let xs=Vo(Jn,"div");xs.className="persona-clear-chat-tooltip-arrow",ct.appendChild(xs);let Yn=Ye.getBoundingClientRect();ct.style.position="fixed",ct.style.zIndex=String(Hn),ct.style.left=`${Yn.left+Yn.width/2}px`,ct.style.top=`${Yn.top-8}px`,ct.style.transform="translate(-50%, -100%)",hs.appendChild(ct)},zr=()=>{ct&&ct.parentNode&&(ct.parentNode.removeChild(ct),ct=null)};Rt.addEventListener("mouseenter",xr),Rt.addEventListener("mouseleave",zr),Ye.addEventListener("focus",xr),Ye.addEventListener("blur",zr),Rt._cleanupTooltip=()=>{zr(),Rt&&(Rt.removeEventListener("mouseenter",xr),Rt.removeEventListener("mouseleave",zr)),Ye&&(Ye.removeEventListener("focus",xr),Ye.removeEventListener("blur",zr))}}}}let cr=o.actionParsers&&o.actionParsers.length?o.actionParsers:[js],go=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ma.message,ma.messageAndClick];T=Gs({parsers:cr,handlers:go,getSessionMetadata:p,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),me=nx(o,T,Z),_.updateConfig(o),bn(Je,_.getMessages(),me),ha(),K(),X(_.isStreaming());let to=((vm=o.voiceRecognition)==null?void 0:vm.enabled)===!0,jn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Gn=((wm=(Cm=o.voiceRecognition)==null?void 0:Cm.provider)==null?void 0:wm.type)==="runtype";if(to&&(jn||Gn))if(!z||!Ht){let te=Vx(o.voiceRecognition,o.sendButton);te&&(z=te.micButton,Ht=te.micButtonWrapper,Jt.insertBefore(Ht,Cr),z.addEventListener("click",pi),z.disabled=_.isStreaming())}else{let te=(Sm=o.voiceRecognition)!=null?Sm:{},Et=(Am=o.sendButton)!=null?Am:{},jt=(Mm=te.iconName)!=null?Mm:"mic",it=(Tm=Et.size)!=null?Tm:"40px",It=(Em=te.iconSize)!=null?Em:it,hr=parseFloat(It)||24;z.style.width=It,z.style.height=It,z.style.minWidth=It,z.style.minHeight=It;let Er=(Lm=(km=te.iconColor)!=null?km:Et.textColor)!=null?Lm:"currentColor";z.innerHTML="";let So=ve(jt,hr,Er,2);So?z.appendChild(So):z.textContent="\u{1F3A4}";let Nr=(Pm=te.backgroundColor)!=null?Pm:Et.backgroundColor;Nr?z.style.backgroundColor=Nr:z.style.backgroundColor="",Er?z.style.color=Er:z.style.color="var(--persona-text, #111827)",te.borderWidth?(z.style.borderWidth=te.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),te.borderColor?z.style.borderColor=te.borderColor:z.style.borderColor="",te.paddingX?(z.style.paddingLeft=te.paddingX,z.style.paddingRight=te.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),te.paddingY?(z.style.paddingTop=te.paddingY,z.style.paddingBottom=te.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let er=Ht==null?void 0:Ht.querySelector(".persona-send-button-tooltip"),ro=(Rm=te.tooltipText)!=null?Rm:"Start voice recognition";if(((Im=te.showTooltip)!=null?Im:!1)&&ro)if(er)er.textContent=ro,er.style.display="";else{let xr=document.createElement("div");xr.className="persona-send-button-tooltip",xr.textContent=ro,Ht==null||Ht.insertBefore(xr,z)}else er&&(er.style.display="none");Ht.style.display="",z.disabled=_.isStreaming()}else z&&Ht&&(Ht.style.display="none",((Hm=(Wm=o.voiceRecognition)==null?void 0:Wm.provider)==null?void 0:Hm.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():_o&&Sn());if(((Bm=o.attachments)==null?void 0:Bm.enabled)===!0)if(!we||!oe){let te=(Dm=o.attachments)!=null?Dm:{},jt=(Nm=((Fm=o.sendButton)!=null?Fm:{}).size)!=null?Nm:"40px";At||(At=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),At.style.display="none",Wt.insertBefore(At,ke)),De||(De=document.createElement("input"),De.type="file",De.accept=((Om=te.allowedTypes)!=null?Om:an).join(","),De.multiple=((_m=te.maxFiles)!=null?_m:4)>1,De.style.display="none",De.setAttribute("aria-label","Attach files"),Wt.insertBefore(De,ke)),we=S("div","persona-send-button-wrapper"),oe=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),oe.type="button",oe.setAttribute("aria-label",(Um=te.buttonTooltipText)!=null?Um:"Attach file");let it=(qm=te.buttonIconName)!=null?qm:"paperclip",It=jt,hr=parseFloat(It)||40,Er=Math.round(hr*.6);oe.style.width=It,oe.style.height=It,oe.style.minWidth=It,oe.style.minHeight=It,oe.style.fontSize="18px",oe.style.lineHeight="1",oe.style.backgroundColor="transparent",oe.style.color="var(--persona-primary, #111827)",oe.style.border="none",oe.style.borderRadius="6px",oe.style.transition="background-color 0.15s ease",oe.addEventListener("mouseenter",()=>{oe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),oe.addEventListener("mouseleave",()=>{oe.style.backgroundColor="transparent"});let So=ve(it,Er,"currentColor",1.5);So?oe.appendChild(So):oe.textContent="\u{1F4CE}",oe.addEventListener("click",ro=>{ro.preventDefault(),De==null||De.click()}),we.appendChild(oe);let Nr=(Vm=te.buttonTooltipText)!=null?Vm:"Attach file",er=S("div","persona-send-button-tooltip");er.textContent=Nr,we.appendChild(er),Gt.append(we),!yt&&De&&At&&(yt=la.fromConfig(te),yt.setPreviewsContainer(At),De.addEventListener("change",async()=>{yt&&(De!=null&&De.files)&&(await yt.handleFileSelect(De.files),De.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(ax(te.dropOverlay))}else{we.style.display="";let te=($m=o.attachments)!=null?$m:{};De&&(De.accept=((zm=te.allowedTypes)!=null?zm:an).join(","),De.multiple=((jm=te.maxFiles)!=null?jm:4)>1),yt&&yt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else we&&(we.style.display="none"),yt&&yt.clearAttachments(),(Gm=pe.querySelector(".persona-attachment-drop-overlay"))==null||Gm.remove();let Xt=(Km=o.sendButton)!=null?Km:{},Kn=(Xm=Xt.useIcon)!=null?Xm:!1,Mn=(Qm=Xt.iconText)!=null?Qm:"\u2191",Tn=Xt.iconName,en=(Jm=Xt.tooltipText)!=null?Jm:"Send message",Xn=(Ym=Xt.showTooltip)!=null?Ym:!1,wo=(Zm=Xt.size)!=null?Zm:"40px",rt=Xt.backgroundColor,gr=Xt.textColor;if(Kn){if(je.style.width=wo,je.style.height=wo,je.style.minWidth=wo,je.style.minHeight=wo,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",gr?je.style.color=gr:je.style.color="var(--persona-button-primary-fg, #ffffff)",Tn){let te=parseFloat(wo)||24,Et=(gr==null?void 0:gr.trim())||"currentColor",jt=ve(Tn,te,Et,2);jt?je.appendChild(jt):je.textContent=Mn}else je.textContent=Mn;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rt?(je.style.backgroundColor=rt,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(tg=(eg=o.copy)==null?void 0:eg.sendButtonLabel)!=null?tg:"Send",je.style.width="",je.style.height="",je.style.minWidth="",je.style.minHeight="",je.style.fontSize="",je.style.lineHeight="",je.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",rt?(je.style.backgroundColor=rt,je.classList.remove("persona-bg-persona-accent")):je.classList.add("persona-bg-persona-accent"),gr?je.style.color=gr:je.classList.add("persona-text-white");Xt.borderWidth?(je.style.borderWidth=Xt.borderWidth,je.style.borderStyle="solid"):(je.style.borderWidth="",je.style.borderStyle=""),Xt.borderColor?je.style.borderColor=Xt.borderColor:je.style.borderColor="",Xt.paddingX?(je.style.paddingLeft=Xt.paddingX,je.style.paddingRight=Xt.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Xt.paddingY?(je.style.paddingTop=Xt.paddingY,je.style.paddingBottom=Xt.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let Vt=Cr==null?void 0:Cr.querySelector(".persona-send-button-tooltip");if(Xn&&en)if(Vt)Vt.textContent=en,Vt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=en,Cr==null||Cr.insertBefore(te,je)}else Vt&&(Vt.style.display="none");let qt=(sg=(rg=o.layout)==null?void 0:rg.contentMaxWidth)!=null?sg:H()?(ag=(ng=(og=o.launcher)==null?void 0:og.composerBar)==null?void 0:ng.contentMaxWidth)!=null?ag:"720px":void 0;qt?(Je.style.maxWidth=qt,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%",Wt&&(Wt.style.maxWidth=qt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Ge&&(Ge.style.maxWidth=qt,Ge.style.marginLeft="auto",Ge.style.marginRight="auto")):(Je.style.maxWidth="",Je.style.marginLeft="",Je.style.marginRight="",Je.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Ge&&(Ge.style.maxWidth="",Ge.style.marginLeft="",Ge.style.marginRight=""));let ft=(ig=o.statusIndicator)!=null?ig:{},Qt=(lg=ft.visible)!=null?lg:!0;if(ur.style.display=Qt?"":"none",_){let te=_.getStatus();Lt(ur,(jt=>{var it,It,hr,Er;return jt==="idle"?(it=ft.idleText)!=null?it:kr.idle:jt==="connecting"?(It=ft.connectingText)!=null?It:kr.connecting:jt==="connected"?(hr=ft.connectedText)!=null?hr:kr.connected:jt==="error"?(Er=ft.errorText)!=null?Er:kr.error:kr[jt]})(te),ft,te)}ur.classList.remove("persona-text-left","persona-text-center","persona-text-right");let St=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";ur.classList.add(St)},open(){W()&&I(!0,"api")},close(){W()&&I(!1,"api")},toggle(){W()&&I(!k,"api")},clearChat(){Ir=!1,_.clearMessages(),Bo.clear(),No();try{localStorage.removeItem(Ya),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ya}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ya)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}c={},T.syncFromMetadata(),ge==null||ge.clear(),ue==null||ue.reset(),G==null||G.update()},setMessage(l){return!ke||_.isStreaming()?!1:(!k&&W()&&I(!0,"system"),ke.value=l,ke.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let f=(l==null?void 0:l.trim())||ke.value.trim();return f?(!k&&W()&&I(!0,"system"),ke.value="",ke.style.height="auto",_.sendMessage(f),!0):!1},startVoiceRecognition(){var f,h;return _.isStreaming()?!1:((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!k&&W()&&I(!0,"system"),mt.manuallyDeactivated=!1,Vr(),_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),po("user"),_.isVoiceActive()&&Ta()})),!0):_o?!0:Qp()?(!k&&W()&&I(!0,"system"),mt.manuallyDeactivated=!1,Vr(),di("user"),!0):!1},stopVoiceRecognition(){var l,f;return((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Vr(),po("user"),Zo()}),!0):!1:_o?(mt.manuallyDeactivated=!0,Vr(),Sn("user"),!0):!1},injectMessage(l){return!k&&W()&&I(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!k&&W()&&I(!0,"system");let f=_.injectAssistantMessage(l);return N&&(N=!1,q&&(clearTimeout(q),q=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),f},injectUserMessage(l){return!k&&W()&&I(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!k&&W()&&I(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!k&&W()&&I(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!k&&W()&&I(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!k&&W()&&I(!0,"system"),_.injectTestEvent(l)},async connectStream(l,f){return _.connectStream(l,f)},__pushEventStreamEvent(l){ge&&(ue==null||ue.processEvent(l.type,l.payload),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Ie||!ge||zo()},hideEventStream(){ce&&yo()},isEventStreamVisible(){return ce},showArtifacts(){xo(o)&&(Ir=!1,Jr(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){xo(o)&&(Ir=!0,Jr())},upsertArtifact(l){return xo(o)?(Ir=!1,_.upsertArtifact(l)):null},selectArtifact(l){xo(o)&&_.selectArtifact(l)},clearArtifacts(){xo(o)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return E&&!k&&!H()||!ke?!1:(ke.focus(),!0)},async resolveApproval(l,f,h){let R=_.getMessages().find(F=>{var $;return F.variant==="approval"&&(($=F.approval)==null?void 0:$.id)===l});if(!(R!=null&&R.approval))throw new Error(`Approval not found: ${l}`);if(R.approval.toolType==="webmcp"){_.resolveWebMcpApproval(R.id,f);return}return _.resolveApproval(R.approval,f,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){m(l)},on(l,f){return a.on(l,f)},off(l,f){a.off(l,f)},isOpen(){return W()&&k},isVoiceActive(){return mt.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:W()&&k,launcherEnabled:E,voiceActive:mt.active,streaming:_.isStreaming()}},showCSATFeedback(l){!k&&W()&&I(!0,"system");let f=Je.querySelector(".persona-feedback-container");f&&f.remove();let h=Ll({onSubmit:async(v,R)=>{var F;_.isClientTokenMode()&&await _.submitCSATFeedback(v,R),(F=l==null?void 0:l.onSubmit)==null||F.call(l,v,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&W()&&I(!0,"system");let f=Je.querySelector(".persona-feedback-container");f&&f.remove();let h=Pl({onSubmit:async(v,R)=>{var F;_.isClientTokenMode()&&await _.submitNPSFeedback(v,R),(F=l==null?void 0:l.onSubmit)==null||F.call(l,v,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,f){return _.submitCSATFeedback(l,f)},async submitNPSFeedback(l,f){return _.submitNPSFeedback(l,f)},destroy(){Ae!=null&&(clearInterval(Ae),Ae=null),dt.forEach(l=>l()),_e.remove(),Ze==null||Ze.remove(),rr==null||rr.destroy(),mr==null||mr.remove(),Wo&&j.removeEventListener("click",Wo)}};if((((of=r==null?void 0:r.debugTools)!=null?of:!1)||!!o.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,f={controller:dr,getMessages:dr.getMessages,getStatus:dr.getStatus,getMetadata:dr.getPersistentMetadata,updateMetadata:dr.updatePersistentMetadata,clearHistory:()=>dr.clearChat(),setVoiceActive:h=>h?dr.startVoiceRecognition():dr.stopVoiceRecognition()};window.AgentWidgetBrowser=f,dt.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.focusInput()};if(window.addEventListener("persona:focusInput",f),dt.push(()=>{window.removeEventListener("persona:focusInput",f)}),Ie){let O=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&dr.showEventStream()},D=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&dr.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",D),dt.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",D)})}let h=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.showArtifacts()},v=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.hideArtifacts()},R=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&dr.upsertArtifact(D.artifact)},F=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&dr.selectArtifact(D.id)},$=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&dr.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",$),dt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",$)})}let mo=Wv(o.persistState);if(mo&&W()){let l=Hv(mo.storage),f=`${mo.keyPrefix}widget-open`,h=`${mo.keyPrefix}widget-voice`,v=`${mo.keyPrefix}widget-voice-mode`;if(l){let R=((nf=mo.persist)==null?void 0:nf.openState)&&l.getItem(f)==="true",F=((af=mo.persist)==null?void 0:af.voiceState)&&l.getItem(h)==="true",$=((sf=mo.persist)==null?void 0:sf.voiceState)&&l.getItem(v)==="true";if(R&&setTimeout(()=>{dr.open(),setTimeout(()=>{var O;if(F||$)dr.startVoiceRecognition();else if((O=mo.persist)!=null&&O.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(lf=mo.persist)!=null&&lf.openState&&(a.on("widget:opened",()=>{l.setItem(f,"true")}),a.on("widget:closed",()=>{l.setItem(f,"false")})),(df=mo.persist)!=null&&df.voiceState&&(a.on("voice:state",O=>{l.setItem(h,O.active?"true":"false")}),a.on("user:message",O=>{l.setItem(v,O.viaVoice?"true":"false")})),mo.clearOnChatClear){let O=()=>{l.removeItem(f),l.removeItem(h),l.removeItem(v)},D=()=>O();window.addEventListener("persona:clear-chat",D),dt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return u&&W()&&setTimeout(()=>{dr.open()},0),Ve(),Qs||mi().then(()=>{_&&(xa++,Bo.clear(),bn(Je,_.getMessages(),me))}).catch(()=>{}),dr};var Bv=(e,t)=>{let r=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(r);return n?Math.max(0,t*parseFloat(n[1])/100):420},Dv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Fv=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Nv=(e,t)=>{let r=e.parentElement;if(!r)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),!(!n||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},sx=(e,t)=>{var o,n;let r=(n=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?n:!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0"},Dp=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},ix=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Dp(e)},Wp=e=>{e.style.transition=""},Hp=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Bp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Wl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ov=(e,t,r,o,n)=>{n?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,o),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(o))},_v=(e,t,r,o,n,a)=>{let s=a?t:e;n==="left"?s.firstElementChild!==o&&s.replaceChildren(o,r):s.lastElementChild!==o&&s.replaceChildren(r,o)},lx=(e,t,r,o,n,a,s)=>{var x,C,T,E,M,P;let i=no(a),c=i.reveal==="push";Ov(e,t,r,o,c),_v(e,t,r,o,i.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let d=e.ownerDocument.defaultView,u=(C=(x=a==null?void 0:a.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,g=(E=(T=a==null?void 0:a.launcher)==null?void 0:T.mobileBreakpoint)!=null?E:640,p=d!=null?d.innerWidth<=g:!1;if(u&&p&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Hp(t),Wp(o),ix(o),Bp(r),Wl(n,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((P=(M=a==null?void 0:a.launcher)==null?void 0:M.zIndex)!=null?P:Lr),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),ix(o),Dv(o,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Hp(t),Wp(o),Bp(r),Wl(n,o);let y=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",b=s?"translateX(0)":w;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=y,o.style.transform=b,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Wp(o),Dp(o),Wl(n,o);let y=Bv(i.width,e.clientWidth),w=Math.max(0,e.clientWidth),b=i.animate?"margin-left 180ms ease":"none",A=i.side==="right"?s?-y:0:s?0:-y;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${w+y}px`,t.style.transition=b,t.style.marginLeft=`${A}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${w}px`,r.style.maxWidth=`${w}px`,r.style.minWidth=`${w}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Hp(t),Dp(o),Bp(r),Wl(n,o);let y=i.reveal==="emerge";y?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let w=s?i.width:"0px",b=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",A=!s;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${w}`,o.style.width=w,o.style.maxWidth=w,o.style.minWidth=w,o.style.minHeight="0",Fv(o,i.maxHeight),o.style.overflow=y||A?"hidden":"visible",o.style.transition=b,y&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.boxSizing="border-box")}},Uv=(e,t)=>{let r=e.ownerDocument.createElement("div");return sx(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){sx(r,o)},destroy(){r.remove()}}},qv=(e,t)=>{var P,y,w,b;let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),c=r.createElement("div"),d=r.createElement("aside"),u=r.createElement("div"),g=(y=(P=t==null?void 0:t.launcher)==null?void 0:P.enabled)==null||y?(b=(w=t==null?void 0:t.launcher)==null?void 0:w.autoExpand)!=null?b:!1:!0;i.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",d.appendChild(u),o.insertBefore(s,e),c.appendChild(e);let p=null,m=()=>{p==null||p.disconnect(),p=null},x=()=>{m(),no(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(p=new ResizeObserver(()=>{lx(s,i,c,d,u,t,g)}),p.observe(s))},C=!1,T=()=>{lx(s,i,c,d,u,t,g),x(),g&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,Nv(s,no(t)))},E=s.ownerDocument.defaultView,M=()=>{T()};return E==null||E.addEventListener("resize",M),no(t).reveal==="push"?(i.appendChild(c),i.appendChild(d),s.appendChild(i)):(s.appendChild(c),s.appendChild(d)),T(),{mode:"docked",host:u,shell:s,syncWidgetState(A){let H=A.launcherEnabled?A.open:!0;g!==H&&(g=H,T())},updateConfig(A){var H,W;t=A,((W=(H=t==null?void 0:t.launcher)==null?void 0:H.enabled)!=null?W:!0)===!1&&(g=!0),T()},destroy(){E==null||E.removeEventListener("resize",M),m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Ks=(e,t)=>pr(t)?qv(e,t):Uv(e,t);var Fp={},dx=!1,Vv=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},$v=()=>{try{if(typeof Fp!="undefined"&&Fp.url)return new URL("../widget.css",Fp.url).href}catch{}return null},cx=(e,t)=>{let r=$v(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let a=n.cloneNode(!0);e.insertBefore(a,e.firstChild)};if(e instanceof ShadowRoot)if(r){let n=t.createElement("link");n.rel="stylesheet",n.href=r,n.setAttribute("data-persona","true"),e.insertBefore(n,e.firstChild)}else o();else if(!t.head.querySelector("link[data-persona]")&&r){let a=t.createElement("link");a.rel="stylesheet",a.href=r,a.setAttribute("data-persona","true"),t.head.appendChild(a)}},px=e=>{let t=Vv(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Ks(t,n),s,i=[],c=(T,E)=>{var w,b;let P=!((b=(w=E==null?void 0:E.launcher)==null?void 0:w.enabled)!=null?b:!0)||pr(E),y=o.createElement("div");if(y.setAttribute("data-persona-root","true"),P&&(y.style.height="100%",y.style.display="flex",y.style.flexDirection="column",y.style.flex="1",y.style.minHeight="0"),r){let A=T.attachShadow({mode:"open"});A.appendChild(y),cx(A,o)}else T.appendChild(y),cx(T,o);return t.id&&y.setAttribute("data-persona-instance",t.id),y},d=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},g=()=>{let T=c(a.host,n);s=Il(T,n,{debugTools:e.debugTools}),u()},p=()=>{i.forEach(T=>T()),i=[],s.destroy()};g(),e.onChatReady?e.onChatReady():e.onReady&&(dx||(dx=!0,console.warn("[Persona] `onReady` is deprecated: use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let m=T=>{p(),a.destroy(),a=Ks(t,T),n=T,g()},x={update(T){var b,A,H,W,k,N;let E={...n,...T,launcher:{...(b=n==null?void 0:n.launcher)!=null?b:{},...(A=T==null?void 0:T.launcher)!=null?A:{},dock:{...(W=(H=n==null?void 0:n.launcher)==null?void 0:H.dock)!=null?W:{},...(N=(k=T==null?void 0:T.launcher)==null?void 0:k.dock)!=null?N:{}}}},M=pr(n),P=pr(E),y=Dn(n),w=Dn(E);if(M!==P||y!==w){m(E);return}n=E,a.updateConfig(n),s.update(T),d()},destroy(){p(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},C=new Proxy(x,{get(T,E,M){if(E==="host")return a.host;if(E in T)return Reflect.get(T,E,M);let P=s[E];return typeof P=="function"?P.bind(s):P}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=C),C};var hx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),zv=new Set(["button","a","input","select","textarea","details","summary"]),jv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Np=/\b(product|card|item|listing|result)\b/i,_p=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Gv=3e3,Kv=100;function xx(e){let t=typeof e.className=="string"?e.className:"";if(Np.test(t)||e.id&&Np.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&Np.test(o.value))return!0}return!1}function yx(e){var t;return _p.test(((t=e.textContent)!=null?t:"").trim())}function bx(e){var r;let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=(r=t[o].getAttribute("href"))!=null?r:"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function Xv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ux(e){let t=e.match(_p);return t?t[0]:null}function fx(e){var o,n,a;let t=(o=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?o:e.querySelector("a[href]");if(t&&((n=t.textContent)!=null&&n.trim())){let s=t.getAttribute("href");return{title:t.textContent.trim(),href:s&&s!=="#"?s:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return(a=r==null?void 0:r.textContent)!=null&&a.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function Qv(e){let t=[],r=o=>{let n=o.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll("button").forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('[role="button"]').forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{var n;r((n=o.value)!=null?n:"")}),t.slice(0,6)}var Jv="commerce-card",Yv="result-card";function mx(e){return!xx(e)||!yx(e)||!bx(e)&&!Xv(e)?0:5200}function gx(e){var o;return!xx(e)||yx(e)||!bx(e)||((o=e.textContent)!=null?o:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Up=[{id:Jv,scoreElement(e){return mx(e)},shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if(r.interactivity==="static"){let o=r.text.trim();return!!(o.length===0||_p.test(o)&&o.length<32)}return!0},formatSummary(e,t){var c,d,u;if(mx(e)===0)return null;let{title:r,href:o}=fx(e),n=(u=(d=ux(((c=e.textContent)!=null?c:"").trim()))!=null?d:ux(t.text))!=null?u:"",a=Qv(e);return[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
111
+ `)}},{id:Yv,scoreElement(e){return gx(e)},formatSummary(e,t){if(gx(e)===0)return null;let{title:r,href:o}=fx(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
112
+ `)}}];function Zv(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function e0(e){var u,g,p,m,x,C,T,E,M,P,y,w,b;let t=(u=e.options)!=null?u:{},r=(p=(g=t.maxElements)!=null?g:e.maxElements)!=null?p:80,o=(x=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",n=(T=(C=t.maxTextLength)!=null?C:e.maxTextLength)!=null?T:200,a=(M=(E=t.visibleOnly)!=null?E:e.visibleOnly)!=null?M:!0,s=(P=t.root)!=null?P:e.root,i=(y=t.mode)!=null?y:"structured",c=(w=t.maxCandidates)!=null?w:Math.max(500,r*10),d=(b=e.rules)!=null?b:Up;return i==="simple"&&e.rules&&e.rules.length>0?(Zv(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:r,maxCandidates:c,excludeSelector:o,maxTextLength:n,visibleOnly:a,root:s,rules:d}}function Op(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var t0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function r0(e){let t=e.tagName.toLowerCase(),r=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||r==="textbox"||r==="combobox"||r==="listbox"||r==="spinbutton"?"input":t==="button"||r==="button"||zv.has(t)||r&&jv.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function vx(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function o0(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let c=e.getAttribute("role");c&&(t.role=c);for(let d=0;d<e.attributes.length;d++){let u=e.attributes[d];u.name.startsWith("data-")&&(t[u.name]=u.value)}return t}function qp(e){let t=e.tagName.toLowerCase();if(e.id){let n=`#${Op(e.id)}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}}for(let n of t0){let a=e.getAttribute(n);if(a){let s=`${t}[${n}="${Op(a)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let r=Array.from(e.classList).filter(n=>n&&!n.startsWith("persona-")).slice(0,3);if(r.length>0){let n=`${t}.${r.map(s=>Op(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}let a=e.parentElement;if(a){let i=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let c=`${n}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let o=e.parentElement;if(o){let a=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function n0(e){return e==="static"?Kv:Gv}function Cx(e,t){var n;let r=e.tagName.toLowerCase(),o=((n=e.textContent)!=null?n:"").trim().substring(0,t);return{selector:qp(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:r0(e),attributes:o0(e)}}function a0(e,t,r,o){let n=n0(t.interactivity),a=null;for(let s of r){let i=s.scoreElement(e,t,o);i>0&&(n+=i,s.formatSummary&&!a&&(a=s))}return{score:n,formattingRule:a}}function s0(e,t){var r;for(let o of e)if(t.el!==o.el&&(r=o.formattingRule)!=null&&r.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function i0(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,u=d.tagName.toLowerCase();if(hx.has(u)){i=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!vx(d)){i=s.nextNode();continue}let g=Cx(d,e.maxTextLength),p=g.text.length>0,m=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(T=>T==="role");if(!p&&!m){i=s.nextNode();continue}if(o.has(g.selector)){i=s.nextNode();continue}o.add(g.selector);let{score:x,formattingRule:C}=a0(d,g,e.rules,r);n.push({el:d,domIndex:a,enriched:g,score:x,formattingRule:C}),a+=1}i=s.nextNode()}n.sort((d,u)=>{let g=d.enriched.interactivity==="static"?1:0,p=u.enriched.interactivity==="static"?1:0;return g!==p?g-p:u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex});let c=[];for(let d of n){if(c.length>=e.maxElements)break;s0(c,d)||c.push(d)}return c.sort((d,u)=>{let g=d.enriched.interactivity==="static"?1:0,p=u.enriched.interactivity==="static"?1:0;return g!==p?g-p:g===1&&u.score!==d.score?u.score-d.score:d.domIndex-u.domIndex}),c.map(d=>{var p;let u;if((p=d.formattingRule)!=null&&p.formatSummary){let m=d.formattingRule.formatSummary(d.el,d.enriched,r);m&&(u=m)}let g={...d.enriched};return u&&(g.formattedSummary=u),g})}function l0(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,d=c.tagName.toLowerCase();if(hx.has(d)){a=n.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!vx(c)){a=n.nextNode();continue}let u=Cx(c,e.maxTextLength),g=u.text.length>0,p=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!g&&!p){a=n.nextNode();continue}o.has(u.selector)||(o.add(u.selector),r.push(u))}a=n.nextNode()}let s=[],i=[];for(let c of r)c.interactivity!=="static"?s.push(c):i.push(c);return[...s,...i].slice(0,e.maxElements)}function wx(e={}){var o;let t=e0(e),r=(o=t.root)!=null?o:document.body;return r?t.mode==="simple"?l0(t,r):i0(t,r):[]}var Hl=100;function Sx(e,t={}){var a;if(e.length===0)return"No page elements found.";let r=(a=t.mode)!=null?a:"structured",o=[];if(r==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
113
113
  ${s.map(i=>`- ${i.split(`
114
114
  `).join(`
115
115
  `)}`).join(`
116
- `)}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let s of e)r==="structured"&&s.formattedSummary||n[s.interactivity].push(s);if(n.clickable.length>0){let s=n.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Wl)}" (clickable)`);o.push(`Interactive elements:
116
+ `)}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let s of e)r==="structured"&&s.formattedSummary||n[s.interactivity].push(s);if(n.clickable.length>0){let s=n.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Hl)}" (clickable)`);o.push(`Interactive elements:
117
117
  ${s.join(`
118
- `)}`)}if(n.navigable.length>0){let s=n.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Wl)}" (navigable)`);o.push(`Navigation links:
118
+ `)}`)}if(n.navigable.length>0){let s=n.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Hl)}" (navigable)`);o.push(`Navigation links:
119
119
  ${s.join(`
120
- `)}`)}if(n.input.length>0){let s=n.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Wl)}" (input)`);o.push(`Form inputs:
120
+ `)}`)}if(n.input.length>0){let s=n.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Hl)}" (input)`);o.push(`Form inputs:
121
121
  ${s.join(`
122
- `)}`)}if(n.static.length>0){let s=n.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Wl)}"`);o.push(`Content:
122
+ `)}`)}if(n.static.length>0){let s=n.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Hl)}"`);o.push(`Content:
123
123
  ${s.join(`
124
124
  `)}`)}return o.join(`
125
125
 
126
- `)}var wx="3.35.0";var Sx=wx;function Ax(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Mx(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Tx(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var o;let r={...t.palette};return(o=e.colors)!=null&&o.primary&&(r.colors={...r.colors,primary:{50:$o(e.colors.primary,.95),100:$o(e.colors.primary,.9),200:$o(e.colors.primary,.8),300:$o(e.colors.primary,.7),400:$o(e.colors.primary,.6),500:e.colors.primary,600:$o(e.colors.primary,.8),700:$o(e.colors.primary,.7),800:$o(e.colors.primary,.6),900:$o(e.colors.primary,.5),950:$o(e.colors.primary,.45)}}),{...t,palette:r}}}}function Ex(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function kx(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function $o(e,t){let r=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),n=parseInt(e.slice(5,7),16),a=Math.round(r+(255-r)*(1-t)),s=Math.round(o+(255-o)*(1-t)),i=Math.round(n+(255-n)*(1-t));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Lx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var d0={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Px={components:{panel:{borderRadius:"0",shadow:"none"}}},qp={id:"shop",label:"Shopping Assistant",config:{theme:d0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:oo},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Vp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Px}},$p={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Px}},zp={shop:qp,minimal:Vp,fullscreen:$p};function Rx(e){return zp[e]}var c0=`
126
+ `)}function Ax(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Mx(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Tx(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var o;let r={...t.palette};return(o=e.colors)!=null&&o.primary&&(r.colors={...r.colors,primary:{50:$o(e.colors.primary,.95),100:$o(e.colors.primary,.9),200:$o(e.colors.primary,.8),300:$o(e.colors.primary,.7),400:$o(e.colors.primary,.6),500:e.colors.primary,600:$o(e.colors.primary,.8),700:$o(e.colors.primary,.7),800:$o(e.colors.primary,.6),900:$o(e.colors.primary,.5),950:$o(e.colors.primary,.45)}}),{...t,palette:r}}}}function Ex(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function kx(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function $o(e,t){let r=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),n=parseInt(e.slice(5,7),16),a=Math.round(r+(255-r)*(1-t)),s=Math.round(o+(255-o)*(1-t)),i=Math.round(n+(255-n)*(1-t));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Lx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var d0={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Px={components:{panel:{borderRadius:"0",shadow:"none"}}},Vp={id:"shop",label:"Shopping Assistant",config:{theme:d0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:oo},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},$p={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Px}},zp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Px}},jp={shop:Vp,minimal:$p,fullscreen:zp};function Rx(e){return jp[e]}var c0=`
127
127
  @keyframes persona-stream-wipe {
128
128
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
129
129
  to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
@@ -159,7 +159,7 @@ ${s.join(`
159
159
  mask-image: none !important;
160
160
  }
161
161
  }
162
- `.trim(),p0={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:c0};da(p0);var u0=`
162
+ `.trim(),p0={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:c0};ca(p0);var u0=`
163
163
  [data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
164
164
  animation: persona-stream-glyph-cycle-fade
165
165
  calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
@@ -177,7 +177,7 @@ ${s.join(`
177
177
  opacity: 1 !important;
178
178
  }
179
179
  }
180
- `.trim(),Ks="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",f0=10,m0=120,jp=120,g0=.4,h0=50,x0=e=>{var o;if(!e)return jp;let r=((o=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:o.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):jp},Ox=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=x0(t);return m0*r/jp},Gp=e=>{let t=Ks[Math.floor(Math.random()*Ks.length)];return e&&t===e&&(t=Ks[(Ks.indexOf(t)+1)%Ks.length]),t},y0=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let r=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let n of Array.from(r)){if(n===e){o=!0;continue}o&&Math.random()<g0&&(n.textContent=Gp())}},Ix=new WeakMap,Wx=25,Hx=.5,b0=6,Bx=.25,Dx=new WeakMap,Fx=new WeakMap,v0=(e,t)=>{var n;if(!e)return Wx*Hx;let r=Dx.get(e);Dx.set(e,t);let o=(n=Fx.get(e))!=null?n:Wx;if(r!==void 0){let a=t-r;a>1&&(o=o*(1-Bx)+a*Bx,Fx.set(e,o))}return Math.max(b0,o*Hx)},Ya=new Map,C0=e=>{var r;let t=e.closest("[data-message-id]");return(r=t==null?void 0:t.dataset.messageId)!=null?r:null},w0=e=>{var t;e&&Ya.set(e,((t=Ya.get(e))!=null?t:0)+1)},S0=e=>{var r;if(!e)return;let t=(r=Ya.get(e))!=null?r:0;t<=1?Ya.delete(e):Ya.set(e,t-1)},_x=e=>{var d;if(e.dataset.glyphCycleScheduled==="true")return;let t=(d=e.textContent)!=null?d:"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Gp();let r=C0(e);r&&(e.dataset.glyphCycleMessageId=r),w0(r);let o=e.closest(".persona-stream-glyph-cycle"),n=Date.now(),a=v0(o,n),s=Ox(e),i=f0*s,c=n+i;if(o){let u=Ix.get(o);u!==void 0&&(c=Math.max(c,u)),Ix.set(o,c+a)}A0(e,t,c)},A0=(e,t,r)=>{var s;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=Ox(e),n=(s=e.textContent)!=null?s:void 0,a=()=>{var c;if(!e.isConnected)return;if(Date.now()>=r){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,S0((c=e.dataset.glyphCycleMessageId)!=null?c:null),delete e.dataset.glyphCycleMessageId;return}let i=Gp(n);e.textContent=i,n=i,y0(e),setTimeout(a,o)};setTimeout(a,o)},Nx=e=>{var r;let t=(r=e.querySelectorAll)==null?void 0:r.call(e,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let o of Array.from(t))_x(o)},M0=e=>e.nodeType===1,T0={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:u0,bufferContent(e){if(e.length<h0)return"";let t=0,r=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(r=o),o+=1}return r<0?"":e.slice(0,r)},isAnimating(e){var t;return((t=Ya.get(e.id))!=null?t:0)>0},onAttach(e){Nx(e);let t=new MutationObserver(r=>{for(let o of r)for(let n of Array.from(o.addedNodes))M0(n)&&(n.classList.contains("persona-stream-char")&&n.closest(".persona-stream-glyph-cycle")?_x(n):Nx(n))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};da(T0);var Ux,qx,nr=typeof document!="undefined"&&(qx=(Ux=document.currentScript)==null?void 0:Ux.src)!=null?qx:null;yg(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${nr!=null?nr:"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});cg(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${nr!=null?nr:"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});fi().catch(e=>{typeof console!="undefined"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});Zg(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${nr!=null?nr:"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});return ty(E0);})();
180
+ `.trim(),Xs="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",f0=10,m0=120,Gp=120,g0=.4,h0=50,x0=e=>{var o;if(!e)return Gp;let r=((o=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:o.trim()).match(/([\d.]+)\s*ms/);return r?parseFloat(r[1]):Gp},Ox=e=>{let t=e.closest(".persona-stream-glyph-cycle"),r=x0(t);return m0*r/Gp},Kp=e=>{let t=Xs[Math.floor(Math.random()*Xs.length)];return e&&t===e&&(t=Xs[(Xs.indexOf(t)+1)%Xs.length]),t},y0=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let r=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let n of Array.from(r)){if(n===e){o=!0;continue}o&&Math.random()<g0&&(n.textContent=Kp())}},Ix=new WeakMap,Wx=25,Hx=.5,b0=6,Bx=.25,Dx=new WeakMap,Fx=new WeakMap,v0=(e,t)=>{var n;if(!e)return Wx*Hx;let r=Dx.get(e);Dx.set(e,t);let o=(n=Fx.get(e))!=null?n:Wx;if(r!==void 0){let a=t-r;a>1&&(o=o*(1-Bx)+a*Bx,Fx.set(e,o))}return Math.max(b0,o*Hx)},Za=new Map,C0=e=>{var r;let t=e.closest("[data-message-id]");return(r=t==null?void 0:t.dataset.messageId)!=null?r:null},w0=e=>{var t;e&&Za.set(e,((t=Za.get(e))!=null?t:0)+1)},S0=e=>{var r;if(!e)return;let t=(r=Za.get(e))!=null?r:0;t<=1?Za.delete(e):Za.set(e,t-1)},_x=e=>{var d;if(e.dataset.glyphCycleScheduled==="true")return;let t=(d=e.textContent)!=null?d:"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Kp();let r=C0(e);r&&(e.dataset.glyphCycleMessageId=r),w0(r);let o=e.closest(".persona-stream-glyph-cycle"),n=Date.now(),a=v0(o,n),s=Ox(e),i=f0*s,c=n+i;if(o){let u=Ix.get(o);u!==void 0&&(c=Math.max(c,u)),Ix.set(o,c+a)}A0(e,t,c)},A0=(e,t,r)=>{var s;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=Ox(e),n=(s=e.textContent)!=null?s:void 0,a=()=>{var c;if(!e.isConnected)return;if(Date.now()>=r){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,S0((c=e.dataset.glyphCycleMessageId)!=null?c:null),delete e.dataset.glyphCycleMessageId;return}let i=Kp(n);e.textContent=i,n=i,y0(e),setTimeout(a,o)};setTimeout(a,o)},Nx=e=>{var r;let t=(r=e.querySelectorAll)==null?void 0:r.call(e,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let o of Array.from(t))_x(o)},M0=e=>e.nodeType===1,T0={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:u0,bufferContent(e){if(e.length<h0)return"";let t=0,r=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(r=o),o+=1}return r<0?"":e.slice(0,r)},isAnimating(e){var t;return((t=Za.get(e.id))!=null?t:0)>0},onAttach(e){Nx(e);let t=new MutationObserver(r=>{for(let o of r)for(let n of Array.from(o.addedNodes))M0(n)&&(n.classList.contains("persona-stream-char")&&n.closest(".persona-stream-glyph-cycle")?_x(n):Nx(n))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};ca(T0);var Ux,qx,nr=typeof document!="undefined"&&(qx=(Ux=document.currentScript)==null?void 0:Ux.src)!=null?qx:null;bg(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${nr!=null?nr:"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});pg(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${nr!=null?nr:"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});mi().catch(e=>{typeof console!="undefined"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});th(()=>{let e=nr==null?void 0:nr.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===nr?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${nr!=null?nr:"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});return ty(E0);})();
181
181
  /*! Bundled license information:
182
182
 
183
183
  lucide/dist/esm/icons/activity.mjs: