@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.
package/dist/index.cjs CHANGED
@@ -1,20 +1,20 @@
1
- "use strict";var nh=Object.create;var ui=Object.defineProperty;var rh=Object.getOwnPropertyDescriptor;var oh=Object.getOwnPropertyNames;var sh=Object.getPrototypeOf,ah=Object.prototype.hasOwnProperty;var ha=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pl=(e,t)=>{for(var n in t)ui(e,n,{get:t[n],enumerable:!0})},tm=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of oh(t))!ah.call(e,s)&&s!==n&&ui(e,s,{get:()=>t[s],enumerable:!(r=rh(t,s))||r.enumerable});return e};var Il=(e,t,n)=>(n=e!=null?nh(sh(e)):{},tm(t||!e||!e.__esModule?ui(n,"default",{value:e,enumerable:!0}):n,e)),ih=e=>tm(ui({},"__esModule",{value:!0}),e);var om={};Pl(om,{DOMPurify:()=>rm.default,Marked:()=>nm.Marked});var nm,rm,sm=ha(()=>{"use strict";nm=require("marked"),rm=Il(require("dompurify"),1)});var Os,Gl=ha(()=>{"use strict";Os=class{constructor(t=24e3,n={}){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 s;this.sampleRate=t;let r=Math.max(0,(s=n.prebufferMs)!=null?s:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let s=new Uint8Array(this.remainder.length+t.length);s.set(this.remainder),s.set(t,this.remainder.length),n=s,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}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 n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let s=n.createBufferSource();s.buffer=r,s.connect(n.destination);let o=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=o:this.nextStartTime<o&&(this.nextStartTime=o,this.waterlineSamples>0&&(this.buffering=!0)),s.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}s.onended=()=>{let a=this.activeSources.indexOf(s);a!==-1&&this.activeSources.splice(a,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 n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}}});function ry(e){return e.replace(/\/+$/,"")}async function oy(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Wi,Ym=ha(()=>{"use strict";Gl();Wi=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Os(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var s,o,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;t===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;t===this.generation&&((g=r.onEnd)==null||g.call(r))});let c=`${ry(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(s=n.voice)!=null?s:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await oy(p));let m=p.body.getReader();for(;;){let{done:g,value:f}=await m.read();if(t!==this.generation){await m.cancel().catch(()=>{});return}if(g)break;f&&f.byteLength>0&&d.enqueue(f)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(o=this.opts).onError)==null||a.call(o,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var Hi,Zm=ha(()=>{"use strict";Hi=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var s;r=!0,(s=n.onStart)==null||s.call(n)},onEnd:()=>{var s;return(s=n.onEnd)==null?void 0:s.call(n)},onError:s=>{var o,a,i;if(r){(o=n.onError)==null||o.call(n,s);return}(i=(a=this.options).onFallback)==null||i.call(a,s),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,s;(n=(t=this.primary).destroy)==null||n.call(t),(s=(r=this.fallback).destroy)==null||s.call(r)}}});var eg={};Pl(eg,{FallbackSpeechEngine:()=>Hi,RuntypeSpeechEngine:()=>Wi});var tg=ha(()=>{"use strict";Ym();Zm()});var kx={};Pl(kx,{ASK_USER_QUESTION_CLIENT_TOOL:()=>zl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>ql,ASK_USER_QUESTION_TOOL_NAME:()=>va,AgentWidgetClient:()=>ns,AgentWidgetSession:()=>_s,AttachmentManager:()=>as,BrowserSpeechEngine:()=>Po,DEFAULT_COMPONENTS:()=>Zl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Di,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>tr,DEFAULT_PALETTE:()=>Xl,DEFAULT_SEMANTIC:()=>Yl,DEFAULT_WIDGET_CONFIG:()=>_t,PRESETS:()=>Fc,PRESET_FULLSCREEN:()=>Oc,PRESET_MINIMAL:()=>Nc,PRESET_SHOP:()=>Dc,ReadAloudController:()=>ss,SUGGEST_REPLIES_CLIENT_TOOL:()=>bi,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>$l,SUGGEST_REPLIES_TOOL_NAME:()=>Cr,THEME_ZONES:()=>cg,VERSION:()=>us,WEBMCP_TOOL_PREFIX:()=>Yr,WebMcpBridge:()=>Rs,accessibilityPlugin:()=>kf,animationsPlugin:()=>Lf,applyThemeVariables:()=>Io,attachHeaderToContainer:()=>ls,brandPlugin:()=>Pf,buildComposer:()=>zs,buildDefaultHeader:()=>ic,buildHeader:()=>oo,buildHeaderWithLayout:()=>qs,buildMinimalHeader:()=>lc,builtInClientToolsForDispatch:()=>Sa,collectEnrichedPageContext:()=>Tf,componentRegistry:()=>so,createActionManager:()=>Va,createAgentExperience:()=>bl,createAskUserQuestionBubble:()=>Rm,createBestAvailableVoiceProvider:()=>Ri,createBubbleWithLayout:()=>Hg,createCSATFeedback:()=>fl,createComboButton:()=>Xi,createComponentMiddleware:()=>of,createComponentStreamParser:()=>pl,createDefaultSanitizer:()=>Wl,createDemoCarousel:()=>Jf,createDirectivePostprocessor:()=>gm,createDropdownMenu:()=>Bo,createFlexibleJsonStreamParser:()=>Dm,createIconButton:()=>Kt,createImagePart:()=>Um,createJsonStreamParser:()=>Ei,createLabelButton:()=>Fa,createLocalStorageAdapter:()=>dl,createMarkdownProcessor:()=>ya,createMarkdownProcessorFromConfig:()=>Yo,createMessageActions:()=>fc,createNPSFeedback:()=>hl,createPlainTextParser:()=>Ai,createPlugin:()=>Wf,createRegexJsonParser:()=>Ti,createStandardBubble:()=>Vs,createTextPart:()=>Ea,createTheme:()=>js,createThemeObserver:()=>_i,createToggleGroup:()=>_a,createTypingIndicator:()=>cs,createVoiceProvider:()=>Lo,createWidgetHostLayout:()=>Ka,createXmlParser:()=>Mi,default:()=>Df,defaultActionHandlers:()=>ps,defaultJsonActionParser:()=>za,defaultParseRules:()=>Hc,detectColorScheme:()=>Ia,directivePostprocessor:()=>fm,ensureAskUserQuestionSheet:()=>Bs,escapeHtml:()=>Fr,extractComponentDirectiveFromMessage:()=>gl,fileToImagePart:()=>qm,formatEnrichedContext:()=>Ef,generateAssistantMessageId:()=>rs,generateCodeSnippet:()=>jf,generateMessageId:()=>Om,generateStableSelector:()=>Bc,generateUserMessageId:()=>Ns,getActiveTheme:()=>Us,getColorScheme:()=>tc,getDisplayText:()=>_m,getHeaderLayout:()=>cc,getImageParts:()=>jm,getPreset:()=>Bf,hasComponentDirective:()=>ml,hasImages:()=>$m,headerLayouts:()=>Yi,highContrastPlugin:()=>Rf,initAgentWidget:()=>Pc,isAskUserQuestionMessage:()=>Zr,isComponentDirectiveType:()=>rf,isDockedMountMode:()=>un,isSuggestRepliesMessage:()=>Ca,isVoiceSupported:()=>ka,isWebMcpToolName:()=>Zo,latestAgentSuggestions:()=>xi,listRegisteredStreamAnimations:()=>Tg,markdownPostprocessor:()=>Rl,mergeWithDefaults:()=>Ni,normalizeContent:()=>Fm,parseAskUserQuestionPayload:()=>eo,parseSuggestRepliesPayload:()=>Ul,pickBestVoice:()=>Fs,pluginRegistry:()=>qa,reducedMotionPlugin:()=>If,registerStreamAnimationPlugin:()=>Sg,removeAskUserQuestionSheet:()=>Mo,renderComponentDirective:()=>ul,renderLoadingIndicatorWithFallback:()=>gc,renderLucideIcon:()=>ve,resolveDockConfig:()=>nr,resolveSanitizer:()=>Is,resolveTokens:()=>Oi,stripWebMcpPrefix:()=>gi,themeToCssVariables:()=>Fi,unregisterStreamAnimationPlugin:()=>Ag,validateImageFile:()=>zm,validateTheme:()=>ec});module.exports=ih(kx);var cm=require("marked"),dm=Il(require("dompurify"),1);var am=null,Ls=null,ks=null;var im=e=>{Ls=e},lm=()=>Ls?Promise.resolve(Ls):ks||(am?(ks=am().then(e=>(Ls=e,e)),ks):(ks=Promise.resolve().then(()=>(sm(),om)).then(e=>(Ls=e,e)),ks)),Ps=()=>Ls;im({Marked:cm.Marked,DOMPurify:dm.default});var lh=e=>{if(e)return e},ya=e=>{let t=null;return n=>{var s,o;let r=Ps();if(!r)return Fr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(s=i==null?void 0:i.gfm)!=null?s:!0,breaks:(o=i==null?void 0:i.breaks)!=null?o:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=lh(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},Yo=e=>e?ya({markedOptions:e.options,renderer:e.renderer}):ya(),ch=ya(),Rl=e=>ch(e),Fr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),um=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),pm=e=>`%%FORM_PLACEHOLDER_${e}%%`,mm=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=pm(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=pm(t.length);return t.push({token:o,type:s}),o}),n},gm=e=>{let t=Yo(e);return n=>{let r=[],s=mm(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${um(i)}"></div>`;o=o.replace(d,p)}),o}},fm=e=>{let t=[],n=mm(e,t),r=Rl(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${um(o)}"></div>`;r=r.replace(a,d)}),r};var dh={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"]},ph=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Wl=()=>{let e=null;return t=>{let n=Ps();if(!n)return Fr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(s,o)=>{if(o.attrName==="src"||o.attrName==="href"){let a=o.attrValue;a.toLowerCase().startsWith("data:")&&!ph.test(a)&&(o.attrValue="",o.keepAttr=!1)}})}return e.sanitize(t,dh)}},Is=e=>e===!1?null:typeof e=="function"?e:Wl();var Yr="webmcp:",Hl=new Map,hm=e=>{var t;Hl.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Hl.set(n.name,r)}},Bl=e=>Hl.get(gi(e)),mi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},ym=null;function xm(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${uh(t.join(""))}`}function bm(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function uh(e){let t=bm(e,0).toString(36),n=bm(e,2654435761).toString(36);return`${t}.${n}`}var Rs=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return mi.warn("getTools() threw: shipping an empty WebMCP snapshot.",s),[]}hm(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=gh(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return wr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let x=typeof document!="undefined"&&!!document.modelContext;return wr(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 o=gi(t),a;try{a=await s.getTools()}catch(x){let v=x instanceof Error?x.message:String(x);return wr(`Failed to read WebMCP registry: ${v}`)}hm(a);let i=a.find(x=>x.name===o);if(!i)return wr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return wr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return wr("Aborted by cancel()");let d=Bl(o),c={toolName:o,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return wr("User declined the tool call.");if(r!=null&&r.aborted)return wr("Aborted by cancel()");let p=new AbortController,m=!1,g=setTimeout(()=>{m=!0,p.abort()},this.timeoutMs),f=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",f,{once:!0}));try{let x=await s.executeTool(i,bh(n),{signal:p.signal});return fh(x)}catch(x){if(m)return wr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return wr("Aborted by cancel()");let v=x instanceof Error?x.message:String(x);return wr(v)}finally{clearTimeout(g),r&&r.removeEventListener("abort",f)}}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}(ym?await ym():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 n=t;return typeof n.getTools!="function"||typeof n.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 r;let n=(r=this.confirmHandler)!=null?r:hh;try{return await n(t)}catch(s){return mi.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>mh(t,r))}},gi=e=>e.startsWith(Yr)?e.slice(Yr.length):e,Zo=e=>e.startsWith(Yr),mh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},gh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},fh=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:xh(t)}]}},wr=e=>({isError:!0,content:[{type:"text",text:e}]}),hh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=yh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var nh=Object.create;var ui=Object.defineProperty;var rh=Object.getOwnPropertyDescriptor;var oh=Object.getOwnPropertyNames;var sh=Object.getPrototypeOf,ah=Object.prototype.hasOwnProperty;var ha=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pl=(e,t)=>{for(var n in t)ui(e,n,{get:t[n],enumerable:!0})},tm=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of oh(t))!ah.call(e,s)&&s!==n&&ui(e,s,{get:()=>t[s],enumerable:!(r=rh(t,s))||r.enumerable});return e};var Il=(e,t,n)=>(n=e!=null?nh(sh(e)):{},tm(t||!e||!e.__esModule?ui(n,"default",{value:e,enumerable:!0}):n,e)),ih=e=>tm(ui({},"__esModule",{value:!0}),e);var om={};Pl(om,{DOMPurify:()=>rm.default,Marked:()=>nm.Marked});var nm,rm,sm=ha(()=>{"use strict";nm=require("marked"),rm=Il(require("dompurify"),1)});var Os,Gl=ha(()=>{"use strict";Os=class{constructor(t=24e3,n={}){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 s;this.sampleRate=t;let r=Math.max(0,(s=n.prebufferMs)!=null?s:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let s=new Uint8Array(this.remainder.length+t.length);s.set(this.remainder),s.set(t,this.remainder.length),n=s,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}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 n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let s=n.createBufferSource();s.buffer=r,s.connect(n.destination);let o=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=o:this.nextStartTime<o&&(this.nextStartTime=o,this.waterlineSamples>0&&(this.buffering=!0)),s.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}s.onended=()=>{let a=this.activeSources.indexOf(s);a!==-1&&this.activeSources.splice(a,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 n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}}});function oy(e){return e.replace(/\/+$/,"")}async function sy(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Wi,Zm=ha(()=>{"use strict";Gl();Wi=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Os(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var s,o,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;t===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;t===this.generation&&((g=r.onEnd)==null||g.call(r))});let c=`${oy(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(s=n.voice)!=null?s:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await sy(p));let m=p.body.getReader();for(;;){let{done:g,value:f}=await m.read();if(t!==this.generation){await m.cancel().catch(()=>{});return}if(g)break;f&&f.byteLength>0&&d.enqueue(f)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(o=this.opts).onError)==null||a.call(o,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var Hi,eg=ha(()=>{"use strict";Hi=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var s;r=!0,(s=n.onStart)==null||s.call(n)},onEnd:()=>{var s;return(s=n.onEnd)==null?void 0:s.call(n)},onError:s=>{var o,a,i;if(r){(o=n.onError)==null||o.call(n,s);return}(i=(a=this.options).onFallback)==null||i.call(a,s),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,s;(n=(t=this.primary).destroy)==null||n.call(t),(s=(r=this.fallback).destroy)==null||s.call(r)}}});var tg={};Pl(tg,{FallbackSpeechEngine:()=>Hi,RuntypeSpeechEngine:()=>Wi});var ng=ha(()=>{"use strict";Zm();eg()});var kx={};Pl(kx,{ASK_USER_QUESTION_CLIENT_TOOL:()=>zl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>ql,ASK_USER_QUESTION_TOOL_NAME:()=>va,AgentWidgetClient:()=>rs,AgentWidgetSession:()=>_s,AttachmentManager:()=>is,BrowserSpeechEngine:()=>Io,DEFAULT_COMPONENTS:()=>Zl,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Di,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>tr,DEFAULT_PALETTE:()=>Xl,DEFAULT_SEMANTIC:()=>Yl,DEFAULT_WIDGET_CONFIG:()=>_t,PRESETS:()=>Fc,PRESET_FULLSCREEN:()=>Oc,PRESET_MINIMAL:()=>Nc,PRESET_SHOP:()=>Dc,ReadAloudController:()=>as,SUGGEST_REPLIES_CLIENT_TOOL:()=>bi,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>$l,SUGGEST_REPLIES_TOOL_NAME:()=>Sr,THEME_ZONES:()=>dg,VERSION:()=>gr,WEBMCP_TOOL_PREFIX:()=>Zr,WebMcpBridge:()=>Rs,accessibilityPlugin:()=>kf,animationsPlugin:()=>Lf,applyThemeVariables:()=>Ro,attachHeaderToContainer:()=>cs,brandPlugin:()=>Pf,buildComposer:()=>zs,buildDefaultHeader:()=>ic,buildHeader:()=>so,buildHeaderWithLayout:()=>qs,buildMinimalHeader:()=>lc,builtInClientToolsForDispatch:()=>Sa,collectEnrichedPageContext:()=>Ef,componentRegistry:()=>ao,createActionManager:()=>Va,createAgentExperience:()=>bl,createAskUserQuestionBubble:()=>Rm,createBestAvailableVoiceProvider:()=>Ri,createBubbleWithLayout:()=>Bg,createCSATFeedback:()=>fl,createComboButton:()=>Xi,createComponentMiddleware:()=>sf,createComponentStreamParser:()=>pl,createDefaultSanitizer:()=>Wl,createDemoCarousel:()=>Jf,createDirectivePostprocessor:()=>gm,createDropdownMenu:()=>Do,createFlexibleJsonStreamParser:()=>Dm,createIconButton:()=>Kt,createImagePart:()=>qm,createJsonStreamParser:()=>Ei,createLabelButton:()=>Fa,createLocalStorageAdapter:()=>dl,createMarkdownProcessor:()=>ya,createMarkdownProcessorFromConfig:()=>Zo,createMessageActions:()=>fc,createNPSFeedback:()=>hl,createPlainTextParser:()=>Ai,createPlugin:()=>Wf,createRegexJsonParser:()=>Ti,createStandardBubble:()=>Vs,createTextPart:()=>Ea,createTheme:()=>js,createThemeObserver:()=>_i,createToggleGroup:()=>_a,createTypingIndicator:()=>ds,createVoiceProvider:()=>Po,createWidgetHostLayout:()=>Ka,createXmlParser:()=>Mi,default:()=>Df,defaultActionHandlers:()=>us,defaultJsonActionParser:()=>za,defaultParseRules:()=>Hc,detectColorScheme:()=>Ia,directivePostprocessor:()=>fm,ensureAskUserQuestionSheet:()=>Bs,escapeHtml:()=>_r,extractComponentDirectiveFromMessage:()=>gl,fileToImagePart:()=>zm,formatEnrichedContext:()=>Mf,generateAssistantMessageId:()=>os,generateCodeSnippet:()=>jf,generateMessageId:()=>Fm,generateStableSelector:()=>Bc,generateUserMessageId:()=>Ns,getActiveTheme:()=>Us,getColorScheme:()=>tc,getDisplayText:()=>$m,getHeaderLayout:()=>cc,getImageParts:()=>Um,getPreset:()=>Bf,hasComponentDirective:()=>ml,hasImages:()=>jm,headerLayouts:()=>Yi,highContrastPlugin:()=>Rf,initAgentWidget:()=>Pc,isAskUserQuestionMessage:()=>eo,isComponentDirectiveType:()=>of,isDockedMountMode:()=>un,isSuggestRepliesMessage:()=>Ca,isVoiceSupported:()=>ka,isWebMcpToolName:()=>es,latestAgentSuggestions:()=>xi,listRegisteredStreamAnimations:()=>Eg,markdownPostprocessor:()=>Rl,mergeWithDefaults:()=>Ni,normalizeContent:()=>_m,parseAskUserQuestionPayload:()=>to,parseSuggestRepliesPayload:()=>Ul,pickBestVoice:()=>Fs,pluginRegistry:()=>qa,reducedMotionPlugin:()=>If,registerStreamAnimationPlugin:()=>Ag,removeAskUserQuestionSheet:()=>ko,renderComponentDirective:()=>ul,renderLoadingIndicatorWithFallback:()=>gc,renderLucideIcon:()=>ve,resolveDockConfig:()=>nr,resolveSanitizer:()=>Is,resolveTokens:()=>Oi,stripWebMcpPrefix:()=>gi,themeToCssVariables:()=>Fi,unregisterStreamAnimationPlugin:()=>Tg,validateImageFile:()=>Vm,validateTheme:()=>ec});module.exports=ih(kx);var cm=require("marked"),dm=Il(require("dompurify"),1);var am=null,Ls=null,ks=null;var im=e=>{Ls=e},lm=()=>Ls?Promise.resolve(Ls):ks||(am?(ks=am().then(e=>(Ls=e,e)),ks):(ks=Promise.resolve().then(()=>(sm(),om)).then(e=>(Ls=e,e)),ks)),Ps=()=>Ls;im({Marked:cm.Marked,DOMPurify:dm.default});var lh=e=>{if(e)return e},ya=e=>{let t=null;return n=>{var s,o;let r=Ps();if(!r)return _r(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(s=i==null?void 0:i.gfm)!=null?s:!0,breaks:(o=i==null?void 0:i.breaks)!=null?o:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=lh(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},Zo=e=>e?ya({markedOptions:e.options,renderer:e.renderer}):ya(),ch=ya(),Rl=e=>ch(e),_r=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),um=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),pm=e=>`%%FORM_PLACEHOLDER_${e}%%`,mm=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=pm(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=pm(t.length);return t.push({token:o,type:s}),o}),n},gm=e=>{let t=Zo(e);return n=>{let r=[],s=mm(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${um(i)}"></div>`;o=o.replace(d,p)}),o}},fm=e=>{let t=[],n=mm(e,t),r=Rl(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${um(o)}"></div>`;r=r.replace(a,d)}),r};var dh={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"]},ph=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Wl=()=>{let e=null;return t=>{let n=Ps();if(!n)return _r(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(s,o)=>{if(o.attrName==="src"||o.attrName==="href"){let a=o.attrValue;a.toLowerCase().startsWith("data:")&&!ph.test(a)&&(o.attrValue="",o.keepAttr=!1)}})}return e.sanitize(t,dh)}},Is=e=>e===!1?null:typeof e=="function"?e:Wl();var Zr="webmcp:",Hl=new Map,hm=e=>{var t;Hl.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Hl.set(n.name,r)}},Bl=e=>Hl.get(gi(e)),mi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},ym=null;function xm(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${uh(t.join(""))}`}function bm(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function uh(e){let t=bm(e,0).toString(36),n=bm(e,2654435761).toString(36);return`${t}.${n}`}var Rs=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return mi.warn("getTools() threw: shipping an empty WebMCP snapshot.",s),[]}hm(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=gh(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return Cr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let x=typeof document!="undefined"&&!!document.modelContext;return Cr(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 o=gi(t),a;try{a=await s.getTools()}catch(x){let v=x instanceof Error?x.message:String(x);return Cr(`Failed to read WebMCP registry: ${v}`)}hm(a);let i=a.find(x=>x.name===o);if(!i)return Cr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return Cr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return Cr("Aborted by cancel()");let d=Bl(o),c={toolName:o,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return Cr("User declined the tool call.");if(r!=null&&r.aborted)return Cr("Aborted by cancel()");let p=new AbortController,m=!1,g=setTimeout(()=>{m=!0,p.abort()},this.timeoutMs),f=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",f,{once:!0}));try{let x=await s.executeTool(i,bh(n),{signal:p.signal});return fh(x)}catch(x){if(m)return Cr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return Cr("Aborted by cancel()");let v=x instanceof Error?x.message:String(x);return Cr(v)}finally{clearTimeout(g),r&&r.removeEventListener("abort",f)}}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}(ym?await ym():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 n=t;return typeof n.getTools!="function"||typeof n.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 r;let n=(r=this.confirmHandler)!=null?r:hh;try{return await n(t)}catch(s){return mi.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>mh(t,r))}},gi=e=>e.startsWith(Zr)?e.slice(Zr.length):e,es=e=>e.startsWith(Zr),mh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},gh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},fh=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:xh(t)}]}},Cr=e=>({isError:!0,content:[{type:"text",text:e}]}),hh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=yh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
2
2
 
3
3
  Arguments:
4
4
  ${t}`:"")+(e.description?`
5
5
 
6
- ${e.description}`:"");return window.confirm(n)},yh=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)}},bh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},xh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var To=require("partial-json");var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},_r=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Lt=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[o,a]of Object.entries(t.attrs))r.setAttribute(o,a);if(t.style){let o=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(o[i]=d)}}let s=n.filter(o=>o!=null);return s.length>0&&r.append(...s),r},ba=(...e)=>e.filter(Boolean).join(" ");var va="ask_user_question",xa=8,Ws="data-persona-ask-sheet-for",vh="Other",wh="Other\u2026",wm="Type your own answer here",Cm="Send",Ch="Next",Sh="Back",Ah="Submit all",Th="Skip",Eh=3,Dl="data-ask-current-index",Nl="data-ask-question-count",Sm="data-ask-answers",Ol="data-ask-grouped",Am="data-ask-layout",Mh=e=>e.layout==="pills"?"pills":"rows",kh=e=>e.getAttribute(Am)==="pills"?"pills":"rows",vm=!1,Tm=e=>e.replace(/["\\]/g,"\\$&"),Zr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===va,fi=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},eo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=(0,To.parse)(s,To.STR|To.OBJ|To.ARR);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},wa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>xa&&!vm&&(vm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${xa}.`)),t.slice(0,xa)},Lh=e=>{var t;return(t=wa(e)[0])!=null?t:null},Ph=(e,t)=>{var n;return(n=wa(e)[t])!=null?n:null},Em=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Mm=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=y("span","persona-ask-row-check");r.appendChild(s)}else{let s=y("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},Ih=(e,t,n,r)=>{let o=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}o.appendChild(a);let d=Mm(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Rh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Wh=(e,t,n,r)=>{var p,m,g;let o=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<Eh;f++)o.appendChild(Rh(r));return o}if(d.forEach((f,x)=>{o.appendChild(Ih(f,x,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?vh:wh;if(r==="rows"){let x=y("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(d.length)),x.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),A=document.createElement("input");A.type="text",A.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",A.placeholder=(p=t.freeTextPlaceholder)!=null?p:wm,A.setAttribute("data-ask-free-text-input","true"),A.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:f),v.appendChild(A),x.appendChild(v);let M=Mm(r,a,d.length);M&&x.appendChild(M),o.appendChild(x)}else{let x=y("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=(g=t.freeTextLabel)!=null?g:f,o.appendChild(x)}}return o},km=(e,t)=>{var o,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:wm,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Cm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Hh=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:Cm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Bh=(e,t,n)=>{var c,p,m,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=y("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(c=n.backLabel)!=null?c:Sh,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:Th,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:Ah:(g=n.nextLabel)!=null?g:Ch,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},es=e=>{let t=e.getAttribute(Sm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Lm=(e,t)=>{e.setAttribute(Sm,JSON.stringify(t))},mr=e=>{var n;let t=Number((n=e.getAttribute(Dl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Dh=(e,t)=>{e.setAttribute(Dl,String(Math.max(0,Math.floor(t))))},Hs=e=>{var n;let t=Number((n=e.getAttribute(Nl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Eo=e=>e.getAttribute(Ol)==="true",Nh=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Oh=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},hi=(e,t)=>{let{payload:n}=eo(t),r=wa(n),s=es(e),o={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(s,d)&&(o[c]=s[d]))}),o},Pm=e=>{let t=es(e),n=mr(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var m;let c=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Im=e=>{if(!Eo(e))return;let t=es(e),n=mr(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Fl=(e,t,n)=>{let r=fi(n),s=kh(e),{payload:o,complete:a}=eo(t),i=Eo(e),d=mr(e),c=Hs(e),p=i?Ph(o,d):Lh(o),m=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${c}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let B=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=B,x.classList.toggle("persona-ask-question-skeleton",!B&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let B=Wh(p,r,a,s);v.replaceWith(B)}if(s!=="rows"){let B=e.querySelector('[data-ask-free-text-row="true"]');B&&B.replaceWith(km(r,s))}let A=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!A?e.appendChild(Hh(r)):(!m||i)&&A&&A.remove(),e.setAttribute("data-multi-select",m?"true":"false");let M=e.querySelector('[data-ask-nav-row="true"]');if(i){let B=Bh(d,c,r);M?M.replaceWith(B):e.appendChild(B)}else M&&M.remove();Pm(e),Im(e)},Fh=(e,t,n)=>{let r=fi(t),s=Mh(r),o=e.toolCall.id,a=wa(n),i=Math.max(1,a.length),d=i>1,c=Nh(e,a),p=d?Oh(e,i):0,m=y("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ws,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(Nl,String(i)),m.setAttribute(Dl,String(p)),m.setAttribute(Ol,d?"true":"false"),m.setAttribute(Am,s),Lm(m,c),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Em(m,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",g.appendChild(x),m.appendChild(g);let A=y("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return A.setAttribute("data-ask-pill-list","true"),A.setAttribute("role","group"),m.appendChild(A),s!=="rows"&&m.appendChild(km(r,s)),Fl(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},_h=(e,t,n)=>{let{payload:r}=eo(t),s=Math.max(1,wa(r).length);s>Hs(e)&&(e.setAttribute(Nl,String(s)),s>1&&!Eo(e)&&e.setAttribute(Ol,"true")),Fl(e,t,n)},Rm=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=fi(t);Em(n,r);let s=y("span","persona-ask-stub-label"),{complete:o}=eo(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Bs=(e,t,n)=>{if(!n||!Zr(e)||fi(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${Ws}]`).forEach(c=>{c.getAttribute(Ws)!==s&&c.remove()});let a=n.querySelector(`[${Ws}="${Tm(s)}"]`);if(a){_h(a,e,t);return}let{payload:i}=eo(e),d=Fh(e,t,i);n.appendChild(d)},Mo=(e,t)=>{if(!e)return;let n=t?`[${Ws}="${Tm(t)}"]`:`[${Ws}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},_l=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ko=(e,t)=>{let n=es(e),r=mr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Lm(e,n),Pm(e),Im(e)},yi=(e,t,n,r)=>{let s=Hs(e),o=Math.max(0,Math.min(s-1,r));Dh(e,o),Fl(e,t,n)};var Cr="suggest_replies";var $l={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},bi={name:Cr,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:$l,origin:"sdk",annotations:{readOnlyHint:!0}},jl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ca=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Cr},Ul=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},xi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Ca(r))continue;let s=Ul((t=r.toolCall)==null?void 0:t.args);return s.length>0?s:null}return null},Wm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var ql={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:xa,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},zl={name:va,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:ql,origin:"sdk",annotations:{readOnlyHint:!0}},Sa=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(zl),Wm(e)&&t.push(bi),t};var to=require("partial-json"),vi=e=>e.replace(/\\n/g,`
6
+ ${e.description}`:"");return window.confirm(n)},yh=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)}},bh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},xh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Eo=require("partial-json");var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},$r=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Lt=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[o,a]of Object.entries(t.attrs))r.setAttribute(o,a);if(t.style){let o=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(o[i]=d)}}let s=n.filter(o=>o!=null);return s.length>0&&r.append(...s),r},ba=(...e)=>e.filter(Boolean).join(" ");var va="ask_user_question",xa=8,Ws="data-persona-ask-sheet-for",vh="Other",wh="Other\u2026",wm="Type your own answer here",Cm="Send",Ch="Next",Sh="Back",Ah="Submit all",Th="Skip",Eh=3,Dl="data-ask-current-index",Nl="data-ask-question-count",Sm="data-ask-answers",Ol="data-ask-grouped",Am="data-ask-layout",Mh=e=>e.layout==="pills"?"pills":"rows",kh=e=>e.getAttribute(Am)==="pills"?"pills":"rows",vm=!1,Tm=e=>e.replace(/["\\]/g,"\\$&"),eo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===va,fi=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},to=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=(0,Eo.parse)(s,Eo.STR|Eo.OBJ|Eo.ARR);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},wa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>xa&&!vm&&(vm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${xa}.`)),t.slice(0,xa)},Lh=e=>{var t;return(t=wa(e)[0])!=null?t:null},Ph=(e,t)=>{var n;return(n=wa(e)[t])!=null?n:null},Em=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Mm=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=y("span","persona-ask-row-check");r.appendChild(s)}else{let s=y("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},Ih=(e,t,n,r)=>{let o=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}o.appendChild(a);let d=Mm(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Rh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Wh=(e,t,n,r)=>{var p,m,g;let o=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<Eh;f++)o.appendChild(Rh(r));return o}if(d.forEach((f,x)=>{o.appendChild(Ih(f,x,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?vh:wh;if(r==="rows"){let x=y("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(d.length)),x.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),A=document.createElement("input");A.type="text",A.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",A.placeholder=(p=t.freeTextPlaceholder)!=null?p:wm,A.setAttribute("data-ask-free-text-input","true"),A.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:f),v.appendChild(A),x.appendChild(v);let M=Mm(r,a,d.length);M&&x.appendChild(M),o.appendChild(x)}else{let x=y("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=(g=t.freeTextLabel)!=null?g:f,o.appendChild(x)}}return o},km=(e,t)=>{var o,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:wm,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Cm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Hh=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:Cm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Bh=(e,t,n)=>{var c,p,m,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=y("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(c=n.backLabel)!=null?c:Sh,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:Th,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:Ah:(g=n.nextLabel)!=null?g:Ch,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},ts=e=>{let t=e.getAttribute(Sm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Lm=(e,t)=>{e.setAttribute(Sm,JSON.stringify(t))},mr=e=>{var n;let t=Number((n=e.getAttribute(Dl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Dh=(e,t)=>{e.setAttribute(Dl,String(Math.max(0,Math.floor(t))))},Hs=e=>{var n;let t=Number((n=e.getAttribute(Nl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Mo=e=>e.getAttribute(Ol)==="true",Nh=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Oh=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},hi=(e,t)=>{let{payload:n}=to(t),r=wa(n),s=ts(e),o={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(s,d)&&(o[c]=s[d]))}),o},Pm=e=>{let t=ts(e),n=mr(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var m;let c=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Im=e=>{if(!Mo(e))return;let t=ts(e),n=mr(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Fl=(e,t,n)=>{let r=fi(n),s=kh(e),{payload:o,complete:a}=to(t),i=Mo(e),d=mr(e),c=Hs(e),p=i?Ph(o,d):Lh(o),m=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${c}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let B=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=B,x.classList.toggle("persona-ask-question-skeleton",!B&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let B=Wh(p,r,a,s);v.replaceWith(B)}if(s!=="rows"){let B=e.querySelector('[data-ask-free-text-row="true"]');B&&B.replaceWith(km(r,s))}let A=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!A?e.appendChild(Hh(r)):(!m||i)&&A&&A.remove(),e.setAttribute("data-multi-select",m?"true":"false");let M=e.querySelector('[data-ask-nav-row="true"]');if(i){let B=Bh(d,c,r);M?M.replaceWith(B):e.appendChild(B)}else M&&M.remove();Pm(e),Im(e)},Fh=(e,t,n)=>{let r=fi(t),s=Mh(r),o=e.toolCall.id,a=wa(n),i=Math.max(1,a.length),d=i>1,c=Nh(e,a),p=d?Oh(e,i):0,m=y("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ws,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(Nl,String(i)),m.setAttribute(Dl,String(p)),m.setAttribute(Ol,d?"true":"false"),m.setAttribute(Am,s),Lm(m,c),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Em(m,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",g.appendChild(x),m.appendChild(g);let A=y("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return A.setAttribute("data-ask-pill-list","true"),A.setAttribute("role","group"),m.appendChild(A),s!=="rows"&&m.appendChild(km(r,s)),Fl(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},_h=(e,t,n)=>{let{payload:r}=to(t),s=Math.max(1,wa(r).length);s>Hs(e)&&(e.setAttribute(Nl,String(s)),s>1&&!Mo(e)&&e.setAttribute(Ol,"true")),Fl(e,t,n)},Rm=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=fi(t);Em(n,r);let s=y("span","persona-ask-stub-label"),{complete:o}=to(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Bs=(e,t,n)=>{if(!n||!eo(e)||fi(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${Ws}]`).forEach(c=>{c.getAttribute(Ws)!==s&&c.remove()});let a=n.querySelector(`[${Ws}="${Tm(s)}"]`);if(a){_h(a,e,t);return}let{payload:i}=to(e),d=Fh(e,t,i);n.appendChild(d)},ko=(e,t)=>{if(!e)return;let n=t?`[${Ws}="${Tm(t)}"]`:`[${Ws}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},_l=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Lo=(e,t)=>{let n=ts(e),r=mr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Lm(e,n),Pm(e),Im(e)},yi=(e,t,n,r)=>{let s=Hs(e),o=Math.max(0,Math.min(s-1,r));Dh(e,o),Fl(e,t,n)};var Sr="suggest_replies";var $l={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},bi={name:Sr,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:$l,origin:"sdk",annotations:{readOnlyHint:!0}},jl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ca=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Sr},Ul=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},xi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Ca(r))continue;let s=Ul((t=r.toolCall)==null?void 0:t.args);return s.length>0?s:null}return null},Wm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var ql={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:xa,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},zl={name:va,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:ql,origin:"sdk",annotations:{readOnlyHint:!0}},Sa=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(zl),Wm(e)&&t.push(bi),t};var no=require("partial-json"),vi=e=>e.replace(/\\n/g,`
7
7
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ds=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)}},$h=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Hm=e=>e.status==="complete"?$h(e):e.status==="pending"?"Waiting":"",jh=e=>{var s,o,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Bm=e=>e.status==="complete"?jh(e):"Using tool...",wi=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ta=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return wi(t)},Ci=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return wi(t)},Vl=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Ta(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Si=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&Aa(r,n.slice(o,a.index),[]),a[1]!==void 0?Aa(r,a[1],["bold"]):a[2]!==void 0?Aa(r,a[2],["italic"]):a[3]!==void 0&&Aa(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&Aa(r,n.slice(o),[]),r},Aa=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Uh=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},ts=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ai=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ti=()=>{var t;let e=Uh();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Ei=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=(0,to.parse)(n,to.STR|to.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?vi(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=vi(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Dm=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?vi(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?vi(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=(0,to.parse)(o,to.STR|to.OBJ),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Mi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ki=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var qh="https://api.runtype.com/v1/dispatch",Li="https://api.runtype.com";function zh(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Kl=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 Vh(e){switch(e){case"json":return Ei;case"regex-json":return Ti;case"xml":return Mi;default:return Ai}}var Nm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Kh(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=Nm(n);if(!Nm(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=ts(e);return ts(t)!==null&&a===null?t:e}var ns=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:qh,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Vh(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new Rs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Li}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Li}/v1/client/feedback`}async sendFeedback(t){var a,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 s={...t,...this.config.clientToken&&{token:this.config.clientToken}},o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!o.ok){let d=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let k=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:k}),k}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([k])=>k!=="sessionId"&&k!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(Kl).map(k=>{var H,S,I;return{id:k.id,role:k.role,content:(I=(S=(H=k.contentParts)!=null?H:k.llmContent)!=null?S:k.rawContent)!=null?I:k.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,f=!!(g&&g.length>0),x=f?xm(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,A=f&&v&&this.lastSentClientToolsFingerprint===x,M=!1,B=null,D;for(let k=0;;k++){let S={...m,...f&&(M||!A)&&g?{clientTools:g}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),D=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:r.signal}),D.status===409&&k===0&&f){let I=await D.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}B=I!=null?I:{error:"Chat request failed"}}break}if(!D.ok){let k=B!=null?B:await D.json().catch(()=>({error:"Chat request failed"}));if(D.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let S=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:S}),S}if(D.status===429){let S=new Error(k.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let H=new Error(k.error||"Failed to send message");throw n({type:"error",error:H}),H}if(!D.body){let k=new Error("No response body received");throw n({type:"error",error:k}),k}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(D.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Li}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Li}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Kl).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return c-p}).map(i=>{var d,c,p;return{role:i.role,content:(p=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Sa(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var o,a;let r={messages:t.slice().filter(Kl).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return c-p}).map(i=>{var d,c,p;return{role:i.role,content:(p=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=[...Sa(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=m,s(m),m},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var wn,Wt,mn,Ar;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=U=>{let G=U.reasoning?{...U.reasoning,chunks:[...U.reasoning.chunks]}:void 0,ye=U.toolCall?{...U.toolCall,chunks:U.toolCall.chunks?[...U.toolCall.chunks]:void 0}:void 0,Xe=U.tools?U.tools.map(rt=>({...rt,chunks:rt.chunks?[...rt.chunks]:void 0})):void 0;return{...U,reasoning:G,toolCall:ye,tools:Xe}},m=U=>{if(U.role!=="assistant"||U.variant)return!0;let G=Array.isArray(U.contentParts)&&U.contentParts.length>0,ye=typeof U.rawContent=="string"&&U.rawContent.trim()!=="";return typeof U.content=="string"&&U.content.trim()!==""||G||ye||!!U.stopReason},g=U=>{m(U)&&n({type:"message",message:p(U)})},f=null,x=null,v={current:null},A={current:null},M=!1,B=new Map,D=new Map,k=new Map,H=new Map,S={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},N=(U,G,ye="")=>`${U}::${G}::${ye}`,O=(U,G)=>`${U}::${G}::`,L=(U,G,ye,Xe)=>{let rt=N(U,G,ye),Ue=k.get(rt);if(Ue)return Ue;let $e=ye?`-${ye}`:"",Pt={id:`nested-${U}-${G}${$e}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...ye?{partId:ye}:{},agentMetadata:{executionId:Xe,parentToolId:U,parentStepId:G}};return k.set(rt,Pt),g(Pt),Pt},j=U=>{if(U==null)return null;try{return String(U)}catch{return null}},z=U=>{var G,ye,Xe,rt,Ue;return j((Ue=(rt=(Xe=(ye=(G=U.stepId)!=null?G:U.step_id)!=null?ye:U.step)!=null?Xe:U.parentId)!=null?rt:U.flowStepId)!=null?Ue:U.flow_step_id)},oe=U=>{var G,ye,Xe,rt,Ue,$e,Pt;return j((Pt=($e=(Ue=(rt=(Xe=(ye=(G=U.callId)!=null?G:U.call_id)!=null?ye:U.requestId)!=null?Xe:U.request_id)!=null?rt:U.toolCallId)!=null?Ue:U.tool_call_id)!=null?$e:U.stepId)!=null?Pt:U.step_id)},ke=r,Ke=!1,Ce=()=>{if(f)return f;let U;return!Ke&&ke?(U=ke,Ke=!0):ke&&A.current?U=`${ke}_${A.current}`:U=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:U,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(f),f},We=(U,G)=>{S.lastId=G,U&&S.byStep.set(U,G)},Ne=(U,G)=>{var Ue;let ye=(Ue=U.reasoningId)!=null?Ue:U.id,Xe=z(U);if(ye){let $e=String(ye);return We(Xe,$e),$e}if(Xe){let $e=S.byStep.get(Xe);if($e)return S.lastId=$e,$e}if(S.lastId&&!G)return S.lastId;if(!G)return null;let rt=`reason-${c()}`;return We(Xe,rt),rt},be=U=>{let G=B.get(U);if(G)return G;let ye={id:`reason-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:U,status:"streaming",chunks:[]}};return B.set(U,ye),g(ye),ye},Be=(U,G)=>{I.lastId=G,U&&I.byCall.set(U,G)},ue=new Set,Q=new Map,ne=new Set,pe=new Map,me=U=>{if(!U)return!1;let G=U.replace(/_+/g,"_").replace(/^_|_$/g,"");return G==="emit_artifact_markdown"||G==="emit_artifact_component"},K=(U,G)=>{var Ue;let ye=(Ue=U.toolId)!=null?Ue:U.id,Xe=oe(U);if(ye){let $e=String(ye);return Be(Xe,$e),$e}if(Xe){let $e=I.byCall.get(Xe);if($e)return I.lastId=$e,$e}if(I.lastId&&!G)return I.lastId;if(!G)return null;let rt=`tool-${c()}`;return Be(Xe,rt),rt},ae=U=>{let G=D.get(U);if(G)return G;let ye={id:`tool-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:U,status:"pending"}};return D.set(U,ye),g(ye),ye},He=U=>{if(typeof U=="number"&&Number.isFinite(U))return U;if(typeof U=="string"){let G=Number(U);if(!Number.isNaN(G)&&Number.isFinite(G))return G;let ye=Date.parse(U);if(!Number.isNaN(ye))return ye}return Date.now()},Y=U=>{if(typeof U=="string")return U;if(U==null)return"";try{return JSON.stringify(U)}catch{return String(U)}},ee=new Map,ie=new Map,Se=new Map,tt=new Map,Qe=null,Oe=(U,G,ye)=>{var Pt;let Xe=Se.get(U);Xe||(Xe=[],Se.set(U,Xe));let rt=0,Ue=Xe.length;for(;rt<Ue;){let Gt=rt+Ue>>>1;Xe[Gt].seq<G?rt=Gt+1:Ue=Gt}((Pt=Xe[rt])==null?void 0:Pt.seq)===G?Xe[rt]={seq:G,text:ye}:Xe.splice(rt,0,{seq:G,text:ye});let $e="";for(let Gt=0;Gt<Xe.length;Gt++)$e+=Xe[Gt].text;return $e},fe=(U,G)=>{let ye=Y(G),Xe=ie.get(U.id),rt=Kh(Xe,ye);U.rawContent=rt;let Ue=ee.get(U.id),$e=V=>{var le;let Ht=(le=U.content)!=null?le:"";V.trim()!==""&&(Ht.trim().length===0||V.startsWith(Ht)||V.trimStart().startsWith(Ht.trim()))&&(U.content=V)},Pt=()=>{var V;if(Ue){let Ht=(V=Ue.close)==null?void 0:V.call(Ue);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(U.id),ie.delete(U.id),U.streaming=!1,g(U)};if(!Ue){$e(ye),Pt();return}let Gt=ts(rt);if(Gt!==null&&Gt.trim()!==""){$e(Gt),Pt();return}let Yt=V=>{var Ae;let Ht=typeof V=="string"?V:(Ae=V==null?void 0:V.text)!=null?Ae:null;if(Ht!==null&&Ht.trim()!=="")return Ht;let le=Ue.getExtractedText();return le!==null&&le.trim()!==""?le:ye},Ln;try{Ln=Ue.processChunk(rt)}catch{$e(ye),Pt();return}if(Ln instanceof Promise){Ln.then(V=>{$e(Yt(V)),Pt()}).catch(()=>{$e(ye),Pt()});return}$e(Yt(Ln)),Pt()},nt=[],te=!1,ge,Me=()=>{te||(te=!0,queueMicrotask(()=>{te=!1,ge()}))},Ze=new ki((U,G)=>{nt.push({payloadType:U,payload:G}),Me()}),Je=null,Pe=new Map,Ge=(wn=this.config.iterationDisplay)!=null?wn:"separate";for(ge=()=>{var U,G,ye,Xe,rt,Ue,$e,Pt,Gt,Yt,Ln,V,Ht,le,Ae,_e,Tt,sn,an,Cn,Nt,at,Dt,pt,Zt,or,Pn,ln,Fn,Tr,vt,qn,Er,jr,fr,bt,No,Mr,Oo,_n,ms,io,Ur,lo,co,Fo,_o,po,Ct,zn,Vn,In,Et,sr,ar,Kn,uo,qr,mo,Gn,Ot,Rn,ir,go,zr,fo,kr,Jn,xe,ut,nn,gn,Lr,Ys,Vr,$o,Pr,_,gs,Ir,Rr,Kr,Wr,hr,fs,Ja,Qn,Xn,yr,br,jo,Gr,An,Hr,hs,Uo,ys,Qa,bs,Xa,xs,yt,Zs,lr,$n,Ya,Za,vs,Jr,ea,ho,ta,na,ra,oa,jn,ws,Br,Dr,sa,ei,aa,ia,qo,ti,ni,ri,oi,si,yo,bo,ai,la,xo,ii,ca,vo,da;for(let Cs=0;Cs<nt.length;Cs++){let qe=nt[Cs].payloadType,C=nt[Cs].payload;if(qe==="reason_start"){let $=(U=Ne(C,!0))!=null?U:`reason-${c()}`,E=be($);E.reasoning=(G=E.reasoning)!=null?G:{id:$,status:"streaming",chunks:[]},E.reasoning.startedAt=(Xe=E.reasoning.startedAt)!=null?Xe:He((ye=C.startedAt)!=null?ye:C.timestamp),E.reasoning.completedAt=void 0,E.reasoning.durationMs=void 0,E.streaming=!0,E.reasoning.status="streaming",g(E)}else if(qe==="reason_delta"||qe==="reason_chunk"){let $=(Ue=(rt=Ne(C,!1))!=null?rt:Ne(C,!0))!=null?Ue:`reason-${c()}`,E=be($);E.reasoning=($e=E.reasoning)!=null?$e:{id:$,status:"streaming",chunks:[]},E.reasoning.startedAt=(Gt=E.reasoning.startedAt)!=null?Gt:He((Pt=C.startedAt)!=null?Pt:C.timestamp);let X=(V=(Ln=(Yt=C.reasoningText)!=null?Yt:C.text)!=null?Ln:C.delta)!=null?V:"";if(X&&C.hidden!==!0){let se=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(se!==void 0){let J=Oe($,se,String(X));E.reasoning.chunks=[J]}else E.reasoning.chunks.push(String(X))}if(E.reasoning.status=C.done?"complete":"streaming",C.done){E.reasoning.completedAt=He((Ht=C.completedAt)!=null?Ht:C.timestamp);let se=(le=E.reasoning.startedAt)!=null?le:Date.now();E.reasoning.durationMs=Math.max(0,((Ae=E.reasoning.completedAt)!=null?Ae:Date.now())-se)}E.streaming=E.reasoning.status!=="complete",g(E)}else if(qe==="reason_complete"){let $=(Tt=(_e=Ne(C,!1))!=null?_e:Ne(C,!0))!=null?Tt:`reason-${c()}`,E=B.get($);if(E!=null&&E.reasoning){E.reasoning.status="complete",E.reasoning.completedAt=He((sn=C.completedAt)!=null?sn:C.timestamp);let se=(an=E.reasoning.startedAt)!=null?an:Date.now();E.reasoning.durationMs=Math.max(0,((Cn=E.reasoning.completedAt)!=null?Cn:Date.now())-se),E.streaming=!1,g(E)}let X=z(C);X&&S.byStep.delete(X)}else if(qe==="tool_start"){let $=(Nt=K(C,!0))!=null?Nt:`tool-${c()}`,E=(at=C.toolName)!=null?at:C.name;if(me(E)){ue.add($);continue}let X=ae($),se=(Dt=X.toolCall)!=null?Dt:{id:$,status:"pending"};se.name=E!=null?E:se.name,se.status="running",C.args!==void 0?se.args=C.args:C.parameters!==void 0&&(se.args=C.parameters),se.startedAt=(Zt=se.startedAt)!=null?Zt:He((pt=C.startedAt)!=null?pt:C.timestamp),se.completedAt=void 0,se.durationMs=void 0,X.toolCall=se,X.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(X.agentMetadata={executionId:(or=J==null?void 0:J.executionId)!=null?or:C.executionId,iteration:(Pn=J==null?void 0:J.iteration)!=null?Pn:C.iteration}),g(X)}else if(qe==="tool_chunk"||qe==="tool_delta"){let $=(Fn=(ln=K(C,!1))!=null?ln:K(C,!0))!=null?Fn:`tool-${c()}`;if(ue.has($))continue;let E=ae($),X=(Tr=E.toolCall)!=null?Tr:{id:$,status:"running"};X.startedAt=(qn=X.startedAt)!=null?qn:He((vt=C.startedAt)!=null?vt:C.timestamp);let se=(fr=(jr=(Er=C.text)!=null?Er:C.delta)!=null?jr:C.message)!=null?fr:"";se&&(X.chunks=(bt=X.chunks)!=null?bt:[],X.chunks.push(String(se))),X.status="running",E.toolCall=X,E.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(E.agentMetadata=(Oo=E.agentMetadata)!=null?Oo:{executionId:(No=J==null?void 0:J.executionId)!=null?No:C.executionId,iteration:(Mr=J==null?void 0:J.iteration)!=null?Mr:C.iteration}),g(E)}else if(qe==="tool_complete"){let $=(ms=(_n=K(C,!1))!=null?_n:K(C,!0))!=null?ms:`tool-${c()}`;if(ue.has($)){ue.delete($);continue}let E=ae($),X=(io=E.toolCall)!=null?io:{id:$,status:"running"};X.status="complete",C.result!==void 0&&(X.result=C.result),typeof C.duration=="number"&&(X.duration=C.duration),X.completedAt=He((Ur=C.completedAt)!=null?Ur:C.timestamp);let se=(lo=C.duration)!=null?lo:C.executionTime;if(typeof se=="number")X.durationMs=se;else{let je=(co=X.startedAt)!=null?co:Date.now();X.durationMs=Math.max(0,((Fo=X.completedAt)!=null?Fo:Date.now())-je)}E.toolCall=X,E.streaming=!1;let J=C.agentContext;(J||C.executionId)&&(E.agentMetadata=(Ct=E.agentMetadata)!=null?Ct:{executionId:(_o=J==null?void 0:J.executionId)!=null?_o:C.executionId,iteration:(po=J==null?void 0:J.iteration)!=null?po:C.iteration}),g(E);let Ee=oe(C);Ee&&I.byCall.delete(Ee)}else if(qe==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let $=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,E=(zn=$!=null?$:C.toolId)!=null?zn:`local-${c()}`,X=ae(E),se=C.toolName,J=Zo(se),Ee=(Vn=X.toolCall)!=null?Vn:{id:E,status:"pending"};Ee.name=se,Ee.args=C.parameters,Ee.status=J?"running":"complete",Ee.chunks=(In=Ee.chunks)!=null?In:[],Ee.startedAt=(sr=Ee.startedAt)!=null?sr:He((Et=C.startedAt)!=null?Et:C.timestamp),J?(Ee.completedAt=void 0,Ee.duration=void 0,Ee.durationMs=void 0):Ee.completedAt=(ar=Ee.completedAt)!=null?ar:Ee.startedAt,X.toolCall=Ee,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(uo=C.executionId)!=null?uo:(Kn=X.agentMetadata)==null?void 0:Kn.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},g(X)}else if(qe==="text_start"){if((qr=C.toolContext)!=null&&qr.toolId)continue;let $=C.partId;if($!==void 0&&A.current!==null&&$!==A.current){let E=f;E&&(E.streaming=!1,g(E),Qe=E,f=null,M=!0)}$!==void 0&&(A.current=$)}else if(qe==="text_end"){if((mo=C.toolContext)!=null&&mo.toolId)continue;let $=f;$&&($.streaming=!1,g($),Qe=$,f=null,M=!0)}else if(qe==="step_chunk"||qe==="step_delta"){let $=C.stepType,E=C.executionType;if($==="tool"||E==="context")continue;let X=C.toolContext;if(X!=null&&X.toolId){let je=String((Ot=(Gn=C.id)!=null?Gn:X.stepId)!=null?Ot:`step-${c()}`),lt=C.partId!==void 0&&C.partId!==null?String(C.partId):"",ot=`${X.toolId}::${je}`,Bt=H.get(ot);if(lt!==""&&Bt!==void 0&&Bt!==""&&Bt!==lt){let St=k.get(N(X.toolId,je,Bt));St&&St.streaming!==!1&&(St.streaming=!1,g(St))}lt!==""&&H.set(ot,lt);let qt=L(X.toolId,je,lt,X.executionId),cn=(zr=(go=(ir=(Rn=C.text)!=null?Rn:C.delta)!=null?ir:C.content)!=null?go:C.chunk)!=null?zr:"";cn&&(qt.content+=String(cn),qt.streaming=!0,g(qt)),C.isComplete&&(qt.streaming=!1,g(qt));continue}let se=C.partId;if(se!==void 0&&A.current!==null&&se!==A.current){let je=f;je&&(je.streaming=!1,g(je),Qe=je,f=null,M=!0)}se!==void 0&&(A.current=se);let J=se!==void 0&&(fo=tt.get(se))!=null?fo:Ce();se!==void 0&&(J.partId||(J.partId=se),tt.set(se,J));let Ee=(ut=(xe=(Jn=(kr=C.text)!=null?kr:C.delta)!=null?Jn:C.content)!=null?xe:C.chunk)!=null?ut:"";if(Ee){let je=typeof C.seq=="number"?C.seq:void 0,lt=se!=null?se:J.id,ot=je!==void 0?Oe(lt,je,String(Ee)):((nn=ie.get(J.id))!=null?nn:"")+Ee;J.rawContent=ot,ee.has(J.id)||ee.set(J.id,this.createStreamParser());let Bt=ee.get(J.id),qt=ot.trim().startsWith("{")||ot.trim().startsWith("[");if(qt&&ie.set(J.id,ot),Bt.__isPlainTextParser===!0){J.content=je!==void 0?ot:J.content+Ee,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,g(J);continue}let St=Bt.processChunk(ot);if(St instanceof Promise)St.then(Mt=>{var Wn;let xn=typeof Mt=="string"?Mt:(Wn=Mt==null?void 0:Mt.text)!=null?Wn:null;if(xn!==null&&xn.trim()!=="")J.content=xn,g(J);else if(!qt&&!ot.trim().startsWith("<")){let Sn=f,en=Sn&&Sn.id===J.id?Sn:J;en.id===J.id&&(en.content=je!==void 0?ot:en.content+Ee,ie.delete(en.id),ee.delete(en.id),en.rawContent=void 0,g(en))}}).catch(()=>{J.content=je!==void 0?ot:J.content+Ee,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,g(J)});else{let Mt=typeof St=="string"?St:(gn=St==null?void 0:St.text)!=null?gn:null;Mt!==null&&Mt.trim()!==""?(J.content=Mt,g(J)):!qt&&!ot.trim().startsWith("<")&&(J.content=je!==void 0?ot:J.content+Ee,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,g(J))}}if(C.isComplete){let je=(Ys=(Lr=C.result)==null?void 0:Lr.response)!=null?Ys:J.content;if(je){let lt=ie.get(J.id),ot=lt!=null?lt:Y(je);J.rawContent=ot;let Bt=ee.get(J.id),qt=null,cn=!1;if(Bt&&(qt=Bt.getExtractedText(),qt===null&&(qt=ts(ot)),qt===null)){let St=Bt.processChunk(ot);St instanceof Promise?(cn=!0,St.then(Mt=>{var Wn;let xn=typeof Mt=="string"?Mt:(Wn=Mt==null?void 0:Mt.text)!=null?Wn:null;if(xn!==null){let Sn=f;Sn&&Sn.id===J.id&&(Sn.content=xn,Sn.streaming=!1,ee.delete(Sn.id),ie.delete(Sn.id),g(Sn))}})):qt=typeof St=="string"?St:(Vr=St==null?void 0:St.text)!=null?Vr:null}if(!cn){qt!==null&&qt.trim()!==""?J.content=qt:ie.has(J.id)||(J.content=Y(je));let St=ee.get(J.id);if(St){let Mt=($o=St.close)==null?void 0:$o.call(St);Mt instanceof Promise&&Mt.catch(()=>{}),ee.delete(J.id)}ie.delete(J.id),J.streaming=!1,g(J)}}}}else if(qe==="step_complete"){let $=C.stepType,E=C.executionType;if($==="tool"||E==="context")continue;let X=C.toolContext;if(X!=null&&X.toolId){let je=String((_=(Pr=C.id)!=null?Pr:X.stepId)!=null?_:"");if(je){let lt=O(X.toolId,je);for(let[ot,Bt]of k)ot.startsWith(lt)&&Bt.streaming!==!1&&(Bt.streaming=!1,g(Bt));H.delete(`${X.toolId}::${je}`)}continue}let se=C.stopReason;if(M){if(f!==null){let ot=f;se&&(ot.stopReason=se),ee.delete(ot.id),ie.delete(ot.id),ot.streaming!==!1&&(ot.streaming=!1,g(ot))}let je=(gs=C.result)==null?void 0:gs.response,lt=Qe;lt&&(se&&(lt.stopReason=se),je!=null?fe(lt,je):(ee.delete(lt.id),ie.delete(lt.id))),Qe=null;continue}let J=(Ir=C.result)==null?void 0:Ir.response,Ee=Ce();if(se&&(Ee.stopReason=se),J!=null){let je=ee.get(Ee.id),lt=!1,ot=!1;if(je){let Bt=je.getExtractedText(),qt=ie.get(Ee.id),cn=qt!=null?qt:Y(J);if(Ee.rawContent=cn,Bt!==null&&Bt.trim()!=="")Ee.content=Bt,lt=!0;else{let St=ts(cn);if(St!==null)Ee.content=St,lt=!0;else{let Mt=je.processChunk(cn);if(Mt instanceof Promise)ot=!0,Mt.then(xn=>{var Sn;let Wn=typeof xn=="string"?xn:(Sn=xn==null?void 0:xn.text)!=null?Sn:null;if(Wn!==null&&Wn.trim()!==""){let en=f;en&&en.id===Ee.id&&(en.content=Wn,en.streaming=!1,ee.delete(en.id),ie.delete(en.id),g(en))}else{let en=je.getExtractedText(),cr=f;cr&&cr.id===Ee.id&&(en!==null&&en.trim()!==""?cr.content=en:ie.has(cr.id)||(cr.content=Y(J)),cr.streaming=!1,ee.delete(cr.id),ie.delete(cr.id),g(cr))}});else{let xn=typeof Mt=="string"?Mt:(Rr=Mt==null?void 0:Mt.text)!=null?Rr:null;if(xn!==null&&xn.trim()!=="")Ee.content=xn,lt=!0;else{let Wn=je.getExtractedText();Wn!==null&&Wn.trim()!==""&&(Ee.content=Wn,lt=!0)}}}}}if(!ot){if(!Ee.rawContent){let Bt=ie.get(Ee.id);Ee.rawContent=Bt!=null?Bt:Y(J)}if(!lt&&!ie.has(Ee.id)&&(Ee.content=Y(J)),je){let Bt=(Kr=je.close)==null?void 0:Kr.call(je);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Ee.id),ie.delete(Ee.id),Ee.streaming=!1,g(Ee)}}else ee.delete(Ee.id),ie.delete(Ee.id),Ee.streaming=!1,g(Ee)}else if(qe==="flow_complete"){let $=(Wr=C.result)==null?void 0:Wr.response;if(M){if(f!==null){let E=f;ee.delete(E.id),ie.delete(E.id),E.streaming!==!1&&(E.streaming=!1,g(E))}}else if($!=null){let E=Ce(),X=ie.get(E.id),se=X!=null?X:Y($);E.rawContent=se;let J=Y($),Ee=ee.get(E.id);if(Ee){let ot=ts(se);if(ot!==null)J=ot;else{let Bt=Ee.processChunk(se);Bt instanceof Promise&&Bt.then(cn=>{var Mt;let St=typeof cn=="string"?cn:(Mt=cn==null?void 0:cn.text)!=null?Mt:null;St!==null&&(E.content=St,E.streaming=!1,g(E))});let qt=Ee.getExtractedText();qt!==null&&(J=qt)}}ee.delete(E.id),ie.delete(E.id);let je=J!==E.content,lt=E.streaming!==!1;je&&(E.content=J),E.streaming=!1,(je||lt)&&g(E)}else if(f!==null){let E=f;ee.delete(E.id),ie.delete(E.id),E.streaming!==!1&&(E.streaming=!1,g(E))}n({type:"status",status:"idle"})}else if(qe==="agent_start")Je={executionId:C.executionId,agentId:(hr=C.agentId)!=null?hr:"virtual",agentName:(fs=C.agentName)!=null?fs:"",status:"running",currentIteration:0,maxTurns:(Ja=C.maxTurns)!=null?Ja:1,startedAt:He(C.startedAt)};else if(qe==="agent_iteration_start"){if(Je&&(Je.currentIteration=C.iteration),Ge==="separate"&&C.iteration>1){let $=f;$&&($.streaming=!1,g($),Pe.set(C.iteration-1,$),f=null)}}else if(qe==="agent_turn_start")x=null;else if(qe==="agent_turn_delta"){if(C.contentType==="text"){let $=Ce();$.content+=(Qn=C.delta)!=null?Qn:"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:Je==null?void 0:Je.agentName},x=$,g($)}else if(C.contentType==="thinking"){let $=(Xn=C.turnId)!=null?Xn:`agent-think-${C.iteration}`,E=be($);E.reasoning=(yr=E.reasoning)!=null?yr:{id:$,status:"streaming",chunks:[]},E.reasoning.chunks.push((br=C.delta)!=null?br:""),E.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},g(E)}else if(C.contentType==="tool_input"){let $=(jo=C.toolCallId)!=null?jo:I.lastId;if($){let E=D.get($);E!=null&&E.toolCall&&(E.toolCall.chunks=(Gr=E.toolCall.chunks)!=null?Gr:[],E.toolCall.chunks.push((An=C.delta)!=null?An:""),g(E))}}}else if(qe==="agent_turn_complete"){let $=C.turnId;if($){let se=B.get($);if(se!=null&&se.reasoning){se.reasoning.status="complete",se.reasoning.completedAt=He(C.completedAt);let J=(Hr=se.reasoning.startedAt)!=null?Hr:Date.now();se.reasoning.durationMs=Math.max(0,((hs=se.reasoning.completedAt)!=null?hs:Date.now())-J),se.streaming=!1,g(se)}}let E=C.stopReason,X=f!=null?f:x;if(E&&X!==null){let se=C.turnId;(!se||((Uo=X.agentMetadata)==null?void 0:Uo.turnId)===se)&&(X.stopReason=E,g(X))}}else if(qe==="agent_tool_start"){f&&(f.streaming=!1,g(f),f=null);let $=(ys=C.toolCallId)!=null?ys:`agent-tool-${c()}`;Be(oe(C),$);let E=ae($),X=(Qa=E.toolCall)!=null?Qa:{id:$,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=(Xa=(bs=C.toolName)!=null?bs:C.name)!=null?Xa:X.name,X.status="running",C.parameters!==void 0&&(X.args=C.parameters),X.startedAt=He((xs=C.startedAt)!=null?xs:C.timestamp),E.toolCall=X,E.streaming=!0,E.agentMetadata={executionId:C.executionId,iteration:C.iteration},g(E)}else if(qe==="agent_tool_delta"){let $=(yt=C.toolCallId)!=null?yt:I.lastId;if($){let E=(Zs=D.get($))!=null?Zs:ae($);E.toolCall&&(E.toolCall.chunks=(lr=E.toolCall.chunks)!=null?lr:[],E.toolCall.chunks.push(($n=C.delta)!=null?$n:""),E.toolCall.status="running",E.streaming=!0,g(E))}}else if(qe==="agent_tool_complete"){let $=(Ya=C.toolCallId)!=null?Ya:I.lastId;if($){let E=(Za=D.get($))!=null?Za:ae($);if(E.toolCall){E.toolCall.status="complete",C.result!==void 0&&(E.toolCall.result=C.result),typeof C.executionTime=="number"&&(E.toolCall.durationMs=C.executionTime),E.toolCall.completedAt=He((vs=C.completedAt)!=null?vs:C.timestamp),E.streaming=!1,g(E);let X=oe(C);X&&I.byCall.delete(X)}}}else if(qe==="agent_media"){let $=Array.isArray(C.media)?C.media:[],E=[];for(let X of $){if(!X||typeof X!="object")continue;let se=X,J=typeof se.type=="string"?se.type:void 0,Ee=typeof se.mediaType=="string"?se.mediaType.toLowerCase():"",je=null,lt="";if(J==="media"){let ot=typeof se.data=="string"?se.data:void 0;if(!ot)continue;lt=Ee.length>0?Ee:"application/octet-stream",je=`data:${lt};base64,${ot}`}else if(J==="image-url"){let ot=typeof se.url=="string"?se.url:void 0;if(!ot)continue;lt=Ee,je=ot}else if(J==="file-url"){let ot=typeof se.url=="string"?se.url:void 0;if(!ot)continue;lt=Ee,je=ot}else continue;if(je)if(J==="image-url"||lt.startsWith("image/"))E.push({type:"image",image:je,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))E.push({type:"audio",audio:je,mimeType:lt});else if(lt.startsWith("video/"))E.push({type:"video",video:je,mimeType:lt});else{let ot=lt||"application/octet-stream";E.push({type:"file",data:je,mimeType:ot,filename:zh(ot)})}}if(E.length>0){let X=c(),se=C.toolCallId,Ee={id:`agent-media-${typeof se=="string"&&se.length>0?`${se}-${X}`:String(X)}`,role:"assistant",content:"",contentParts:E,createdAt:new Date().toISOString(),streaming:!1,sequence:X,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};g(Ee);let je=f;je&&(je.streaming=!1,g(je)),f=null,v.current=null}}else if(qe!=="agent_iteration_complete"){if(qe==="agent_reflection"||qe==="agent_reflect"){let $=`agent-reflection-${C.executionId}-${C.iteration}`,E={id:$,role:"assistant",content:(Jr=C.reflection)!=null?Jr:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(ea=C.reflection)!=null?ea:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};g(E)}else if(qe==="agent_complete"){Je&&(Je.status=C.success?"complete":"error",Je.completedAt=He(C.completedAt),Je.stopReason=C.stopReason);let $=f;$&&($.streaming=!1,g($)),n({type:"status",status:"idle"})}else if(qe==="agent_error"){let $=typeof C.error=="string"?C.error:(ta=(ho=C.error)==null?void 0:ho.message)!=null?ta:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):n({type:"error",error:new Error($)})}else if(qe!=="agent_ping"){if(qe==="agent_approval_start"){let $=(na=C.approvalId)!=null?na:`approval-${c()}`,E={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(ra=Je==null?void 0:Je.agentId)!=null?ra:"virtual",executionId:(jn=(oa=C.executionId)!=null?oa:Je==null?void 0:Je.executionId)!=null?jn:"",toolName:(ws=C.toolName)!=null?ws:"",toolType:C.toolType,description:(Dr=C.description)!=null?Dr:`Execute ${(Br=C.toolName)!=null?Br:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};g(E)}else if(qe==="step_await"&&C.awaitReason==="approval_required"){let $=(sa=C.approvalId)!=null?sa:`approval-${c()}`,E={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(ei=Je==null?void 0:Je.agentId)!=null?ei:"virtual",executionId:(ia=(aa=C.executionId)!=null?aa:Je==null?void 0:Je.executionId)!=null?ia:"",toolName:(qo=C.toolName)!=null?qo:"",toolType:C.toolType,description:(ni=C.description)!=null?ni:`Execute ${(ti=C.toolName)!=null?ti:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};g(E)}else if(qe==="agent_approval_complete"){let $=C.approvalId;if($){let X={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(ri=C.decision)!=null?ri:"approved",agentId:(oi=Je==null?void 0:Je.agentId)!=null?oi:"virtual",executionId:(yo=(si=C.executionId)!=null?si:Je==null?void 0:Je.executionId)!=null?yo:"",toolName:(bo=C.toolName)!=null?bo:"",description:(ai=C.description)!=null?ai:"",resolvedAt:Date.now()}};g(X)}}else if(qe==="artifact_start"||qe==="artifact_delta"||qe==="artifact_update"||qe==="artifact_complete"){if(qe==="artifact_start"){let $=C.artifactType,E=String(C.id),X=typeof C.title=="string"?C.title:void 0;if(n({type:"artifact_start",id:E,artifactType:$,title:X,component:typeof C.component=="string"?C.component:void 0}),pe.set(E,{markdown:"",title:X}),!ne.has(E)){ne.add(E);let se={id:`artifact-ref-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:E,title:X,artifactType:$,status:"streaming"}})};Q.set(E,se),g(se)}}else if(qe==="artifact_delta"){let $=String(C.id),E=typeof C.delta=="string"?C.delta:String((la=C.delta)!=null?la:"");n({type:"artifact_delta",id:$,artDelta:E});let X=pe.get($);X&&(X.markdown+=E)}else if(qe==="artifact_update"){let $=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(qe==="artifact_complete"){let $=String(C.id);n({type:"artifact_complete",id:$});let E=Q.get($);if(E){E.streaming=!1;try{let X=JSON.parse((xo=E.rawContent)!=null?xo:"{}");if(X.props){X.props.status="complete";let se=pe.get($);se!=null&&se.markdown&&(X.props.markdown=se.markdown)}E.rawContent=JSON.stringify(X)}catch{}pe.delete($),g(E),Q.delete($)}}}else if(qe==="transcript_insert"){let $=C.message;if(!$||typeof $!="object")continue;let E=String((ii=$.id)!=null?ii:`msg-${c()}`),X=$.role,J={id:E,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:c()};if(g(J),J.rawContent)try{let Ee=JSON.parse(J.rawContent),je=(ca=Ee==null?void 0:Ee.props)==null?void 0:ca.artifactId;typeof je=="string"&&ne.add(je)}catch{}f=null,v.current=null,ee.delete(E),ie.delete(E)}else if(qe==="error"||qe==="step_error"||qe==="dispatch_error"||qe==="flow_error"){let $=null;if(C.error instanceof Error)$=C.error;else if(qe==="dispatch_error"){let E=(vo=C.message)!=null?vo:C.error;E!=null&&E!==""&&($=new Error(String(E)))}else if(qe==="step_error"||qe==="flow_error"){let E=C.error;typeof E=="string"&&E!==""?$=new Error(E):E!=null&&typeof E=="object"&&"message"in E&&($=new Error(String((da=E.message)!=null?da:E)))}else qe==="error"&&C.error!=null&&C.error!==""&&($=new Error(String(C.error)));if($){n({type:"error",error:$});let E=f;E&&E.streaming&&(E.streaming=!1,g(E)),n({type:"status",status:"idle"})}}}}}nt.length=0};;){let{done:U,value:G}=await s.read();if(U)break;a+=o.decode(G,{stream:!0});let ye=a.split(`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},ns=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ai=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ti=()=>{var t;let e=Uh();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Ei=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=(0,no.parse)(n,no.STR|no.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?vi(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=vi(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Dm=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?vi(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?vi(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=(0,no.parse)(o,no.STR|no.OBJ),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Mi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ki=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Nm="3.36.0";var gr=Nm;var zh="https://api.runtype.com/v1/dispatch",Li="https://api.runtype.com";function Vh(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Kl=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 Kh(e){switch(e){case"json":return Ei;case"regex-json":return Ti;case"xml":return Mi;default:return Ai}}var Om=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Gh(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=Om(n);if(!Om(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=ns(e);return ns(t)!==null&&a===null?t:e}var rs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:zh,this.headers={"Content-Type":"application/json","X-Persona-Version":gr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Kh(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new Rs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Li}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":gr},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Li}/v1/client/feedback`}async sendFeedback(t){var a,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 s={...t,...this.config.clientToken&&{token:this.config.clientToken}},o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":gr},body:JSON.stringify(s)});if(!o.ok){let d=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let k=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:k}),k}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([k])=>k!=="sessionId"&&k!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(Kl).map(k=>{var H,S,I;return{id:k.id,role:k.role,content:(I=(S=(H=k.contentParts)!=null?H:k.llmContent)!=null?S:k.rawContent)!=null?I:k.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,f=!!(g&&g.length>0),x=f?xm(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,A=f&&v&&this.lastSentClientToolsFingerprint===x,M=!1,B=null,D;for(let k=0;;k++){let S={...m,...f&&(M||!A)&&g?{clientTools:g}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),D=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":gr},body:JSON.stringify(S),signal:r.signal}),D.status===409&&k===0&&f){let I=await D.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}B=I!=null?I:{error:"Chat request failed"}}break}if(!D.ok){let k=B!=null?B:await D.json().catch(()=>({error:"Chat request failed"}));if(D.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let S=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:S}),S}if(D.status===429){let S=new Error(k.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let H=new Error(k.error||"Failed to send message");throw n({type:"error",error:H}),H}if(!D.body){let k=new Error("No response body received");throw n({type:"error",error:k}),k}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(D.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Li}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Li}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Kl).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return c-p}).map(i=>{var d,c,p;return{role:i.role,content:(p=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Sa(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var o,a;let r={messages:t.slice().filter(Kl).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return c-p}).map(i=>{var d,c,p;return{role:i.role,content:(p=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=[...Sa(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=m,s(m),m},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var wn,Wt,mn,Tr;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=U=>{let G=U.reasoning?{...U.reasoning,chunks:[...U.reasoning.chunks]}:void 0,ye=U.toolCall?{...U.toolCall,chunks:U.toolCall.chunks?[...U.toolCall.chunks]:void 0}:void 0,Xe=U.tools?U.tools.map(rt=>({...rt,chunks:rt.chunks?[...rt.chunks]:void 0})):void 0;return{...U,reasoning:G,toolCall:ye,tools:Xe}},m=U=>{if(U.role!=="assistant"||U.variant)return!0;let G=Array.isArray(U.contentParts)&&U.contentParts.length>0,ye=typeof U.rawContent=="string"&&U.rawContent.trim()!=="";return typeof U.content=="string"&&U.content.trim()!==""||G||ye||!!U.stopReason},g=U=>{m(U)&&n({type:"message",message:p(U)})},f=null,x=null,v={current:null},A={current:null},M=!1,B=new Map,D=new Map,k=new Map,H=new Map,S={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},N=(U,G,ye="")=>`${U}::${G}::${ye}`,O=(U,G)=>`${U}::${G}::`,L=(U,G,ye,Xe)=>{let rt=N(U,G,ye),Ue=k.get(rt);if(Ue)return Ue;let $e=ye?`-${ye}`:"",Pt={id:`nested-${U}-${G}${$e}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...ye?{partId:ye}:{},agentMetadata:{executionId:Xe,parentToolId:U,parentStepId:G}};return k.set(rt,Pt),g(Pt),Pt},j=U=>{if(U==null)return null;try{return String(U)}catch{return null}},z=U=>{var G,ye,Xe,rt,Ue;return j((Ue=(rt=(Xe=(ye=(G=U.stepId)!=null?G:U.step_id)!=null?ye:U.step)!=null?Xe:U.parentId)!=null?rt:U.flowStepId)!=null?Ue:U.flow_step_id)},oe=U=>{var G,ye,Xe,rt,Ue,$e,Pt;return j((Pt=($e=(Ue=(rt=(Xe=(ye=(G=U.callId)!=null?G:U.call_id)!=null?ye:U.requestId)!=null?Xe:U.request_id)!=null?rt:U.toolCallId)!=null?Ue:U.tool_call_id)!=null?$e:U.stepId)!=null?Pt:U.step_id)},ke=r,Ke=!1,Ce=()=>{if(f)return f;let U;return!Ke&&ke?(U=ke,Ke=!0):ke&&A.current?U=`${ke}_${A.current}`:U=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:U,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(f),f},We=(U,G)=>{S.lastId=G,U&&S.byStep.set(U,G)},Ne=(U,G)=>{var Ue;let ye=(Ue=U.reasoningId)!=null?Ue:U.id,Xe=z(U);if(ye){let $e=String(ye);return We(Xe,$e),$e}if(Xe){let $e=S.byStep.get(Xe);if($e)return S.lastId=$e,$e}if(S.lastId&&!G)return S.lastId;if(!G)return null;let rt=`reason-${c()}`;return We(Xe,rt),rt},be=U=>{let G=B.get(U);if(G)return G;let ye={id:`reason-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:U,status:"streaming",chunks:[]}};return B.set(U,ye),g(ye),ye},Be=(U,G)=>{I.lastId=G,U&&I.byCall.set(U,G)},ue=new Set,Q=new Map,ne=new Set,pe=new Map,me=U=>{if(!U)return!1;let G=U.replace(/_+/g,"_").replace(/^_|_$/g,"");return G==="emit_artifact_markdown"||G==="emit_artifact_component"},K=(U,G)=>{var Ue;let ye=(Ue=U.toolId)!=null?Ue:U.id,Xe=oe(U);if(ye){let $e=String(ye);return Be(Xe,$e),$e}if(Xe){let $e=I.byCall.get(Xe);if($e)return I.lastId=$e,$e}if(I.lastId&&!G)return I.lastId;if(!G)return null;let rt=`tool-${c()}`;return Be(Xe,rt),rt},ae=U=>{let G=D.get(U);if(G)return G;let ye={id:`tool-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:U,status:"pending"}};return D.set(U,ye),g(ye),ye},He=U=>{if(typeof U=="number"&&Number.isFinite(U))return U;if(typeof U=="string"){let G=Number(U);if(!Number.isNaN(G)&&Number.isFinite(G))return G;let ye=Date.parse(U);if(!Number.isNaN(ye))return ye}return Date.now()},Y=U=>{if(typeof U=="string")return U;if(U==null)return"";try{return JSON.stringify(U)}catch{return String(U)}},ee=new Map,ie=new Map,Se=new Map,tt=new Map,Qe=null,Oe=(U,G,ye)=>{var Pt;let Xe=Se.get(U);Xe||(Xe=[],Se.set(U,Xe));let rt=0,Ue=Xe.length;for(;rt<Ue;){let Gt=rt+Ue>>>1;Xe[Gt].seq<G?rt=Gt+1:Ue=Gt}((Pt=Xe[rt])==null?void 0:Pt.seq)===G?Xe[rt]={seq:G,text:ye}:Xe.splice(rt,0,{seq:G,text:ye});let $e="";for(let Gt=0;Gt<Xe.length;Gt++)$e+=Xe[Gt].text;return $e},fe=(U,G)=>{let ye=Y(G),Xe=ie.get(U.id),rt=Gh(Xe,ye);U.rawContent=rt;let Ue=ee.get(U.id),$e=V=>{var le;let Ht=(le=U.content)!=null?le:"";V.trim()!==""&&(Ht.trim().length===0||V.startsWith(Ht)||V.trimStart().startsWith(Ht.trim()))&&(U.content=V)},Pt=()=>{var V;if(Ue){let Ht=(V=Ue.close)==null?void 0:V.call(Ue);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(U.id),ie.delete(U.id),U.streaming=!1,g(U)};if(!Ue){$e(ye),Pt();return}let Gt=ns(rt);if(Gt!==null&&Gt.trim()!==""){$e(Gt),Pt();return}let Yt=V=>{var Ae;let Ht=typeof V=="string"?V:(Ae=V==null?void 0:V.text)!=null?Ae:null;if(Ht!==null&&Ht.trim()!=="")return Ht;let le=Ue.getExtractedText();return le!==null&&le.trim()!==""?le:ye},Ln;try{Ln=Ue.processChunk(rt)}catch{$e(ye),Pt();return}if(Ln instanceof Promise){Ln.then(V=>{$e(Yt(V)),Pt()}).catch(()=>{$e(ye),Pt()});return}$e(Yt(Ln)),Pt()},nt=[],te=!1,ge,Me=()=>{te||(te=!0,queueMicrotask(()=>{te=!1,ge()}))},Ze=new ki((U,G)=>{nt.push({payloadType:U,payload:G}),Me()}),Je=null,Pe=new Map,Ge=(wn=this.config.iterationDisplay)!=null?wn:"separate";for(ge=()=>{var U,G,ye,Xe,rt,Ue,$e,Pt,Gt,Yt,Ln,V,Ht,le,Ae,_e,Tt,sn,an,Cn,Nt,at,Dt,pt,Zt,or,Pn,ln,Fn,Er,vt,qn,Mr,Ur,hr,bt,Oo,kr,Fo,_n,ms,lo,qr,co,po,_o,$o,uo,Ct,zn,Vn,In,Et,sr,ar,Kn,mo,zr,go,Gn,Ot,Rn,ir,fo,Vr,ho,Lr,Jn,xe,ut,nn,gn,Pr,Ys,Kr,jo,Ir,_,gs,Rr,Wr,Gr,Hr,yr,fs,Ja,Qn,Xn,br,xr,Uo,Jr,An,Br,hs,qo,ys,Qa,bs,Xa,xs,yt,Zs,lr,$n,Ya,Za,vs,Qr,ea,yo,ta,na,ra,oa,jn,ws,Dr,Nr,sa,ei,aa,ia,zo,ti,ni,ri,oi,si,bo,xo,ai,la,vo,ii,ca,wo,da;for(let Cs=0;Cs<nt.length;Cs++){let qe=nt[Cs].payloadType,C=nt[Cs].payload;if(qe==="reason_start"){let $=(U=Ne(C,!0))!=null?U:`reason-${c()}`,E=be($);E.reasoning=(G=E.reasoning)!=null?G:{id:$,status:"streaming",chunks:[]},E.reasoning.startedAt=(Xe=E.reasoning.startedAt)!=null?Xe:He((ye=C.startedAt)!=null?ye:C.timestamp),E.reasoning.completedAt=void 0,E.reasoning.durationMs=void 0,E.streaming=!0,E.reasoning.status="streaming",g(E)}else if(qe==="reason_delta"||qe==="reason_chunk"){let $=(Ue=(rt=Ne(C,!1))!=null?rt:Ne(C,!0))!=null?Ue:`reason-${c()}`,E=be($);E.reasoning=($e=E.reasoning)!=null?$e:{id:$,status:"streaming",chunks:[]},E.reasoning.startedAt=(Gt=E.reasoning.startedAt)!=null?Gt:He((Pt=C.startedAt)!=null?Pt:C.timestamp);let X=(V=(Ln=(Yt=C.reasoningText)!=null?Yt:C.text)!=null?Ln:C.delta)!=null?V:"";if(X&&C.hidden!==!0){let se=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(se!==void 0){let J=Oe($,se,String(X));E.reasoning.chunks=[J]}else E.reasoning.chunks.push(String(X))}if(E.reasoning.status=C.done?"complete":"streaming",C.done){E.reasoning.completedAt=He((Ht=C.completedAt)!=null?Ht:C.timestamp);let se=(le=E.reasoning.startedAt)!=null?le:Date.now();E.reasoning.durationMs=Math.max(0,((Ae=E.reasoning.completedAt)!=null?Ae:Date.now())-se)}E.streaming=E.reasoning.status!=="complete",g(E)}else if(qe==="reason_complete"){let $=(Tt=(_e=Ne(C,!1))!=null?_e:Ne(C,!0))!=null?Tt:`reason-${c()}`,E=B.get($);if(E!=null&&E.reasoning){E.reasoning.status="complete",E.reasoning.completedAt=He((sn=C.completedAt)!=null?sn:C.timestamp);let se=(an=E.reasoning.startedAt)!=null?an:Date.now();E.reasoning.durationMs=Math.max(0,((Cn=E.reasoning.completedAt)!=null?Cn:Date.now())-se),E.streaming=!1,g(E)}let X=z(C);X&&S.byStep.delete(X)}else if(qe==="tool_start"){let $=(Nt=K(C,!0))!=null?Nt:`tool-${c()}`,E=(at=C.toolName)!=null?at:C.name;if(me(E)){ue.add($);continue}let X=ae($),se=(Dt=X.toolCall)!=null?Dt:{id:$,status:"pending"};se.name=E!=null?E:se.name,se.status="running",C.args!==void 0?se.args=C.args:C.parameters!==void 0&&(se.args=C.parameters),se.startedAt=(Zt=se.startedAt)!=null?Zt:He((pt=C.startedAt)!=null?pt:C.timestamp),se.completedAt=void 0,se.durationMs=void 0,X.toolCall=se,X.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(X.agentMetadata={executionId:(or=J==null?void 0:J.executionId)!=null?or:C.executionId,iteration:(Pn=J==null?void 0:J.iteration)!=null?Pn:C.iteration}),g(X)}else if(qe==="tool_chunk"||qe==="tool_delta"){let $=(Fn=(ln=K(C,!1))!=null?ln:K(C,!0))!=null?Fn:`tool-${c()}`;if(ue.has($))continue;let E=ae($),X=(Er=E.toolCall)!=null?Er:{id:$,status:"running"};X.startedAt=(qn=X.startedAt)!=null?qn:He((vt=C.startedAt)!=null?vt:C.timestamp);let se=(hr=(Ur=(Mr=C.text)!=null?Mr:C.delta)!=null?Ur:C.message)!=null?hr:"";se&&(X.chunks=(bt=X.chunks)!=null?bt:[],X.chunks.push(String(se))),X.status="running",E.toolCall=X,E.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(E.agentMetadata=(Fo=E.agentMetadata)!=null?Fo:{executionId:(Oo=J==null?void 0:J.executionId)!=null?Oo:C.executionId,iteration:(kr=J==null?void 0:J.iteration)!=null?kr:C.iteration}),g(E)}else if(qe==="tool_complete"){let $=(ms=(_n=K(C,!1))!=null?_n:K(C,!0))!=null?ms:`tool-${c()}`;if(ue.has($)){ue.delete($);continue}let E=ae($),X=(lo=E.toolCall)!=null?lo:{id:$,status:"running"};X.status="complete",C.result!==void 0&&(X.result=C.result),typeof C.duration=="number"&&(X.duration=C.duration),X.completedAt=He((qr=C.completedAt)!=null?qr:C.timestamp);let se=(co=C.duration)!=null?co:C.executionTime;if(typeof se=="number")X.durationMs=se;else{let je=(po=X.startedAt)!=null?po:Date.now();X.durationMs=Math.max(0,((_o=X.completedAt)!=null?_o:Date.now())-je)}E.toolCall=X,E.streaming=!1;let J=C.agentContext;(J||C.executionId)&&(E.agentMetadata=(Ct=E.agentMetadata)!=null?Ct:{executionId:($o=J==null?void 0:J.executionId)!=null?$o:C.executionId,iteration:(uo=J==null?void 0:J.iteration)!=null?uo:C.iteration}),g(E);let Ee=oe(C);Ee&&I.byCall.delete(Ee)}else if(qe==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let $=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,E=(zn=$!=null?$:C.toolId)!=null?zn:`local-${c()}`,X=ae(E),se=C.toolName,J=es(se),Ee=(Vn=X.toolCall)!=null?Vn:{id:E,status:"pending"};Ee.name=se,Ee.args=C.parameters,Ee.status=J?"running":"complete",Ee.chunks=(In=Ee.chunks)!=null?In:[],Ee.startedAt=(sr=Ee.startedAt)!=null?sr:He((Et=C.startedAt)!=null?Et:C.timestamp),J?(Ee.completedAt=void 0,Ee.duration=void 0,Ee.durationMs=void 0):Ee.completedAt=(ar=Ee.completedAt)!=null?ar:Ee.startedAt,X.toolCall=Ee,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(mo=C.executionId)!=null?mo:(Kn=X.agentMetadata)==null?void 0:Kn.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},g(X)}else if(qe==="text_start"){if((zr=C.toolContext)!=null&&zr.toolId)continue;let $=C.partId;if($!==void 0&&A.current!==null&&$!==A.current){let E=f;E&&(E.streaming=!1,g(E),Qe=E,f=null,M=!0)}$!==void 0&&(A.current=$)}else if(qe==="text_end"){if((go=C.toolContext)!=null&&go.toolId)continue;let $=f;$&&($.streaming=!1,g($),Qe=$,f=null,M=!0)}else if(qe==="step_chunk"||qe==="step_delta"){let $=C.stepType,E=C.executionType;if($==="tool"||E==="context")continue;let X=C.toolContext;if(X!=null&&X.toolId){let je=String((Ot=(Gn=C.id)!=null?Gn:X.stepId)!=null?Ot:`step-${c()}`),lt=C.partId!==void 0&&C.partId!==null?String(C.partId):"",ot=`${X.toolId}::${je}`,Bt=H.get(ot);if(lt!==""&&Bt!==void 0&&Bt!==""&&Bt!==lt){let St=k.get(N(X.toolId,je,Bt));St&&St.streaming!==!1&&(St.streaming=!1,g(St))}lt!==""&&H.set(ot,lt);let qt=L(X.toolId,je,lt,X.executionId),cn=(Vr=(fo=(ir=(Rn=C.text)!=null?Rn:C.delta)!=null?ir:C.content)!=null?fo:C.chunk)!=null?Vr:"";cn&&(qt.content+=String(cn),qt.streaming=!0,g(qt)),C.isComplete&&(qt.streaming=!1,g(qt));continue}let se=C.partId;if(se!==void 0&&A.current!==null&&se!==A.current){let je=f;je&&(je.streaming=!1,g(je),Qe=je,f=null,M=!0)}se!==void 0&&(A.current=se);let J=se!==void 0&&(ho=tt.get(se))!=null?ho:Ce();se!==void 0&&(J.partId||(J.partId=se),tt.set(se,J));let Ee=(ut=(xe=(Jn=(Lr=C.text)!=null?Lr:C.delta)!=null?Jn:C.content)!=null?xe:C.chunk)!=null?ut:"";if(Ee){let je=typeof C.seq=="number"?C.seq:void 0,lt=se!=null?se:J.id,ot=je!==void 0?Oe(lt,je,String(Ee)):((nn=ie.get(J.id))!=null?nn:"")+Ee;J.rawContent=ot,ee.has(J.id)||ee.set(J.id,this.createStreamParser());let Bt=ee.get(J.id),qt=ot.trim().startsWith("{")||ot.trim().startsWith("[");if(qt&&ie.set(J.id,ot),Bt.__isPlainTextParser===!0){J.content=je!==void 0?ot:J.content+Ee,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,g(J);continue}let St=Bt.processChunk(ot);if(St instanceof Promise)St.then(Mt=>{var Wn;let xn=typeof Mt=="string"?Mt:(Wn=Mt==null?void 0:Mt.text)!=null?Wn:null;if(xn!==null&&xn.trim()!=="")J.content=xn,g(J);else if(!qt&&!ot.trim().startsWith("<")){let Sn=f,en=Sn&&Sn.id===J.id?Sn:J;en.id===J.id&&(en.content=je!==void 0?ot:en.content+Ee,ie.delete(en.id),ee.delete(en.id),en.rawContent=void 0,g(en))}}).catch(()=>{J.content=je!==void 0?ot:J.content+Ee,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,g(J)});else{let Mt=typeof St=="string"?St:(gn=St==null?void 0:St.text)!=null?gn:null;Mt!==null&&Mt.trim()!==""?(J.content=Mt,g(J)):!qt&&!ot.trim().startsWith("<")&&(J.content=je!==void 0?ot:J.content+Ee,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,g(J))}}if(C.isComplete){let je=(Ys=(Pr=C.result)==null?void 0:Pr.response)!=null?Ys:J.content;if(je){let lt=ie.get(J.id),ot=lt!=null?lt:Y(je);J.rawContent=ot;let Bt=ee.get(J.id),qt=null,cn=!1;if(Bt&&(qt=Bt.getExtractedText(),qt===null&&(qt=ns(ot)),qt===null)){let St=Bt.processChunk(ot);St instanceof Promise?(cn=!0,St.then(Mt=>{var Wn;let xn=typeof Mt=="string"?Mt:(Wn=Mt==null?void 0:Mt.text)!=null?Wn:null;if(xn!==null){let Sn=f;Sn&&Sn.id===J.id&&(Sn.content=xn,Sn.streaming=!1,ee.delete(Sn.id),ie.delete(Sn.id),g(Sn))}})):qt=typeof St=="string"?St:(Kr=St==null?void 0:St.text)!=null?Kr:null}if(!cn){qt!==null&&qt.trim()!==""?J.content=qt:ie.has(J.id)||(J.content=Y(je));let St=ee.get(J.id);if(St){let Mt=(jo=St.close)==null?void 0:jo.call(St);Mt instanceof Promise&&Mt.catch(()=>{}),ee.delete(J.id)}ie.delete(J.id),J.streaming=!1,g(J)}}}}else if(qe==="step_complete"){let $=C.stepType,E=C.executionType;if($==="tool"||E==="context")continue;let X=C.toolContext;if(X!=null&&X.toolId){let je=String((_=(Ir=C.id)!=null?Ir:X.stepId)!=null?_:"");if(je){let lt=O(X.toolId,je);for(let[ot,Bt]of k)ot.startsWith(lt)&&Bt.streaming!==!1&&(Bt.streaming=!1,g(Bt));H.delete(`${X.toolId}::${je}`)}continue}let se=C.stopReason;if(M){if(f!==null){let ot=f;se&&(ot.stopReason=se),ee.delete(ot.id),ie.delete(ot.id),ot.streaming!==!1&&(ot.streaming=!1,g(ot))}let je=(gs=C.result)==null?void 0:gs.response,lt=Qe;lt&&(se&&(lt.stopReason=se),je!=null?fe(lt,je):(ee.delete(lt.id),ie.delete(lt.id))),Qe=null;continue}let J=(Rr=C.result)==null?void 0:Rr.response,Ee=Ce();if(se&&(Ee.stopReason=se),J!=null){let je=ee.get(Ee.id),lt=!1,ot=!1;if(je){let Bt=je.getExtractedText(),qt=ie.get(Ee.id),cn=qt!=null?qt:Y(J);if(Ee.rawContent=cn,Bt!==null&&Bt.trim()!=="")Ee.content=Bt,lt=!0;else{let St=ns(cn);if(St!==null)Ee.content=St,lt=!0;else{let Mt=je.processChunk(cn);if(Mt instanceof Promise)ot=!0,Mt.then(xn=>{var Sn;let Wn=typeof xn=="string"?xn:(Sn=xn==null?void 0:xn.text)!=null?Sn:null;if(Wn!==null&&Wn.trim()!==""){let en=f;en&&en.id===Ee.id&&(en.content=Wn,en.streaming=!1,ee.delete(en.id),ie.delete(en.id),g(en))}else{let en=je.getExtractedText(),cr=f;cr&&cr.id===Ee.id&&(en!==null&&en.trim()!==""?cr.content=en:ie.has(cr.id)||(cr.content=Y(J)),cr.streaming=!1,ee.delete(cr.id),ie.delete(cr.id),g(cr))}});else{let xn=typeof Mt=="string"?Mt:(Wr=Mt==null?void 0:Mt.text)!=null?Wr:null;if(xn!==null&&xn.trim()!=="")Ee.content=xn,lt=!0;else{let Wn=je.getExtractedText();Wn!==null&&Wn.trim()!==""&&(Ee.content=Wn,lt=!0)}}}}}if(!ot){if(!Ee.rawContent){let Bt=ie.get(Ee.id);Ee.rawContent=Bt!=null?Bt:Y(J)}if(!lt&&!ie.has(Ee.id)&&(Ee.content=Y(J)),je){let Bt=(Gr=je.close)==null?void 0:Gr.call(je);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Ee.id),ie.delete(Ee.id),Ee.streaming=!1,g(Ee)}}else ee.delete(Ee.id),ie.delete(Ee.id),Ee.streaming=!1,g(Ee)}else if(qe==="flow_complete"){let $=(Hr=C.result)==null?void 0:Hr.response;if(M){if(f!==null){let E=f;ee.delete(E.id),ie.delete(E.id),E.streaming!==!1&&(E.streaming=!1,g(E))}}else if($!=null){let E=Ce(),X=ie.get(E.id),se=X!=null?X:Y($);E.rawContent=se;let J=Y($),Ee=ee.get(E.id);if(Ee){let ot=ns(se);if(ot!==null)J=ot;else{let Bt=Ee.processChunk(se);Bt instanceof Promise&&Bt.then(cn=>{var Mt;let St=typeof cn=="string"?cn:(Mt=cn==null?void 0:cn.text)!=null?Mt:null;St!==null&&(E.content=St,E.streaming=!1,g(E))});let qt=Ee.getExtractedText();qt!==null&&(J=qt)}}ee.delete(E.id),ie.delete(E.id);let je=J!==E.content,lt=E.streaming!==!1;je&&(E.content=J),E.streaming=!1,(je||lt)&&g(E)}else if(f!==null){let E=f;ee.delete(E.id),ie.delete(E.id),E.streaming!==!1&&(E.streaming=!1,g(E))}n({type:"status",status:"idle"})}else if(qe==="agent_start")Je={executionId:C.executionId,agentId:(yr=C.agentId)!=null?yr:"virtual",agentName:(fs=C.agentName)!=null?fs:"",status:"running",currentIteration:0,maxTurns:(Ja=C.maxTurns)!=null?Ja:1,startedAt:He(C.startedAt)};else if(qe==="agent_iteration_start"){if(Je&&(Je.currentIteration=C.iteration),Ge==="separate"&&C.iteration>1){let $=f;$&&($.streaming=!1,g($),Pe.set(C.iteration-1,$),f=null)}}else if(qe==="agent_turn_start")x=null;else if(qe==="agent_turn_delta"){if(C.contentType==="text"){let $=Ce();$.content+=(Qn=C.delta)!=null?Qn:"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:Je==null?void 0:Je.agentName},x=$,g($)}else if(C.contentType==="thinking"){let $=(Xn=C.turnId)!=null?Xn:`agent-think-${C.iteration}`,E=be($);E.reasoning=(br=E.reasoning)!=null?br:{id:$,status:"streaming",chunks:[]},E.reasoning.chunks.push((xr=C.delta)!=null?xr:""),E.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},g(E)}else if(C.contentType==="tool_input"){let $=(Uo=C.toolCallId)!=null?Uo:I.lastId;if($){let E=D.get($);E!=null&&E.toolCall&&(E.toolCall.chunks=(Jr=E.toolCall.chunks)!=null?Jr:[],E.toolCall.chunks.push((An=C.delta)!=null?An:""),g(E))}}}else if(qe==="agent_turn_complete"){let $=C.turnId;if($){let se=B.get($);if(se!=null&&se.reasoning){se.reasoning.status="complete",se.reasoning.completedAt=He(C.completedAt);let J=(Br=se.reasoning.startedAt)!=null?Br:Date.now();se.reasoning.durationMs=Math.max(0,((hs=se.reasoning.completedAt)!=null?hs:Date.now())-J),se.streaming=!1,g(se)}}let E=C.stopReason,X=f!=null?f:x;if(E&&X!==null){let se=C.turnId;(!se||((qo=X.agentMetadata)==null?void 0:qo.turnId)===se)&&(X.stopReason=E,g(X))}}else if(qe==="agent_tool_start"){f&&(f.streaming=!1,g(f),f=null);let $=(ys=C.toolCallId)!=null?ys:`agent-tool-${c()}`;Be(oe(C),$);let E=ae($),X=(Qa=E.toolCall)!=null?Qa:{id:$,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=(Xa=(bs=C.toolName)!=null?bs:C.name)!=null?Xa:X.name,X.status="running",C.parameters!==void 0&&(X.args=C.parameters),X.startedAt=He((xs=C.startedAt)!=null?xs:C.timestamp),E.toolCall=X,E.streaming=!0,E.agentMetadata={executionId:C.executionId,iteration:C.iteration},g(E)}else if(qe==="agent_tool_delta"){let $=(yt=C.toolCallId)!=null?yt:I.lastId;if($){let E=(Zs=D.get($))!=null?Zs:ae($);E.toolCall&&(E.toolCall.chunks=(lr=E.toolCall.chunks)!=null?lr:[],E.toolCall.chunks.push(($n=C.delta)!=null?$n:""),E.toolCall.status="running",E.streaming=!0,g(E))}}else if(qe==="agent_tool_complete"){let $=(Ya=C.toolCallId)!=null?Ya:I.lastId;if($){let E=(Za=D.get($))!=null?Za:ae($);if(E.toolCall){E.toolCall.status="complete",C.result!==void 0&&(E.toolCall.result=C.result),typeof C.executionTime=="number"&&(E.toolCall.durationMs=C.executionTime),E.toolCall.completedAt=He((vs=C.completedAt)!=null?vs:C.timestamp),E.streaming=!1,g(E);let X=oe(C);X&&I.byCall.delete(X)}}}else if(qe==="agent_media"){let $=Array.isArray(C.media)?C.media:[],E=[];for(let X of $){if(!X||typeof X!="object")continue;let se=X,J=typeof se.type=="string"?se.type:void 0,Ee=typeof se.mediaType=="string"?se.mediaType.toLowerCase():"",je=null,lt="";if(J==="media"){let ot=typeof se.data=="string"?se.data:void 0;if(!ot)continue;lt=Ee.length>0?Ee:"application/octet-stream",je=`data:${lt};base64,${ot}`}else if(J==="image-url"){let ot=typeof se.url=="string"?se.url:void 0;if(!ot)continue;lt=Ee,je=ot}else if(J==="file-url"){let ot=typeof se.url=="string"?se.url:void 0;if(!ot)continue;lt=Ee,je=ot}else continue;if(je)if(J==="image-url"||lt.startsWith("image/"))E.push({type:"image",image:je,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))E.push({type:"audio",audio:je,mimeType:lt});else if(lt.startsWith("video/"))E.push({type:"video",video:je,mimeType:lt});else{let ot=lt||"application/octet-stream";E.push({type:"file",data:je,mimeType:ot,filename:Vh(ot)})}}if(E.length>0){let X=c(),se=C.toolCallId,Ee={id:`agent-media-${typeof se=="string"&&se.length>0?`${se}-${X}`:String(X)}`,role:"assistant",content:"",contentParts:E,createdAt:new Date().toISOString(),streaming:!1,sequence:X,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};g(Ee);let je=f;je&&(je.streaming=!1,g(je)),f=null,v.current=null}}else if(qe!=="agent_iteration_complete"){if(qe==="agent_reflection"||qe==="agent_reflect"){let $=`agent-reflection-${C.executionId}-${C.iteration}`,E={id:$,role:"assistant",content:(Qr=C.reflection)!=null?Qr:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(ea=C.reflection)!=null?ea:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};g(E)}else if(qe==="agent_complete"){Je&&(Je.status=C.success?"complete":"error",Je.completedAt=He(C.completedAt),Je.stopReason=C.stopReason);let $=f;$&&($.streaming=!1,g($)),n({type:"status",status:"idle"})}else if(qe==="agent_error"){let $=typeof C.error=="string"?C.error:(ta=(yo=C.error)==null?void 0:yo.message)!=null?ta:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):n({type:"error",error:new Error($)})}else if(qe!=="agent_ping"){if(qe==="agent_approval_start"){let $=(na=C.approvalId)!=null?na:`approval-${c()}`,E={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(ra=Je==null?void 0:Je.agentId)!=null?ra:"virtual",executionId:(jn=(oa=C.executionId)!=null?oa:Je==null?void 0:Je.executionId)!=null?jn:"",toolName:(ws=C.toolName)!=null?ws:"",toolType:C.toolType,description:(Nr=C.description)!=null?Nr:`Execute ${(Dr=C.toolName)!=null?Dr:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};g(E)}else if(qe==="step_await"&&C.awaitReason==="approval_required"){let $=(sa=C.approvalId)!=null?sa:`approval-${c()}`,E={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(ei=Je==null?void 0:Je.agentId)!=null?ei:"virtual",executionId:(ia=(aa=C.executionId)!=null?aa:Je==null?void 0:Je.executionId)!=null?ia:"",toolName:(zo=C.toolName)!=null?zo:"",toolType:C.toolType,description:(ni=C.description)!=null?ni:`Execute ${(ti=C.toolName)!=null?ti:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};g(E)}else if(qe==="agent_approval_complete"){let $=C.approvalId;if($){let X={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(ri=C.decision)!=null?ri:"approved",agentId:(oi=Je==null?void 0:Je.agentId)!=null?oi:"virtual",executionId:(bo=(si=C.executionId)!=null?si:Je==null?void 0:Je.executionId)!=null?bo:"",toolName:(xo=C.toolName)!=null?xo:"",description:(ai=C.description)!=null?ai:"",resolvedAt:Date.now()}};g(X)}}else if(qe==="artifact_start"||qe==="artifact_delta"||qe==="artifact_update"||qe==="artifact_complete"){if(qe==="artifact_start"){let $=C.artifactType,E=String(C.id),X=typeof C.title=="string"?C.title:void 0;if(n({type:"artifact_start",id:E,artifactType:$,title:X,component:typeof C.component=="string"?C.component:void 0}),pe.set(E,{markdown:"",title:X}),!ne.has(E)){ne.add(E);let se={id:`artifact-ref-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:E,title:X,artifactType:$,status:"streaming"}})};Q.set(E,se),g(se)}}else if(qe==="artifact_delta"){let $=String(C.id),E=typeof C.delta=="string"?C.delta:String((la=C.delta)!=null?la:"");n({type:"artifact_delta",id:$,artDelta:E});let X=pe.get($);X&&(X.markdown+=E)}else if(qe==="artifact_update"){let $=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(qe==="artifact_complete"){let $=String(C.id);n({type:"artifact_complete",id:$});let E=Q.get($);if(E){E.streaming=!1;try{let X=JSON.parse((vo=E.rawContent)!=null?vo:"{}");if(X.props){X.props.status="complete";let se=pe.get($);se!=null&&se.markdown&&(X.props.markdown=se.markdown)}E.rawContent=JSON.stringify(X)}catch{}pe.delete($),g(E),Q.delete($)}}}else if(qe==="transcript_insert"){let $=C.message;if(!$||typeof $!="object")continue;let E=String((ii=$.id)!=null?ii:`msg-${c()}`),X=$.role,J={id:E,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:c()};if(g(J),J.rawContent)try{let Ee=JSON.parse(J.rawContent),je=(ca=Ee==null?void 0:Ee.props)==null?void 0:ca.artifactId;typeof je=="string"&&ne.add(je)}catch{}f=null,v.current=null,ee.delete(E),ie.delete(E)}else if(qe==="error"||qe==="step_error"||qe==="dispatch_error"||qe==="flow_error"){let $=null;if(C.error instanceof Error)$=C.error;else if(qe==="dispatch_error"){let E=(wo=C.message)!=null?wo:C.error;E!=null&&E!==""&&($=new Error(String(E)))}else if(qe==="step_error"||qe==="flow_error"){let E=C.error;typeof E=="string"&&E!==""?$=new Error(E):E!=null&&typeof E=="object"&&"message"in E&&($=new Error(String((da=E.message)!=null?da:E)))}else qe==="error"&&C.error!=null&&C.error!==""&&($=new Error(String(C.error)));if($){n({type:"error",error:$});let E=f;E&&E.streaming&&(E.streaming=!1,g(E)),n({type:"status",status:"idle"})}}}}}nt.length=0};;){let{done:U,value:G}=await s.read();if(U)break;a+=o.decode(G,{stream:!0});let ye=a.split(`
10
10
 
11
11
  `);a=(Wt=ye.pop())!=null?Wt:"";for(let Xe of ye){let rt=Xe.split(`
12
- `),Ue="message",$e="";for(let Yt of rt)Yt.startsWith("event:")?Ue=Yt.replace("event:","").trim():Yt.startsWith("data:")&&($e+=Yt.replace("data:","").trim());if(!$e)continue;let Pt;try{Pt=JSON.parse($e)}catch(Yt){n({type:"error",error:Yt instanceof Error?Yt:new Error("Failed to parse chat stream payload")});continue}let Gt=Ue!=="message"?Ue:(mn=Pt.type)!=null?mn:"message";if((Ar=this.onSSEEvent)==null||Ar.call(this,Gt,Pt),this.parseSSEEvent){v.current=f;let Yt=await this.handleCustomSSEEvent(Pt,n,v,g,c,A);if(v.current&&v.current!==f&&(f=v.current),Yt)continue}Ze.push(Gt,Pt),ge()}}Ze.flushPending(),ge(),Ze.destroy()}};function Om(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ns(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function rs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Pi="[Image]";function Fm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function _m(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function $m(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function jm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ea(e){return{type:"text",text:e}}function Um(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 qm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function zm(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Vm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Gh=["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"],no=[...Vm,...Gh];function Jh(e){return Vm.includes(e)||e.startsWith("image/")}function Ii(e){return Jh(e.type)}async function Km(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ii(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Gm(e,t=no,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Qh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Jm(e,t){let n=Qh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}Gl();var Qm=16e3,Xh=24e3,Yh=4096,Zh=1380533830;function ey(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Zh?new Uint8Array(e,44):new Uint8Array(e)}function ty(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Ma=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 o,a,i,d;if(this.callLive)return;let t=(o=this.config)==null?void 0:o.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Qm,channelCount:1,echoCancellation:!0}});if(s!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,m=new p({sampleRate:Qm});m.state==="suspended"&&await m.resume().catch(()=>{}),this.captureContext=m;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Os(Xh);if(s!==this.callGeneration){g.destroy(),c.getTracks().forEach(v=>v.stop()),m.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{s===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${ty(r)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(f,["runtype.bearer",n]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{s===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(m,c,x,s))},x.onmessage=v=>this.handleMessage(v,s),x.onerror=()=>{s===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(s===this.callGeneration){if(v.code!==1e3){let A=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${A}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}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,n,r,s){let o=t.createMediaStreamSource(n);this.sourceNode=o;let a=t.createScriptProcessor(Yh,1,1);this.processor=a,a.onaudioprocess=i=>{if(s!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let m=Math.max(-1,Math.min(1,d[p]));c[p]=m<0?m*32768:m*32767}r.send(c.buffer)},o.connect(a),a.connect(t.destination)}handleMessage(t,n){var s,o;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(s=r.text)!=null?s:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(o=r.text)!=null?o:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=ey(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}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(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(s=>s(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var os=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Lo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ma(e.runtype);case"browser":if(!os.isSupported())throw new Error("Browser speech recognition not supported");return new os(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ri(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Lo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Lo({type:"runtype",runtype:e.runtype});if(os.isSupported())return Lo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function ka(e){try{return Ri(e),!0}catch{return!1}}function Fs(e){var n;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 r of t){let s=e.find(o=>o.name===r);if(s)return s}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Po=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t.text),o=r.getVoices();if(t.voice){let i=o.find(d=>d.name===t.voice);i&&(s.voice=i)}else o.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(o):Fs(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),s.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},s.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(s),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var ss=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,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!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,n){var r,s;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(s=this.engine)==null||s.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var s;let r=++this.generation;(s=this.engine)==null||s.stop(),this.set(t,"loading");try{if(!this.engine){let o=await this.resolveEngine();if(r!==this.generation)return;if(!o){this.set(null,"idle");return}this.engine=o}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function Jl(e){if(!e)return"";let t=ny(e);return Xm(t!==null?t:e)}function ny(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Xm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
12
+ `),Ue="message",$e="";for(let Yt of rt)Yt.startsWith("event:")?Ue=Yt.replace("event:","").trim():Yt.startsWith("data:")&&($e+=Yt.replace("data:","").trim());if(!$e)continue;let Pt;try{Pt=JSON.parse($e)}catch(Yt){n({type:"error",error:Yt instanceof Error?Yt:new Error("Failed to parse chat stream payload")});continue}let Gt=Ue!=="message"?Ue:(mn=Pt.type)!=null?mn:"message";if((Tr=this.onSSEEvent)==null||Tr.call(this,Gt,Pt),this.parseSSEEvent){v.current=f;let Yt=await this.handleCustomSSEEvent(Pt,n,v,g,c,A);if(v.current&&v.current!==f&&(f=v.current),Yt)continue}Ze.push(Gt,Pt),ge()}}Ze.flushPending(),ge(),Ze.destroy()}};function Fm(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ns(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function os(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Pi="[Image]";function _m(e){return typeof e=="string"?[{type:"text",text:e}]:e}function $m(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function jm(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Um(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ea(e){return{type:"text",text:e}}function qm(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 zm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Vm(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Km=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Jh=["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"],ro=[...Km,...Jh];function Qh(e){return Km.includes(e)||e.startsWith("image/")}function Ii(e){return Qh(e.type)}async function Gm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ii(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Jm(e,t=ro,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Xh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Qm(e,t){let n=Xh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}Gl();var Xm=16e3,Yh=24e3,Zh=4096,ey=1380533830;function ty(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===ey?new Uint8Array(e,44):new Uint8Array(e)}function ny(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Ma=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 o,a,i,d;if(this.callLive)return;let t=(o=this.config)==null?void 0:o.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Xm,channelCount:1,echoCancellation:!0}});if(s!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,m=new p({sampleRate:Xm});m.state==="suspended"&&await m.resume().catch(()=>{}),this.captureContext=m;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Os(Yh);if(s!==this.callGeneration){g.destroy(),c.getTracks().forEach(v=>v.stop()),m.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{s===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${ny(r)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(f,["runtype.bearer",n]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{s===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(m,c,x,s))},x.onmessage=v=>this.handleMessage(v,s),x.onerror=()=>{s===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(s===this.callGeneration){if(v.code!==1e3){let A=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${A}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}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,n,r,s){let o=t.createMediaStreamSource(n);this.sourceNode=o;let a=t.createScriptProcessor(Zh,1,1);this.processor=a,a.onaudioprocess=i=>{if(s!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let m=Math.max(-1,Math.min(1,d[p]));c[p]=m<0?m*32768:m*32767}r.send(c.buffer)},o.connect(a),a.connect(t.destination)}handleMessage(t,n){var s,o;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(s=r.text)!=null?s:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(o=r.text)!=null?o:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=ty(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}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(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(s=>s(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var ss=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Po(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ma(e.runtype);case"browser":if(!ss.isSupported())throw new Error("Browser speech recognition not supported");return new ss(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ri(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Po({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Po({type:"runtype",runtype:e.runtype});if(ss.isSupported())return Po({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function ka(e){try{return Ri(e),!0}catch{return!1}}function Fs(e){var n;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 r of t){let s=e.find(o=>o.name===r);if(s)return s}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Io=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t.text),o=r.getVoices();if(t.voice){let i=o.find(d=>d.name===t.voice);i&&(s.voice=i)}else o.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(o):Fs(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),s.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},s.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(s),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var as=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,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!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,n){var r,s;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(s=this.engine)==null||s.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var s;let r=++this.generation;(s=this.engine)==null||s.stop(),this.set(t,"loading");try{if(!this.engine){let o=await this.resolveEngine();if(r!==this.generation)return;if(!o){this.set(null,"idle");return}this.engine=o}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function Jl(e){if(!e)return"";let t=ry(e);return Ym(t!==null?t:e)}function ry(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Ym(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
13
  `),t=t.replace(/\n{2,}/g,`
14
- `),t.trim()}var ng=null;var Ql=()=>ng?ng():Promise.resolve().then(()=>(tg(),eg));var sy=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function ay(e,t){return sy.some(n=>e[n]!==t[n])}function rg(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
14
+ `),t.trim()}var rg=null;var Ql=()=>rg?rg():Promise.resolve().then(()=>(ng(),tg));var ay=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function iy(e,t){return ay.some(n=>e[n]!==t[n])}function og(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
15
15
 
16
- _Details: ${n.message}_`:r}var La=e=>({isError:!0,content:[{type:"text",text:e}]}),og=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,sg=e=>Zo(e)||e===Cr,_s=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new ss(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,s,o,a,i,d,c,p,m;if(t.type==="message"){this.upsertMessage(t.message);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(Zo(g.name)||g.name===Cr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((s=t.message.agentMetadata)==null?void 0:s.awaitingLocalTool)===!0&&f&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.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:(a=t.message.agentMetadata.agentName)!=null?a:"",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 g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(m=(p=this.callbacks).onError)==null||m.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new ns(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var s,o,a,i,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(s=t.host)!=null?s:this.config.apiUrl,r=(d=t.agentId)!=null?d:(i=(a=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!n||!r||!this.config.clientToken||Ql().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return ka((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,s,o,a,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Po.isSupported()?new Po({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(r=t.host)!=null?r:this.config.apiUrl,c=(i=t.agentId)!=null?i:(a=(o=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:o.runtype)==null?void 0:a.agentId,p=this.config.clientToken,m=t.browserFallback!==!1;if(d&&c&&p)return Ql().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:f})=>{let x=new g({host:d,agentId:c,clientToken:p,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return m&&n?new f(x,n,{onFallback:v=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${v.message}`)}):x});if(m&&n)return p&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Lo(s);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"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,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,s,o,a,i,d,c,p,m;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:(o=(s=t.runtype)==null?void 0:s.clientToken)!=null?o:this.config.clientToken,host:(i=(a=t.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=t.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=t.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((p=t.browser)==null?void 0:p.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!ay(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new ns(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:m}=t,f={id:a!=null?a:n==="user"?Ns():n==="assistant"?rs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:m=!1,voiceProcessing:g,rawContent:f}=r,v={id:d!=null?d:s==="user"?Ns():s==="assistant"?rs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,c={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(c),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,m,g,f;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let s=Ns(),o=rs(),a={id:s,role:"user",content:r||Pi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let A=rg(x,this.config.errorMessage);if(A){let M={id:o,role:"assistant",createdAt:new Date().toISOString(),content:A,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(x instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,x):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(x))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=rs();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let m=rg(c,this.config.errorMessage);if(m){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,m,g,f,x;let s=`approval-${t.id}`,o={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===s),i={id:s,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:o};this.upsertMessage(i),(m=this.abortController)==null||m.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let A=null;if(v instanceof Response){if(!v.ok){let M=await v.json().catch(()=>null);throw new Error((g=M==null?void 0:M.error)!=null?g:`Approval request failed: ${v.status}`)}A=v.body}else v instanceof ReadableStream&&(A=v);A?await this.connectStream(A,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let A=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,A||(x=(f=this.callbacks).onError)==null||x.call(f,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,g,f,x,v,A,M,B,D,k,H;let r=this.messages.find(S=>S.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=t.agentMetadata)==null?void 0:m.executionId,o=(g=t.toolCall)==null?void 0:g.name;if(!s||!o){(x=(f=this.callbacks).onError)==null||x.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let S=(v=t.toolCall)==null?void 0:v.args,I=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(I.length===1){let N=typeof((A=I[0])==null?void 0:A.question)=="string"?I[0].question:"";N&&(a={[N]:n})}}this.markAskUserQuestionResolved(t,a),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(B=t.toolCall)==null?void 0:B.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let S=typeof n=="string"?n:Object.entries(n).map(([I,N])=>`${I}: ${Array.isArray(N)?N.join(", "):N}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let S=a!=null?a:{};c.forEach((I,N)=>{let O=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!O)return;let L=S[O],j=Array.isArray(L)?L.join(", "):typeof L=="string"?L:"";this.appendMessage({id:`ask-user-q-${i}-${N}`,role:"assistant",content:O,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${N}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(s,{[o]:n});if(!S.ok){let I=await S.json().catch(()=>null);throw new Error((D=I==null?void 0:I.error)!=null?D:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let I=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(H=(k=this.callbacks).onError)==null||H.call(k,S instanceof Error?S:new Error(String(S)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var s,o;let n=this.messages.find(a=>a.id===t.id),r=[(s=n==null?void 0:n.toolCall)==null?void 0:s.startedAt,(o=t.toolCall)==null?void 0:o.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,s;if(((r=t.toolCall)==null?void 0:r.name)!==Cr)return!1;let n=this.messages.find(o=>o.id===t.id);return((s=(n!=null?n:t).agentMetadata)==null?void 0:s.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,s=Date.now(),o){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...o},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:s,duration:void 0,durationMs:Math.max(0,s-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,m;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var H,S,I,N,O,L,j;let f=(H=g.toolCall)==null?void 0:H.name,x=(S=g.toolCall)==null?void 0:S.id;if(!f||!x)return null;let v=`${t}:${x}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(v),r.push(v);let A=this.markWebMcpToolRunning(g),M=(N=(I=g.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?N:f;if(f===Cr)return{dedupeKey:v,resumeKey:M,output:jl(),toolMessage:g,startedAt:A,completedAt:Date.now()};let B=new AbortController;this.webMcpResolveControllers.add(B),s.push(B);let D=this.client.executeWebMcpToolCall(f,(O=g.toolCall)==null?void 0:O.args,B.signal),k;if(!D)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await D}catch(z){let oe=z instanceof Error&&(z.name==="AbortError"||z.message.includes("aborted")||z.message.includes("abort"));return oe||(j=(L=this.callbacks).onError)==null||j.call(L,z instanceof Error?z:new Error(String(z))),this.markWebMcpToolComplete(g,La(oe?"Aborted by cancel()":og(z)),A),this.webMcpInflightKeys.delete(v),null}return B.signal.aborted?(this.markWebMcpToolComplete(g,La("Aborted by cancel()"),A),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:M,output:k,toolMessage:g,startedAt:A,completedAt:Date.now()}})),i=[];try{if(i=a.filter(x=>x!==null),i.length===0)return;let g={};for(let x of i)g[x.resumeKey]=x.output;let f=await this.client.resumeFlow(t,g,{signal:o.signal});if(!f.ok){let x=await f.json().catch(()=>null);throw new Error((d=x==null?void 0:x.error)!=null?d:`Resume failed: ${f.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((c=x.toolMessage.toolCall)==null?void 0:c.name)===Cr?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(m=(p=this.callbacks).onError)==null||m.call(p,g instanceof Error?g:new Error(String(g)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,La("Aborted by cancel()"),x.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of s)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,v,A,M,B,D,k,H,S,I,N,O;let n=(x=t.agentMetadata)==null?void 0:x.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(A=t.toolCall)==null?void 0:A.id;if(!n){(B=(M=this.callbacks).onError)==null||B.call(M,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!s){let L=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(L)||this.webMcpResolvedKeys.has(L))return;this.webMcpInflightKeys.add(L);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(L)}catch(j){(k=(D=this.callbacks).onError)==null||k.call(D,j instanceof Error?j:new Error(String(j)))}finally{this.webMcpInflightKeys.delete(L)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(o);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Cr,p=(H=t.toolCall)==null?void 0:H.args,m=c?null:this.client.executeWebMcpToolCall(r,p,d),g="execute",f=a;try{let L;if(c?L=jl():m?L=await m:L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,La("Aborted by cancel()"),a);return}let j=(I=(S=t.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?I:r;g="resume",await this.resumeWithToolOutput(n,j,L,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,L,a,f,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(L){let j=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));(g==="execute"||j||d.aborted)&&this.markWebMcpToolComplete(t,La(j||d.aborted?"Aborted by cancel()":og(L)),a),j||(O=(N=this.callbacks).onError)==null||O.call(N,L instanceof Error?L:new Error(String(L)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=Jl(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Fs(t)}toggleReadAloud(t){let n=this.messages.find(o=>o.id===t);if(!n||n.role!=="assistant")return;let r=Jl(n.content||"");if(!r.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:s==null?void 0:s.voice,rate:s==null?void 0:s.rate,pitch:s==null?void 0:s.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 n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,m,g,f,x,v,A,M,B,D,k,H,S,I,N;if(o!==r)return s;let a={...s,...n};if(((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((m=s.agentMetadata)==null?void 0:m.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let O=s.approval,L=n.approval;a.approval={...O,...L,executionId:L.executionId||O.executionId,toolName:L.toolName||O.toolName,description:L.description||O.description,toolType:(f=L.toolType)!=null?f:O.toolType,reason:(x=L.reason)!=null?x:O.reason,parameters:(v=L.parameters)!=null?v:O.parameters}}let i=(A=n.toolCall)==null?void 0:A.name,d=(M=n.agentMetadata)==null?void 0:M.executionId,c=(B=n.toolCall)==null?void 0:B.id;if(i&&sg(i)&&d&&c&&((D=n.agentMetadata)==null?void 0:D.awaitingLocalTool)===!0){let O=`${d}:${c}`,L=this.webMcpInflightKeys.has(O),j=this.webMcpResolvedKeys.has(O),z=(k=s.toolCall)==null?void 0:k.name,oe=((H=s.agentMetadata)==null?void 0:H.executionId)===d&&((S=s.toolCall)==null?void 0:S.id)===c&&z!==void 0&&sg(z)&&((I=s.toolCall)==null?void 0:I.status)==="complete";(L||j||oe)&&(a.agentMetadata={...(N=a.agentMetadata)!=null?N:{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var w=require("lucide"),iy={activity:w.Activity,"arrow-down":w.ArrowDown,"arrow-up":w.ArrowUp,"arrow-up-right":w.ArrowUpRight,bot:w.Bot,"chevron-down":w.ChevronDown,"chevron-up":w.ChevronUp,"chevron-right":w.ChevronRight,"chevron-left":w.ChevronLeft,check:w.Check,clipboard:w.Clipboard,"clipboard-copy":w.ClipboardCopy,copy:w.Copy,file:w.File,"file-code":w.FileCode,"file-spreadsheet":w.FileSpreadsheet,"file-text":w.FileText,"image-plus":w.ImagePlus,loader:w.Loader,"loader-circle":w.LoaderCircle,mic:w.Mic,paperclip:w.Paperclip,"refresh-cw":w.RefreshCw,search:w.Search,send:w.Send,"shield-alert":w.ShieldAlert,"shield-check":w.ShieldCheck,"shield-x":w.ShieldX,square:w.Square,"thumbs-down":w.ThumbsDown,"thumbs-up":w.ThumbsUp,upload:w.Upload,"volume-2":w.Volume2,x:w.X,user:w.User,mail:w.Mail,phone:w.Phone,calendar:w.Calendar,clock:w.Clock,building:w.Building,"map-pin":w.MapPin,lock:w.Lock,key:w.Key,"credit-card":w.CreditCard,"at-sign":w.AtSign,hash:w.Hash,globe:w.Globe,link:w.Link,"circle-check":w.CircleCheck,"circle-x":w.CircleX,"triangle-alert":w.TriangleAlert,info:w.Info,ban:w.Ban,shield:w.Shield,"arrow-left":w.ArrowLeft,"arrow-right":w.ArrowRight,"external-link":w.ExternalLink,ellipsis:w.Ellipsis,"ellipsis-vertical":w.EllipsisVertical,menu:w.Menu,house:w.House,plus:w.Plus,minus:w.Minus,pencil:w.Pencil,trash:w.Trash,"trash-2":w.Trash2,save:w.Save,download:w.Download,share:w.Share,funnel:w.Funnel,settings:w.Settings,"rotate-cw":w.RotateCw,maximize:w.Maximize,minimize:w.Minimize,"shopping-cart":w.ShoppingCart,"shopping-bag":w.ShoppingBag,package:w.Package,truck:w.Truck,tag:w.Tag,gift:w.Gift,receipt:w.Receipt,wallet:w.Wallet,store:w.Store,"dollar-sign":w.DollarSign,percent:w.Percent,play:w.Play,pause:w.Pause,"volume-x":w.VolumeX,camera:w.Camera,image:w.Image,film:w.Film,headphones:w.Headphones,"message-circle":w.MessageCircle,"message-square":w.MessageSquare,bell:w.Bell,heart:w.Heart,star:w.Star,eye:w.Eye,"eye-off":w.EyeOff,bookmark:w.Bookmark,"calendar-days":w.CalendarDays,history:w.History,timer:w.Timer,folder:w.Folder,"folder-open":w.FolderOpen,files:w.Files,sparkles:w.Sparkles,zap:w.Zap,sun:w.Sun,moon:w.Moon,flag:w.Flag,monitor:w.Monitor,smartphone:w.Smartphone},ve=(e,t=24,n="currentColor",r=2)=>{let s=iy[e];return s?ly(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function ly(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}),s}var Bi={allowedTypes:no,maxFileSize:10*1024*1024,maxFiles:4};function cy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function dy(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 as=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Bi.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Bi.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:Bi.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:Bi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,s,o,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=Gm(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,m);continue}try{let m=await Km(c),g=Ii(c)?URL.createObjectURL(c):null,f={id:cy(),file:c,previewUrl:g,contentPart:m};this.attachments.push(f),this.renderPreview(f)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ii(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=dy(t.file.type),d=ve(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Jm(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let s=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=ve("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var ag=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Pa(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];ag(o)&&ag(s)?n[r]=Pa(o,s):n[r]=s}return n}var tr="min(440px, calc(100vw - 24px))",Di="440px",py={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:tr,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:py,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 ig(e,t){if(!(!e&&!t))return e?t?Pa(e,t):e:t}function Ni(e){var t,n,r,s,o,a,i,d,c,p,m,g,f,x,v,A,M,B,D,k,H;return e?{..._t,...e,theme:ig(_t.theme,e.theme),darkTheme:ig(_t.darkTheme,e.darkTheme),launcher:{..._t.launcher,...e.launcher,dock:{...(t=_t.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=_t.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{..._t.copy,...e.copy},sendButton:{..._t.sendButton,...e.sendButton},statusIndicator:{..._t.statusIndicator,...e.statusIndicator},voiceRecognition:{..._t.voiceRecognition,...e.voiceRecognition},features:(()=>{var ue,Q,ne,pe,me,K,ae,He,Y,ee;let S=(ue=_t.features)==null?void 0:ue.artifacts,I=(Q=e.features)==null?void 0:Q.artifacts,N=(ne=_t.features)==null?void 0:ne.scrollToBottom,O=(pe=e.features)==null?void 0:pe.scrollToBottom,L=(me=_t.features)==null?void 0:me.scrollBehavior,j=(K=e.features)==null?void 0:K.scrollBehavior,z=(ae=_t.features)==null?void 0:ae.streamAnimation,oe=(He=e.features)==null?void 0:He.streamAnimation,ke=(Y=_t.features)==null?void 0:Y.askUserQuestion,Ke=(ee=e.features)==null?void 0:ee.askUserQuestion,Ce=S===void 0&&I===void 0?void 0:{...S,...I,layout:{...S==null?void 0:S.layout,...I==null?void 0:I.layout}},We=N===void 0&&O===void 0?void 0:{...N,...O},Ne=L===void 0&&j===void 0?void 0:{...L,...j},be=z===void 0&&oe===void 0?void 0:{...z,...oe},Be=ke===void 0&&Ke===void 0?void 0:{...ke,...Ke,styles:{...ke==null?void 0:ke.styles,...Ke==null?void 0:Ke.styles}};return{..._t.features,...e.features,...We!==void 0?{scrollToBottom:We}:{},...Ne!==void 0?{scrollBehavior:Ne}:{},...Ce!==void 0?{artifacts:Ce}:{},...be!==void 0?{streamAnimation:be}:{},...Be!==void 0?{askUserQuestion:Be}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:_t.suggestionChips,suggestionChipsConfig:{..._t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{..._t.layout,...e.layout,header:{...(a=_t.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=_t.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(m=(p=_t.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(v=(x=_t.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(M=(A=e.layout)==null?void 0:A.messages)==null?void 0:M.timestamp}},slots:{...(B=_t.layout)==null?void 0:B.slots,...(D=e.layout)==null?void 0:D.slots}},markdown:{..._t.markdown,...e.markdown,options:{...(k=_t.markdown)==null?void 0:k.options,...(H=e.markdown)==null?void 0:H.options}},messageActions:{..._t.messageActions,...e.messageActions}}:_t}var Xl={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"}},Yl={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"}},Zl={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:tr,maxWidth:Di,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function $s(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?$s(e,r):r}function Oi(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=$s(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function ec(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function lg(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=lg(o,s):n[r]=s}return n}function uy(e,t){return t?lg(e,t):e}function js(e,t={}){var s,o,a,i,d,c,p,m,g,f,x,v,A;let n={palette:Xl,semantic:Yl,components:Zl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(x=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:x.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(A=e==null?void 0:e.semantic)==null?void 0:A.typography}},components:uy(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let M=ec(r);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(B=>B.message).join(", ")}`)}if(t.plugins)for(let M of t.plugins)r=M.transform(r);return r}function Fi(e){var v,A,M,B,D,k,H,S,I,N,O,L,j,z,oe,ke,Ke,Ce,We,Ne,be,Be,ue,Q,ne,pe,me,K,ae,He,Y,ee,ie,Se,tt,Qe,Oe,fe,nt,te,ge,Me,Ze,Je,Pe,Ge,wn,Wt,mn,Ar,U,G,ye,Xe,rt,Ue,$e,Pt,Gt,Yt,Ln,V,Ht,le,Ae,_e,Tt,sn,an,Cn,Nt,at,Dt,pt,Zt,or,Pn,ln,Fn,Tr,vt,qn,Er,jr,fr,bt,No,Mr,Oo,_n,ms,io,Ur,lo,co,Fo,_o,po,Ct,zn,Vn,In,Et,sr,ar,Kn,uo,qr,mo,Gn,Ot,Rn,ir,go,zr,fo,kr,Jn;let t=Oi(e),n={};for(let[xe,ut]of Object.entries(t)){let nn=xe.replace(/\./g,"-");n[`--persona-${nn}`]=ut.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(A=n["--persona-semantic-colors-secondary"])!=null?A:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(M=n["--persona-semantic-colors-accent"])!=null?M:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(B=n["--persona-semantic-colors-surface"])!=null?B:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(D=n["--persona-semantic-colors-background"])!=null?D:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(k=n["--persona-semantic-colors-container"])!=null?k:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(H=n["--persona-semantic-colors-text"])!=null?H:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(S=n["--persona-semantic-colors-text-muted"])!=null?S:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(N=n["--persona-semantic-colors-border"])!=null?N:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(O=n["--persona-semantic-colors-divider"])!=null?O:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(L=n["--persona-components-voice-recording-indicator"])!=null?L:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(j=n["--persona-components-voice-recording-background"])!=null?j:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(z=n["--persona-components-voice-processing-icon"])!=null?z:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(oe=n["--persona-components-voice-speaking-icon"])!=null?oe:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(ke=n["--persona-components-approval-requested-background"])!=null?ke:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Ke=n["--persona-components-approval-requested-border"])!=null?Ke:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ce=n["--persona-components-approval-requested-text"])!=null?Ce:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(We=n["--persona-components-approval-requested-shadow"])!=null?We:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(Ne=n["--persona-components-approval-approve-background"])!=null?Ne:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(be=n["--persona-components-approval-deny-background"])!=null?be:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Be=n["--persona-components-attachment-image-background"])!=null?Be:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ue=n["--persona-components-attachment-image-border"])!=null?ue:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Q=n["--persona-semantic-typography-fontFamily"])!=null?Q:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ne=n["--persona-semantic-typography-fontSize"])!=null?ne:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(pe=n["--persona-semantic-typography-fontWeight"])!=null?pe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(me=n["--persona-semantic-typography-lineHeight"])!=null?me:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(ae=n["--persona-palette-radius-md"])!=null?ae:"0.375rem",n["--persona-radius-lg"]=(He=n["--persona-palette-radius-lg"])!=null?He:"0.5rem",n["--persona-radius-xl"]=(Y=n["--persona-palette-radius-xl"])!=null?Y:"0.75rem",n["--persona-radius-full"]=(ee=n["--persona-palette-radius-full"])!=null?ee:"9999px",n["--persona-launcher-radius"]=(Se=(ie=n["--persona-components-launcher-borderRadius"])!=null?ie:n["--persona-palette-radius-full"])!=null?Se:"9999px",n["--persona-launcher-bg"]=(tt=n["--persona-components-launcher-background"])!=null?tt:n["--persona-primary"],n["--persona-launcher-fg"]=(Qe=n["--persona-components-launcher-foreground"])!=null?Qe:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Oe=n["--persona-components-launcher-border"])!=null?Oe:n["--persona-border"],n["--persona-button-primary-bg"]=(fe=n["--persona-components-button-primary-background"])!=null?fe:n["--persona-primary"],n["--persona-button-primary-fg"]=(nt=n["--persona-components-button-primary-foreground"])!=null?nt:n["--persona-text-inverse"],n["--persona-button-radius"]=(ge=(te=n["--persona-components-button-primary-borderRadius"])!=null?te:n["--persona-palette-radius-full"])!=null?ge:"9999px",n["--persona-panel-radius"]=(Ze=(Me=n["--persona-components-panel-borderRadius"])!=null?Me:n["--persona-radius-xl"])!=null?Ze:"0.75rem",n["--persona-panel-border"]=(Je=n["--persona-components-panel-border"])!=null?Je:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ge=(Pe=n["--persona-components-panel-shadow"])!=null?Pe:n["--persona-palette-shadows-xl"])!=null?Ge:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(wn=n["--persona-components-launcher-shadow"])!=null?wn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(mn=(Wt=n["--persona-components-input-borderRadius"])!=null?Wt:n["--persona-radius-lg"])!=null?mn:"0.5rem",n["--persona-message-user-radius"]=(U=(Ar=n["--persona-components-message-user-borderRadius"])!=null?Ar:n["--persona-radius-lg"])!=null?U:"0.5rem",n["--persona-message-assistant-radius"]=(ye=(G=n["--persona-components-message-assistant-borderRadius"])!=null?G:n["--persona-radius-lg"])!=null?ye:"0.5rem",n["--persona-header-bg"]=(Xe=n["--persona-components-header-background"])!=null?Xe:n["--persona-surface"],n["--persona-header-border"]=(rt=n["--persona-components-header-border"])!=null?rt:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ue=n["--persona-components-header-iconBackground"])!=null?Ue:n["--persona-primary"],n["--persona-header-icon-fg"]=($e=n["--persona-components-header-iconForeground"])!=null?$e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Pt=n["--persona-components-header-titleForeground"])!=null?Pt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Gt=n["--persona-components-header-subtitleForeground"])!=null?Gt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Yt=n["--persona-components-header-actionIconForeground"])!=null?Yt:n["--persona-muted"];let r=(Ln=e.components)==null?void 0:Ln.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(V=e.components)==null?void 0:V.introCard;n["--persona-intro-card-bg"]=(Ht=n["--persona-components-introCard-background"])!=null?Ht:n["--persona-surface"],n["--persona-intro-card-radius"]=(le=n["--persona-components-introCard-borderRadius"])!=null?le:"1rem",n["--persona-intro-card-padding"]=(Ae=n["--persona-components-introCard-padding"])!=null?Ae:"1.5rem",n["--persona-intro-card-shadow"]=(Tt=(_e=s==null?void 0:s.shadow)!=null?_e:n["--persona-components-introCard-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(sn=n["--persona-components-input-background"])!=null?sn:n["--persona-surface"],n["--persona-input-placeholder"]=(an=n["--persona-components-input-placeholder"])!=null?an:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Cn=n["--persona-components-message-user-background"])!=null?Cn:n["--persona-accent"],n["--persona-message-user-text"]=(Nt=n["--persona-components-message-user-text"])!=null?Nt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(at=n["--persona-components-message-user-shadow"])!=null?at:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Dt=n["--persona-components-message-assistant-background"])!=null?Dt:n["--persona-surface"],n["--persona-message-assistant-text"]=(pt=n["--persona-components-message-assistant-text"])!=null?pt:n["--persona-text"],n["--persona-message-assistant-border"]=(Zt=n["--persona-components-message-assistant-border"])!=null?Zt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(or=n["--persona-components-message-assistant-shadow"])!=null?or:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(ln=(Pn=n["--persona-components-scrollToBottom-background"])!=null?Pn:n["--persona-button-primary-bg"])!=null?ln:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Tr=(Fn=n["--persona-components-scrollToBottom-foreground"])!=null?Fn:n["--persona-button-primary-fg"])!=null?Tr:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(vt=n["--persona-components-scrollToBottom-border"])!=null?vt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(qn=n["--persona-components-scrollToBottom-size"])!=null?qn:"40px",n["--persona-scroll-to-bottom-radius"]=(fr=(jr=(Er=n["--persona-components-scrollToBottom-borderRadius"])!=null?Er:n["--persona-button-radius"])!=null?jr:n["--persona-radius-full"])!=null?fr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(No=(bt=n["--persona-components-scrollToBottom-shadow"])!=null?bt:n["--persona-palette-shadows-sm"])!=null?No:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Mr=n["--persona-components-scrollToBottom-padding"])!=null?Mr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Oo=n["--persona-components-scrollToBottom-gap"])!=null?Oo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(ms=(_n=n["--persona-components-scrollToBottom-fontSize"])!=null?_n:n["--persona-palette-typography-fontSize-sm"])!=null?ms:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(io=n["--persona-components-scrollToBottom-iconSize"])!=null?io:"14px",n["--persona-tool-bubble-shadow"]=(Ur=n["--persona-components-toolBubble-shadow"])!=null?Ur:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(lo=n["--persona-components-reasoningBubble-shadow"])!=null?lo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(co=n["--persona-components-composer-shadow"])!=null?co:"none",n["--persona-md-inline-code-bg"]=(Fo=n["--persona-components-markdown-inlineCode-background"])!=null?Fo:n["--persona-container"],n["--persona-md-inline-code-color"]=(_o=n["--persona-components-markdown-inlineCode-foreground"])!=null?_o:n["--persona-text"],n["--persona-md-link-color"]=(Ct=(po=n["--persona-components-markdown-link-foreground"])!=null?po:n["--persona-accent"])!=null?Ct:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(zn=n["--persona-components-markdown-codeBlock-background"])!=null?zn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Vn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Vn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(In=n["--persona-components-markdown-codeBlock-textColor"])!=null?In:"inherit",n["--persona-md-table-header-bg"]=(Et=n["--persona-components-markdown-table-headerBackground"])!=null?Et:n["--persona-container"],n["--persona-md-table-border-color"]=(sr=n["--persona-components-markdown-table-borderColor"])!=null?sr:n["--persona-border"],n["--persona-md-hr-color"]=(ar=n["--persona-components-markdown-hr-color"])!=null?ar:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Kn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Kn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(uo=n["--persona-components-markdown-blockquote-background"])!=null?uo:"transparent",n["--persona-md-blockquote-text-color"]=(qr=n["--persona-components-markdown-blockquote-textColor"])!=null?qr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(mo=n["--persona-components-collapsibleWidget-container"])!=null?mo:n["--persona-surface"],n["--cw-surface"]=(Gn=n["--persona-components-collapsibleWidget-surface"])!=null?Gn:n["--persona-surface"],n["--cw-border"]=(Ot=n["--persona-components-collapsibleWidget-border"])!=null?Ot:n["--persona-border"],n["--persona-message-border"]=(Rn=n["--persona-components-message-border"])!=null?Rn:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let xe=x.toolbar;xe.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,n["--persona-dropdown-bg"]=(ir=n["--persona-dropdown-bg"])!=null?ir:xe.copyMenuBackground),xe.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,n["--persona-dropdown-border"]=(go=n["--persona-dropdown-border"])!=null?go:xe.copyMenuBorder),xe.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,n["--persona-dropdown-shadow"]=(zr=n["--persona-dropdown-shadow"])!=null?zr:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(fo=n["--persona-dropdown-radius"])!=null?fo:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(kr=n["--persona-dropdown-item-hover-bg"])!=null?kr:xe.copyMenuItemHoverBackground),xe.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(x!=null&&x.tab){let xe=x.tab;xe.background&&(n["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(n["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(n["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(n["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(n["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(n["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(n["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(x!=null&&x.pane){let xe=x.pane;if(xe.toolbarBackground){let ut=(Jn=$s(e,xe.toolbarBackground))!=null?Jn:xe.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ut}}return n}var cg={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 my={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"}}},dg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ia=()=>{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"},gy=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ia()},tc=e=>gy(e),fy=e=>js(e),hy=e=>{var n;let t=js(void 0,{validate:!1});return js({...e,palette:{...t.palette,colors:{...my.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Us=e=>{let t=tc(e),n=dg(e==null?void 0:e.theme),r=dg(e==null?void 0:e.darkTheme);return t==="dark"?hy(Pa(n!=null?n:{},r!=null?r:{})):fy(n)},yy=e=>Fi(e),Io=(e,t)=>{let n=Us(t),r=yy(n);for(let[s,o]of Object.entries(r))e.style.setProperty(s,o)},_i=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ia())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Ia());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var pg=require("idiomorph"),$i=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;pg.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var ji={index:-1,draft:""};function ug(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...ji}}}function mg(e,t){var n,r,s,o,a,i,d,c,p,m,g,f,x,v,A,M,B,D,k,H,S,I,N,O,L,j,z,oe,ke,Ke,Ce,We,Ne,be,Be,ue,Q,ne;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(g=(m=e.approval)==null?void 0:m.status)!=null?g:"",(x=(f=e.toolCall)==null?void 0:f.status)!=null?x:"",(A=(v=e.toolCall)==null?void 0:v.name)!=null?A:"",(D=(B=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:B.length)!=null?D:0,(I=(S=(H=(k=e.toolCall)==null?void 0:k.chunks)==null?void 0:H[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?I:"",typeof((N=e.toolCall)==null?void 0:N.args)=="string"?e.toolCall.args.length:(O=e.toolCall)!=null&&O.args?JSON.stringify(e.toolCall.args).length:0,(z=(j=(L=e.reasoning)==null?void 0:L.chunks)==null?void 0:j.length)!=null?z:0,(Ce=(Ke=(ke=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:ke[e.reasoning.chunks.length-1])==null?void 0:Ke.length)!=null?Ce:0,(Be=(be=(Ne=(We=e.reasoning)==null?void 0:We.chunks)==null?void 0:Ne[e.reasoning.chunks.length-1])==null?void 0:be.slice(-32))!=null?Be:"",(Q=(ue=e.contentParts)==null?void 0:ue.length)!=null?Q:0,(ne=e.stopReason)!=null?ne:"",t].join("\0")}function gg(){return new Map}function fg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function hg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function yg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ui(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function ro(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function is(e,t){return ro(e)-e.scrollTop<=t}function qi(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function zi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}function bg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function xg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function vg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Mn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},kn=1e5,Ro=kn+1;var Ra={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},by=["pre","code","a","script","style"],Vi=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Ra.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ra.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ra.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Ra.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Ra.buffer}},Cg=[{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"}],Wa=new Map;for(let e of Cg)Wa.set(e.name,e);var Sg=e=>{Wa.set(e.name,e)},Ag=e=>{Cg.some(t=>t.name===e)||Wa.delete(e)},Tg=()=>Array.from(Wa.keys()),Ha=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=Wa.get(e))!=null?r:null},Ki=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
17
- `);return o<0?"":e.slice(0,o)}return e},xy=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},vy=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},nc=/\s/,wy=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Cy=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(nc.test(o[i])){let c=i;for(;c<o.length&&nc.test(o[c]);)c+=1;a.appendChild(r.createTextNode(o.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<o.length&&!nc.test(o[p]);)c.appendChild(xy(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}s.replaceChild(a,e)},Sy=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(vy(r,c,t,n.value)),n.value+=1));s.replaceChild(a,e)},Ba=(e,t,n,r)=>{var m,g;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((m=r==null?void 0:r.skipTags)!=null?m:by).map(f=>f.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)wy(d,o)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?Cy:Sy;for(let f of i)p(f,n,c);return s.innerHTML},Gi=(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},Da=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},wg=new WeakMap,Ay=(e,t)=>{var o;if(!e.styles)return;let n=wg.get(t);if(n||(n=new Set,wg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},rc=new WeakMap,Ty=(e,t)=>{if(!e.onAttach)return;let n=rc.get(t);if(n||(n=new Map,rc.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Eg=e=>{let t=rc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},oc=(e,t)=>{Ay(e,t),Ty(e,t)};function sc(e,t=kn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var Na=0,Wo=null;function ac(e=document){var n;if(Na++,Na===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;Wo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,Na=Math.max(0,Na-1),Na===0&&Wo)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=Wo.originalOverflow,s.style.position=Wo.originalPosition,s.style.top=Wo.originalTop,s.style.width=Wo.originalWidth,o.scrollTo(0,Wo.scrollY),Wo=null}}}var Oa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},un=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Ho=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},nr=e=>{var n,r,s,o,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:Oa.side,width:(s=t==null?void 0:t.width)!=null?s:Oa.width,animate:(o=t==null?void 0:t.animate)!=null?o:Oa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Oa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Oa.maxHeight}};var Sr={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Ey="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ji=(e,t={})=>{var A,M,B,D,k,H;let{showClose:n=!0,wrapperClassName:r=Ey,buttonSize:s,iconSize:o="28px"}=t,a=(A=e==null?void 0:e.launcher)!=null?A:{},i=(M=s!=null?s:a.closeButtonSize)!=null?M:"32px",d=y("div",r),c=(B=a.closeButtonTooltipText)!=null?B:"Close chat",p=(D=a.closeButtonShowTooltip)!=null?D:!0,m=(k=a.closeButtonIconName)!=null?k:"x",g=(H=a.closeButtonIconText)!=null?H:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),x=Lt("button",{className:ba("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||On.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=ve(m,o,"currentColor",1);if(v?(v.style.display="block",x.appendChild(v)):x.textContent=g,d.appendChild(x),p&&c){let S=null,I=()=>{if(S)return;let O=x.ownerDocument,L=O.body;if(!L)return;S=_r(O,"div","persona-clear-chat-tooltip"),S.textContent=c;let j=_r(O,"div");j.className="persona-clear-chat-tooltip-arrow",S.appendChild(j);let z=x.getBoundingClientRect();S.style.position="fixed",S.style.zIndex=String(Ro),S.style.left=`${z.left+z.width/2}px`,S.style.top=`${z.top-8}px`,S.style.transform="translate(-50%, -100%)",L.appendChild(S)},N=()=>{S&&S.parentNode&&(S.parentNode.removeChild(S),S=null)};d.addEventListener("mouseenter",I),d.addEventListener("mouseleave",N),x.addEventListener("focus",I),x.addEventListener("blur",N),d._cleanupTooltip=()=>{N(),d.removeEventListener("mouseenter",I),d.removeEventListener("mouseleave",N),x.removeEventListener("focus",I),x.removeEventListener("blur",N)}}return{button:x,wrapper:d}},My="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Qi=(e,t={})=>{var S,I,N,O,L,j,z,oe,ke,Ke,Ce,We,Ne;let{wrapperClassName:n=My,buttonSize:r,iconSize:s="20px"}=t,a=(I=((S=e==null?void 0:e.launcher)!=null?S:{}).clearChat)!=null?I:{},i=(N=r!=null?r:a.size)!=null?N:"32px",d=(O=a.iconName)!=null?O:"refresh-cw",c=(L=a.iconColor)!=null?L:"",p=(j=a.backgroundColor)!=null?j:"",m=(z=a.borderWidth)!=null?z:"",g=(oe=a.borderColor)!=null?oe:"",f=(ke=a.borderRadius)!=null?ke:"",x=(Ke=a.paddingX)!=null?Ke:"",v=(Ce=a.paddingY)!=null?Ce:"",A=(We=a.tooltipText)!=null?We:"Clear chat",M=(Ne=a.showTooltip)!=null?Ne:!0,B=y("div",n),D=!!(m||g),k=Lt("button",{className:ba("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!D&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":A},style:{height:i,width:i,color:c||On.actionIconColor,backgroundColor:p||void 0,border:D?`${m||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),H=ve(d,s,"currentColor",1);if(H&&(H.style.display="block",k.appendChild(H)),B.appendChild(k),M&&A){let be=null,Be=()=>{if(be)return;let Q=k.ownerDocument,ne=Q.body;if(!ne)return;be=_r(Q,"div","persona-clear-chat-tooltip"),be.textContent=A;let pe=_r(Q,"div");pe.className="persona-clear-chat-tooltip-arrow",be.appendChild(pe);let me=k.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(Ro),be.style.left=`${me.left+me.width/2}px`,be.style.top=`${me.top-8}px`,be.style.transform="translate(-50%, -100%)",ne.appendChild(be)},ue=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};B.addEventListener("mouseenter",Be),B.addEventListener("mouseleave",ue),k.addEventListener("focus",Be),k.addEventListener("blur",ue),B._cleanupTooltip=()=>{ue(),B.removeEventListener("mouseenter",Be),B.removeEventListener("mouseleave",ue),k.removeEventListener("focus",Be),k.removeEventListener("blur",ue)}}return{button:k,wrapper:B}};var On={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))"},oo=e=>{var H,S,I,N,O,L,j,z,oe,ke,Ke,Ce,We,Ne,be,Be;let{config:t,showClose:n=!0}=e,r=Lt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),s=(H=t==null?void 0:t.launcher)!=null?H:{},o=(S=s.headerIconSize)!=null?S:"48px",a=(I=s.closeButtonPlacement)!=null?I:"inline",i=(N=s.headerIconHidden)!=null?N:!1,d=s.headerIconName,c=Lt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:o,width:o,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let ue=parseFloat(o)||24,Q=ve(d,ue*.6,"currentColor",1);Q?c.replaceChildren(Q):c.textContent=(L=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?L:"\u{1F4AC}"}else if((j=t==null?void 0:t.launcher)!=null&&j.iconUrl){let ue=y("img");ue.src=t.launcher.iconUrl,ue.alt="",ue.className="persona-rounded-xl persona-object-cover",ue.style.height=o,ue.style.width=o,c.replaceChildren(ue)}else c.textContent=(oe=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?oe:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Lt("span",{className:"persona-text-base persona-font-semibold",text:(Ke=(ke=t==null?void 0:t.launcher)==null?void 0:ke.title)!=null?Ke:"Chat Assistant",style:{color:On.titleColor}}),g=Lt("span",{className:"persona-text-xs",text:(We=(Ce=t==null?void 0:t.launcher)==null?void 0:Ce.subtitle)!=null?We:"Here to help you get answers fast",style:{color:On.subtitleColor}});p.append(m,g),i?r.append(p):r.append(c,p);let f=(Ne=s.clearChat)!=null?Ne:{},x=(be=f.enabled)!=null?be:!0,v=(Be=f.placement)!=null?Be:"inline",A=null,M=null;if(x){let Q=Qi(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});A=Q.button,M=Q.wrapper,v==="top-right"&&(M.style.right="48px"),v==="inline"&&r.appendChild(M)}let B=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&v==="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:D,wrapper:k}=Ji(t,{showClose:n,wrapperClassName:B});return a!=="top-right"&&r.appendChild(k),{header:r,iconHolder:c,headerTitle:m,headerSubtitle:g,closeButton:D,closeButtonWrapper:k,clearChatButton:A,clearChatButtonWrapper:M}},ls=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Bo(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Ro)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let A=document.createElement("hr");a.appendChild(A)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",f.id),f.destructive&&x.setAttribute("data-destructive",""),f.icon){let A=ve(f.icon,16,"currentColor",1.5);A&&x.appendChild(A)}let v=document.createElement("span");v.textContent=f.label,x.appendChild(v),x.addEventListener("click",A=>{A.stopPropagation(),p(),n(f.id)}),a.appendChild(x)}let i=null;function d(){if(!o)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=x=>{!a.contains(x.target)&&!r.contains(x.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?c():p()}function g(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:m,destroy:g}}function Kt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=ve(t,r!=null?r:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function Fa(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let g=ve(t,o!=null?o:14,"currentColor",2);g&&p.appendChild(g)}let m=y("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))p.setAttribute(g,f);return p}function _a(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=y("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let m;p.icon?m=Kt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=y("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function c(p){a=p,d()}return{element:o,setSelected:c}}function Xi(e){var f,x;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let m=ve(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",c.appendChild(m)),d&&(c.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",c.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,A;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(A=d.border)!=null?A:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=Bo({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),s(v)},anchor:c,position:o,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",v=>{v.stopPropagation();let A=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",A?"false":"true"),g.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let v=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var ic=e=>{var r;let t=oo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function ky(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=ve(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=y("div","persona-relative");d.appendChild(i);let c=Bo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var lc=e=>{var B,D,k,H,S,I,N,O,L;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(B=t==null?void 0:t.launcher)!=null?B:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,c,p;if(d)c=Xi({label:(D=a.title)!=null?D:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=On.titleColor,p=(k=c.querySelector(".persona-combo-btn-label"))!=null?k:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=On.titleColor,p.textContent=(H=a.title)!=null?H:"Chat Assistant",c.appendChild(p),ky(c,s==null?void 0:s.trailingActions,(S=s==null?void 0:s.onAction)!=null?S:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let z=s.onTitleClick;c.addEventListener("click",oe=>{oe.target.closest("button")||z()}),c.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),z())})}let j=s==null?void 0:s.titleRowHover;j&&(c.style.borderRadius=(I=j.borderRadius)!=null?I:"10px",c.style.padding=(N=j.padding)!=null?N:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var z,oe;c.style.backgroundColor=(z=j.background)!=null?z:"",c.style.borderColor=(oe=j.border)!=null?oe:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let m=(O=a.closeButtonSize)!=null?O:"32px",g=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=m,f.style.width=m,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||On.actionIconColor;let x=(L=a.closeButtonIconName)!=null?L:"x",v=ve(x,"28px","currentColor",1);v?f.appendChild(v):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let A=y("div");A.style.display="none";let M=y("span");return M.style.display="none",{header:i,iconHolder:A,headerTitle:p,headerSubtitle:M,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Yi={default:ic,minimal:lc},cc=e=>{var t;return(t=Yi[e])!=null?t:Yi.default},qs=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let m=y("span"),g=y("span"),f=y("button");f.style.display="none";let x=y("div");return x.style.display="none",{header:c,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:f,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=cc(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Zi=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:o}},el=e=>{var H,S,I,N,O,L,j,z,oe,ke,Ke,Ce;let t=(H=e==null?void 0:e.sendButton)!=null?H:{},n=(S=t.useIcon)!=null?S:!1,r=(I=t.iconText)!=null?I:"\u2191",s=t.iconName,o=(N=t.stopIconName)!=null?N:"square",a=(O=t.tooltipText)!=null?O:"Send message",i=(L=t.stopTooltipText)!=null?L:"Stop generating",d=(z=(j=e==null?void 0:e.copy)==null?void 0:j.sendButtonLabel)!=null?z:"Send",c=(ke=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?ke:"Stop",p=(Ke=t.showTooltip)!=null?Ke:!1,m=(Ce=t.size)!=null?Ce:"40px",g=t.backgroundColor,f=t.textColor,x=y("div","persona-send-button-wrapper"),v=Lt("button",{className:ba("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||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}}),A=null,M=null;if(n){let We=parseFloat(m)||24,Ne=(f==null?void 0:f.trim())||"currentColor";s?(A=ve(s,We,Ne,2),A?v.appendChild(A):v.textContent=r):v.textContent=r,M=ve(o,We,Ne,2)}else v.textContent=d;let B=null;p&&a&&(B=y("div","persona-send-button-tooltip"),B.textContent=a,x.appendChild(B)),v.setAttribute("aria-label",a),x.appendChild(v);let D="send";return{button:v,wrapper:x,setMode:We=>{if(We===D)return;D=We;let Ne=We==="stop"?i:a;if(v.setAttribute("aria-label",Ne),B&&(B.textContent=Ne),n){if(A&&M){let be=We==="stop"?M:A;v.replaceChildren(be)}}else v.textContent=We==="stop"?c:d}}},tl=e=>{var B,D,k,H,S,I,N,O,L,j,z,oe;let t=(B=e==null?void 0:e.voiceRecognition)!=null?B:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((D=t.provider)==null?void 0:D.type)==="runtype";if(!(r||s))return null;let a=(H=(k=e==null?void 0:e.sendButton)==null?void 0:k.size)!=null?H:"40px",i=(S=t.iconName)!=null?S:"mic",d=(I=t.iconSize)!=null?I:a,c=parseFloat(d)||24,p=(O=t.backgroundColor)!=null?O:(N=e==null?void 0:e.sendButton)==null?void 0:N.backgroundColor,m=(j=t.iconColor)!=null?j:(L=e==null?void 0:e.sendButton)==null?void 0:L.textColor,g=y("div","persona-send-button-wrapper"),f=Lt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=ve(i,c,m||"currentColor",1.5);v?f.appendChild(v):f.textContent="\u{1F3A4}",g.appendChild(f);let A=(z=t.tooltipText)!=null?z:"Start voice recognition";if(((oe=t.showTooltip)!=null?oe:!1)&&A){let ke=y("div","persona-send-button-tooltip");ke.textContent=A,g.appendChild(ke)}return{button:f,wrapper:g}},nl=e=>{var x,v,A,M,B,D,k,H;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let n=(A=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?A:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let s=y("input");s.type="file",s.setAttribute("data-persona-composer-attachment-input",""),s.accept=((M=t.allowedTypes)!=null?M:no).join(","),s.multiple=((B=t.maxFiles)!=null?B:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=(D=t.buttonIconName)!=null?D:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),p=Lt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(k=t.buttonTooltipText)!=null?k:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let m=ve(o,d,"currentColor",1.5);m?p.appendChild(m):p.textContent="\u{1F4CE}",p.addEventListener("click",S=>{S.preventDefault(),s.click()}),c.appendChild(p);let g=(H=t.buttonTooltipText)!=null?H:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,c.appendChild(f),{button:p,wrapper:c,input:s,previewsContainer:r}},rl=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=o,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=o;return r},ol=()=>Lt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var zs=e=>{var x,v,A,M,B,D;let{config:t}=e,n=Lt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=ol(),s=Lt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:o,attachAutoResize:a}=Zi(t);a();let i=el(t),d=tl(t),c=nl(t),p=rl(t);c&&(c.previewsContainer.style.gap="8px",s.append(c.previewsContainer,c.input)),s.append(o);let m=Lt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),m.append(g,f),s.append(m),s.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(c==null?void 0:c.button)&&k.target!==(c==null?void 0:c.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(A=c==null?void 0:c.button)!=null?A:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(B=c==null?void 0:c.input)!=null?B:null,attachmentPreviewsContainer:(D=c==null?void 0:c.previewsContainer)!=null?D:null,actionsRow:m,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var Mg=()=>{let e=Lt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=ve("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),s=y("span","persona-pill-peek__caret"),o=ve("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},kg=e=>{var x,v,A,M,B,D;let{config:t}=e,n=Lt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ol();r.style.display="none";let s=rl(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=Zi(t);o.style.maxHeight="100px",a();let i=el(t),d=tl(t),c=nl(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Lt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&m.append(c.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(c==null?void 0:c.button)&&k.target!==(c==null?void 0:c.wrapper)&&o.focus()}),c&&p.append(c.input),p.append(m,o,g),c&&n.append(c.previewsContainer),n.append(p,r,s);let f=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:s,attachmentButton:(A=c==null?void 0:c.button)!=null?A:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(B=c==null?void 0:c.input)!=null?B:null,attachmentPreviewsContainer:(D=c==null?void 0:c.previewsContainer)!=null?D:null,actionsRow:f,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var Lg=e=>{var p,m,g,f,x,v,A,M,B,D,k,H,S,I,N,O,L;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=un(e);if(Ho(e)){let j=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},z=y("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(x=j.expandedSize)!=null?x:"anchored",z.style.zIndex=String((A=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?A:kn);let oe=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",z.appendChild(oe);let ke=y("div","persona-widget-pill-root");return ke.setAttribute("data-persona-composer-bar",""),ke.dataset.state="collapsed",ke.dataset.expandedSize=(M=j.expandedSize)!=null?M:"anchored",ke.style.zIndex=String((D=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?D:kn),{wrapper:z,panel:oe,pillRoot:ke}}if(n){let j=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(z),{wrapper:j,panel:z}}if(!t){let j=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(H=(k=e==null?void 0:e.launcher)==null?void 0:k.width)!=null?H:"100%";return j.style.width=oe,z.style.width="100%",j.appendChild(z),{wrapper:j,panel:z}}let s=(S=e==null?void 0:e.launcher)!=null?S:{},o=s.position&&Sr[s.position]?Sr[s.position]:Sr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((N=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?N:kn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(L=(O=e==null?void 0:e.launcher)==null?void 0:O.width)!=null?L:e==null?void 0:e.launcherWidth,c=d!=null?d:tr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Ly=(e,t)=>{var k,H,S,I,N,O,L,j,z;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Ji(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(S=(H=(k=e==null?void 0:e.launcher)==null?void 0:k.clearChat)==null?void 0:H.enabled)!=null?S:!0,a=null,i=null;if(o){let oe=Qi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Lt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Lt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let p=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(N=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?N:"Hello \u{1F44B}"}),m=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(L=(O=e==null?void 0:e.copy)==null?void 0:O.welcomeSubtitle)!=null?L:"Ask anything about your account or products."}),g=Lt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,m),f=y("div","persona-flex persona-flex-col persona-gap-3"),x=(j=e==null?void 0:e.layout)==null?void 0:j.contentMaxWidth;x&&(f.style.maxWidth=x,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,f);let A=Lt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),M=kg({config:e}),{root:B,textNode:D}=Mg();return n.append(d,s,c,A),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:f,composerOverlay:A,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:p,introSubtitle:m,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode,peekBanner:B,peekTextNode:D}},Pg=(e,t=!0)=>{var A,M,B,D,k,H,S,I,N;if(Ho(e))return Ly(e,t);let n=Lt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(A=e==null?void 0:e.layout)==null?void 0:A.header,s=((M=e==null?void 0:e.layout)==null?void 0:M.showHeader)!==!1,o=r?qs(e,r,{showClose:t}):oo({config:e,showClose:t}),a=Lt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(D=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?D:"Hello \u{1F44B}"}),d=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(H=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeSubtitle)!=null?H:"Ask anything about your account or products."}),c=Lt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:un(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),m=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let f=zs({config:e}),x=((N=e==null?void 0:e.layout)==null?void 0:N.showFooter)!==!1;s?ls(n,o,e):(o.header.style.display="none",ls(n,o,e)),n.append(a);let v=Lt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return x||(f.footer.style.display="none"),n.append(f.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:d,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var dc=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
16
+ _Details: ${n.message}_`:r}var La=e=>({isError:!0,content:[{type:"text",text:e}]}),sg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ag=e=>es(e)||e===Sr,_s=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new as(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,s,o,a,i,d,c,p,m;if(t.type==="message"){this.upsertMessage(t.message);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(es(g.name)||g.name===Sr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((s=t.message.agentMetadata)==null?void 0:s.awaitingLocalTool)===!0&&f&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.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:(a=t.message.agentMetadata.agentName)!=null?a:"",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 g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(m=(p=this.callbacks).onError)==null||m.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new rs(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var s,o,a,i,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(s=t.host)!=null?s:this.config.apiUrl,r=(d=t.agentId)!=null?d:(i=(a=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!n||!r||!this.config.clientToken||Ql().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return ka((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,s,o,a,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Io.isSupported()?new Io({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(r=t.host)!=null?r:this.config.apiUrl,c=(i=t.agentId)!=null?i:(a=(o=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:o.runtype)==null?void 0:a.agentId,p=this.config.clientToken,m=t.browserFallback!==!1;if(d&&c&&p)return Ql().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:f})=>{let x=new g({host:d,agentId:c,clientToken:p,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return m&&n?new f(x,n,{onFallback:v=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${v.message}`)}):x});if(m&&n)return p&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Po(s);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"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,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,s,o,a,i,d,c,p,m;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:(o=(s=t.runtype)==null?void 0:s.clientToken)!=null?o:this.config.clientToken,host:(i=(a=t.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=t.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=t.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((p=t.browser)==null?void 0:p.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!iy(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new rs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:m}=t,f={id:a!=null?a:n==="user"?Ns():n==="assistant"?os():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:m=!1,voiceProcessing:g,rawContent:f}=r,v={id:d!=null?d:s==="user"?Ns():s==="assistant"?os():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,c={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(c),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,m,g,f;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let s=Ns(),o=os(),a={id:s,role:"user",content:r||Pi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let A=og(x,this.config.errorMessage);if(A){let M={id:o,role:"assistant",createdAt:new Date().toISOString(),content:A,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(x instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,x):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(x))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=os();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let m=og(c,this.config.errorMessage);if(m){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,m,g,f,x;let s=`approval-${t.id}`,o={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===s),i={id:s,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:o};this.upsertMessage(i),(m=this.abortController)==null||m.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let A=null;if(v instanceof Response){if(!v.ok){let M=await v.json().catch(()=>null);throw new Error((g=M==null?void 0:M.error)!=null?g:`Approval request failed: ${v.status}`)}A=v.body}else v instanceof ReadableStream&&(A=v);A?await this.connectStream(A,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let A=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,A||(x=(f=this.callbacks).onError)==null||x.call(f,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,g,f,x,v,A,M,B,D,k,H;let r=this.messages.find(S=>S.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=t.agentMetadata)==null?void 0:m.executionId,o=(g=t.toolCall)==null?void 0:g.name;if(!s||!o){(x=(f=this.callbacks).onError)==null||x.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let S=(v=t.toolCall)==null?void 0:v.args,I=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(I.length===1){let N=typeof((A=I[0])==null?void 0:A.question)=="string"?I[0].question:"";N&&(a={[N]:n})}}this.markAskUserQuestionResolved(t,a),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(B=t.toolCall)==null?void 0:B.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let S=typeof n=="string"?n:Object.entries(n).map(([I,N])=>`${I}: ${Array.isArray(N)?N.join(", "):N}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let S=a!=null?a:{};c.forEach((I,N)=>{let O=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!O)return;let L=S[O],j=Array.isArray(L)?L.join(", "):typeof L=="string"?L:"";this.appendMessage({id:`ask-user-q-${i}-${N}`,role:"assistant",content:O,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${N}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(s,{[o]:n});if(!S.ok){let I=await S.json().catch(()=>null);throw new Error((D=I==null?void 0:I.error)!=null?D:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let I=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(H=(k=this.callbacks).onError)==null||H.call(k,S instanceof Error?S:new Error(String(S)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var s,o;let n=this.messages.find(a=>a.id===t.id),r=[(s=n==null?void 0:n.toolCall)==null?void 0:s.startedAt,(o=t.toolCall)==null?void 0:o.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,s;if(((r=t.toolCall)==null?void 0:r.name)!==Sr)return!1;let n=this.messages.find(o=>o.id===t.id);return((s=(n!=null?n:t).agentMetadata)==null?void 0:s.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,s=Date.now(),o){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...o},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:s,duration:void 0,durationMs:Math.max(0,s-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,m;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var H,S,I,N,O,L,j;let f=(H=g.toolCall)==null?void 0:H.name,x=(S=g.toolCall)==null?void 0:S.id;if(!f||!x)return null;let v=`${t}:${x}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(v),r.push(v);let A=this.markWebMcpToolRunning(g),M=(N=(I=g.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?N:f;if(f===Sr)return{dedupeKey:v,resumeKey:M,output:jl(),toolMessage:g,startedAt:A,completedAt:Date.now()};let B=new AbortController;this.webMcpResolveControllers.add(B),s.push(B);let D=this.client.executeWebMcpToolCall(f,(O=g.toolCall)==null?void 0:O.args,B.signal),k;if(!D)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await D}catch(z){let oe=z instanceof Error&&(z.name==="AbortError"||z.message.includes("aborted")||z.message.includes("abort"));return oe||(j=(L=this.callbacks).onError)==null||j.call(L,z instanceof Error?z:new Error(String(z))),this.markWebMcpToolComplete(g,La(oe?"Aborted by cancel()":sg(z)),A),this.webMcpInflightKeys.delete(v),null}return B.signal.aborted?(this.markWebMcpToolComplete(g,La("Aborted by cancel()"),A),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:M,output:k,toolMessage:g,startedAt:A,completedAt:Date.now()}})),i=[];try{if(i=a.filter(x=>x!==null),i.length===0)return;let g={};for(let x of i)g[x.resumeKey]=x.output;let f=await this.client.resumeFlow(t,g,{signal:o.signal});if(!f.ok){let x=await f.json().catch(()=>null);throw new Error((d=x==null?void 0:x.error)!=null?d:`Resume failed: ${f.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((c=x.toolMessage.toolCall)==null?void 0:c.name)===Sr?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(m=(p=this.callbacks).onError)==null||m.call(p,g instanceof Error?g:new Error(String(g)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,La("Aborted by cancel()"),x.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of s)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,v,A,M,B,D,k,H,S,I,N,O;let n=(x=t.agentMetadata)==null?void 0:x.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(A=t.toolCall)==null?void 0:A.id;if(!n){(B=(M=this.callbacks).onError)==null||B.call(M,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!s){let L=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(L)||this.webMcpResolvedKeys.has(L))return;this.webMcpInflightKeys.add(L);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(L)}catch(j){(k=(D=this.callbacks).onError)==null||k.call(D,j instanceof Error?j:new Error(String(j)))}finally{this.webMcpInflightKeys.delete(L)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(o);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Sr,p=(H=t.toolCall)==null?void 0:H.args,m=c?null:this.client.executeWebMcpToolCall(r,p,d),g="execute",f=a;try{let L;if(c?L=jl():m?L=await m:L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,La("Aborted by cancel()"),a);return}let j=(I=(S=t.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?I:r;g="resume",await this.resumeWithToolOutput(n,j,L,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,L,a,f,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(L){let j=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));(g==="execute"||j||d.aborted)&&this.markWebMcpToolComplete(t,La(j||d.aborted?"Aborted by cancel()":sg(L)),a),j||(O=(N=this.callbacks).onError)==null||O.call(N,L instanceof Error?L:new Error(String(L)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=Jl(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Fs(t)}toggleReadAloud(t){let n=this.messages.find(o=>o.id===t);if(!n||n.role!=="assistant")return;let r=Jl(n.content||"");if(!r.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:s==null?void 0:s.voice,rate:s==null?void 0:s.rate,pitch:s==null?void 0:s.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 n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,m,g,f,x,v,A,M,B,D,k,H,S,I,N;if(o!==r)return s;let a={...s,...n};if(((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((m=s.agentMetadata)==null?void 0:m.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let O=s.approval,L=n.approval;a.approval={...O,...L,executionId:L.executionId||O.executionId,toolName:L.toolName||O.toolName,description:L.description||O.description,toolType:(f=L.toolType)!=null?f:O.toolType,reason:(x=L.reason)!=null?x:O.reason,parameters:(v=L.parameters)!=null?v:O.parameters}}let i=(A=n.toolCall)==null?void 0:A.name,d=(M=n.agentMetadata)==null?void 0:M.executionId,c=(B=n.toolCall)==null?void 0:B.id;if(i&&ag(i)&&d&&c&&((D=n.agentMetadata)==null?void 0:D.awaitingLocalTool)===!0){let O=`${d}:${c}`,L=this.webMcpInflightKeys.has(O),j=this.webMcpResolvedKeys.has(O),z=(k=s.toolCall)==null?void 0:k.name,oe=((H=s.agentMetadata)==null?void 0:H.executionId)===d&&((S=s.toolCall)==null?void 0:S.id)===c&&z!==void 0&&ag(z)&&((I=s.toolCall)==null?void 0:I.status)==="complete";(L||j||oe)&&(a.agentMetadata={...(N=a.agentMetadata)!=null?N:{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var w=require("lucide"),ly={activity:w.Activity,"arrow-down":w.ArrowDown,"arrow-up":w.ArrowUp,"arrow-up-right":w.ArrowUpRight,bot:w.Bot,"chevron-down":w.ChevronDown,"chevron-up":w.ChevronUp,"chevron-right":w.ChevronRight,"chevron-left":w.ChevronLeft,check:w.Check,clipboard:w.Clipboard,"clipboard-copy":w.ClipboardCopy,copy:w.Copy,file:w.File,"file-code":w.FileCode,"file-spreadsheet":w.FileSpreadsheet,"file-text":w.FileText,"image-plus":w.ImagePlus,loader:w.Loader,"loader-circle":w.LoaderCircle,mic:w.Mic,paperclip:w.Paperclip,"refresh-cw":w.RefreshCw,search:w.Search,send:w.Send,"shield-alert":w.ShieldAlert,"shield-check":w.ShieldCheck,"shield-x":w.ShieldX,square:w.Square,"thumbs-down":w.ThumbsDown,"thumbs-up":w.ThumbsUp,upload:w.Upload,"volume-2":w.Volume2,x:w.X,user:w.User,mail:w.Mail,phone:w.Phone,calendar:w.Calendar,clock:w.Clock,building:w.Building,"map-pin":w.MapPin,lock:w.Lock,key:w.Key,"credit-card":w.CreditCard,"at-sign":w.AtSign,hash:w.Hash,globe:w.Globe,link:w.Link,"circle-check":w.CircleCheck,"circle-x":w.CircleX,"triangle-alert":w.TriangleAlert,info:w.Info,ban:w.Ban,shield:w.Shield,"arrow-left":w.ArrowLeft,"arrow-right":w.ArrowRight,"external-link":w.ExternalLink,ellipsis:w.Ellipsis,"ellipsis-vertical":w.EllipsisVertical,menu:w.Menu,house:w.House,plus:w.Plus,minus:w.Minus,pencil:w.Pencil,trash:w.Trash,"trash-2":w.Trash2,save:w.Save,download:w.Download,share:w.Share,funnel:w.Funnel,settings:w.Settings,"rotate-cw":w.RotateCw,maximize:w.Maximize,minimize:w.Minimize,"shopping-cart":w.ShoppingCart,"shopping-bag":w.ShoppingBag,package:w.Package,truck:w.Truck,tag:w.Tag,gift:w.Gift,receipt:w.Receipt,wallet:w.Wallet,store:w.Store,"dollar-sign":w.DollarSign,percent:w.Percent,play:w.Play,pause:w.Pause,"volume-x":w.VolumeX,camera:w.Camera,image:w.Image,film:w.Film,headphones:w.Headphones,"message-circle":w.MessageCircle,"message-square":w.MessageSquare,bell:w.Bell,heart:w.Heart,star:w.Star,eye:w.Eye,"eye-off":w.EyeOff,bookmark:w.Bookmark,"calendar-days":w.CalendarDays,history:w.History,timer:w.Timer,folder:w.Folder,"folder-open":w.FolderOpen,files:w.Files,sparkles:w.Sparkles,zap:w.Zap,sun:w.Sun,moon:w.Moon,flag:w.Flag,monitor:w.Monitor,smartphone:w.Smartphone},ve=(e,t=24,n="currentColor",r=2)=>{let s=ly[e];return s?cy(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function cy(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}),s}var Bi={allowedTypes:ro,maxFileSize:10*1024*1024,maxFiles:4};function dy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function py(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 is=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Bi.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Bi.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:Bi.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:Bi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,s,o,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=Jm(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,m);continue}try{let m=await Gm(c),g=Ii(c)?URL.createObjectURL(c):null,f={id:dy(),file:c,previewUrl:g,contentPart:m};this.attachments.push(f),this.renderPreview(f)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ii(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=py(t.file.type),d=ve(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Qm(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let s=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=ve("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var ig=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Pa(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];ig(o)&&ig(s)?n[r]=Pa(o,s):n[r]=s}return n}var tr="min(440px, calc(100vw - 24px))",Di="440px",uy={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:tr,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:uy,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 lg(e,t){if(!(!e&&!t))return e?t?Pa(e,t):e:t}function Ni(e){var t,n,r,s,o,a,i,d,c,p,m,g,f,x,v,A,M,B,D,k,H;return e?{..._t,...e,theme:lg(_t.theme,e.theme),darkTheme:lg(_t.darkTheme,e.darkTheme),launcher:{..._t.launcher,...e.launcher,dock:{...(t=_t.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=_t.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{..._t.copy,...e.copy},sendButton:{..._t.sendButton,...e.sendButton},statusIndicator:{..._t.statusIndicator,...e.statusIndicator},voiceRecognition:{..._t.voiceRecognition,...e.voiceRecognition},features:(()=>{var ue,Q,ne,pe,me,K,ae,He,Y,ee;let S=(ue=_t.features)==null?void 0:ue.artifacts,I=(Q=e.features)==null?void 0:Q.artifacts,N=(ne=_t.features)==null?void 0:ne.scrollToBottom,O=(pe=e.features)==null?void 0:pe.scrollToBottom,L=(me=_t.features)==null?void 0:me.scrollBehavior,j=(K=e.features)==null?void 0:K.scrollBehavior,z=(ae=_t.features)==null?void 0:ae.streamAnimation,oe=(He=e.features)==null?void 0:He.streamAnimation,ke=(Y=_t.features)==null?void 0:Y.askUserQuestion,Ke=(ee=e.features)==null?void 0:ee.askUserQuestion,Ce=S===void 0&&I===void 0?void 0:{...S,...I,layout:{...S==null?void 0:S.layout,...I==null?void 0:I.layout}},We=N===void 0&&O===void 0?void 0:{...N,...O},Ne=L===void 0&&j===void 0?void 0:{...L,...j},be=z===void 0&&oe===void 0?void 0:{...z,...oe},Be=ke===void 0&&Ke===void 0?void 0:{...ke,...Ke,styles:{...ke==null?void 0:ke.styles,...Ke==null?void 0:Ke.styles}};return{..._t.features,...e.features,...We!==void 0?{scrollToBottom:We}:{},...Ne!==void 0?{scrollBehavior:Ne}:{},...Ce!==void 0?{artifacts:Ce}:{},...be!==void 0?{streamAnimation:be}:{},...Be!==void 0?{askUserQuestion:Be}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:_t.suggestionChips,suggestionChipsConfig:{..._t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{..._t.layout,...e.layout,header:{...(a=_t.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=_t.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(m=(p=_t.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(v=(x=_t.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(M=(A=e.layout)==null?void 0:A.messages)==null?void 0:M.timestamp}},slots:{...(B=_t.layout)==null?void 0:B.slots,...(D=e.layout)==null?void 0:D.slots}},markdown:{..._t.markdown,...e.markdown,options:{...(k=_t.markdown)==null?void 0:k.options,...(H=e.markdown)==null?void 0:H.options}},messageActions:{..._t.messageActions,...e.messageActions}}:_t}var Xl={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"}},Yl={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"}},Zl={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:tr,maxWidth:Di,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function $s(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?$s(e,r):r}function Oi(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=$s(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function ec(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function cg(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=cg(o,s):n[r]=s}return n}function my(e,t){return t?cg(e,t):e}function js(e,t={}){var s,o,a,i,d,c,p,m,g,f,x,v,A;let n={palette:Xl,semantic:Yl,components:Zl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(x=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:x.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(A=e==null?void 0:e.semantic)==null?void 0:A.typography}},components:my(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let M=ec(r);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(B=>B.message).join(", ")}`)}if(t.plugins)for(let M of t.plugins)r=M.transform(r);return r}function Fi(e){var v,A,M,B,D,k,H,S,I,N,O,L,j,z,oe,ke,Ke,Ce,We,Ne,be,Be,ue,Q,ne,pe,me,K,ae,He,Y,ee,ie,Se,tt,Qe,Oe,fe,nt,te,ge,Me,Ze,Je,Pe,Ge,wn,Wt,mn,Tr,U,G,ye,Xe,rt,Ue,$e,Pt,Gt,Yt,Ln,V,Ht,le,Ae,_e,Tt,sn,an,Cn,Nt,at,Dt,pt,Zt,or,Pn,ln,Fn,Er,vt,qn,Mr,Ur,hr,bt,Oo,kr,Fo,_n,ms,lo,qr,co,po,_o,$o,uo,Ct,zn,Vn,In,Et,sr,ar,Kn,mo,zr,go,Gn,Ot,Rn,ir,fo,Vr,ho,Lr,Jn;let t=Oi(e),n={};for(let[xe,ut]of Object.entries(t)){let nn=xe.replace(/\./g,"-");n[`--persona-${nn}`]=ut.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(A=n["--persona-semantic-colors-secondary"])!=null?A:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(M=n["--persona-semantic-colors-accent"])!=null?M:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(B=n["--persona-semantic-colors-surface"])!=null?B:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(D=n["--persona-semantic-colors-background"])!=null?D:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(k=n["--persona-semantic-colors-container"])!=null?k:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(H=n["--persona-semantic-colors-text"])!=null?H:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(S=n["--persona-semantic-colors-text-muted"])!=null?S:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(N=n["--persona-semantic-colors-border"])!=null?N:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(O=n["--persona-semantic-colors-divider"])!=null?O:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(L=n["--persona-components-voice-recording-indicator"])!=null?L:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(j=n["--persona-components-voice-recording-background"])!=null?j:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(z=n["--persona-components-voice-processing-icon"])!=null?z:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(oe=n["--persona-components-voice-speaking-icon"])!=null?oe:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(ke=n["--persona-components-approval-requested-background"])!=null?ke:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Ke=n["--persona-components-approval-requested-border"])!=null?Ke:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ce=n["--persona-components-approval-requested-text"])!=null?Ce:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(We=n["--persona-components-approval-requested-shadow"])!=null?We:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(Ne=n["--persona-components-approval-approve-background"])!=null?Ne:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(be=n["--persona-components-approval-deny-background"])!=null?be:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Be=n["--persona-components-attachment-image-background"])!=null?Be:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ue=n["--persona-components-attachment-image-border"])!=null?ue:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Q=n["--persona-semantic-typography-fontFamily"])!=null?Q:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ne=n["--persona-semantic-typography-fontSize"])!=null?ne:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(pe=n["--persona-semantic-typography-fontWeight"])!=null?pe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(me=n["--persona-semantic-typography-lineHeight"])!=null?me:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(ae=n["--persona-palette-radius-md"])!=null?ae:"0.375rem",n["--persona-radius-lg"]=(He=n["--persona-palette-radius-lg"])!=null?He:"0.5rem",n["--persona-radius-xl"]=(Y=n["--persona-palette-radius-xl"])!=null?Y:"0.75rem",n["--persona-radius-full"]=(ee=n["--persona-palette-radius-full"])!=null?ee:"9999px",n["--persona-launcher-radius"]=(Se=(ie=n["--persona-components-launcher-borderRadius"])!=null?ie:n["--persona-palette-radius-full"])!=null?Se:"9999px",n["--persona-launcher-bg"]=(tt=n["--persona-components-launcher-background"])!=null?tt:n["--persona-primary"],n["--persona-launcher-fg"]=(Qe=n["--persona-components-launcher-foreground"])!=null?Qe:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Oe=n["--persona-components-launcher-border"])!=null?Oe:n["--persona-border"],n["--persona-button-primary-bg"]=(fe=n["--persona-components-button-primary-background"])!=null?fe:n["--persona-primary"],n["--persona-button-primary-fg"]=(nt=n["--persona-components-button-primary-foreground"])!=null?nt:n["--persona-text-inverse"],n["--persona-button-radius"]=(ge=(te=n["--persona-components-button-primary-borderRadius"])!=null?te:n["--persona-palette-radius-full"])!=null?ge:"9999px",n["--persona-panel-radius"]=(Ze=(Me=n["--persona-components-panel-borderRadius"])!=null?Me:n["--persona-radius-xl"])!=null?Ze:"0.75rem",n["--persona-panel-border"]=(Je=n["--persona-components-panel-border"])!=null?Je:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ge=(Pe=n["--persona-components-panel-shadow"])!=null?Pe:n["--persona-palette-shadows-xl"])!=null?Ge:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(wn=n["--persona-components-launcher-shadow"])!=null?wn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(mn=(Wt=n["--persona-components-input-borderRadius"])!=null?Wt:n["--persona-radius-lg"])!=null?mn:"0.5rem",n["--persona-message-user-radius"]=(U=(Tr=n["--persona-components-message-user-borderRadius"])!=null?Tr:n["--persona-radius-lg"])!=null?U:"0.5rem",n["--persona-message-assistant-radius"]=(ye=(G=n["--persona-components-message-assistant-borderRadius"])!=null?G:n["--persona-radius-lg"])!=null?ye:"0.5rem",n["--persona-header-bg"]=(Xe=n["--persona-components-header-background"])!=null?Xe:n["--persona-surface"],n["--persona-header-border"]=(rt=n["--persona-components-header-border"])!=null?rt:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ue=n["--persona-components-header-iconBackground"])!=null?Ue:n["--persona-primary"],n["--persona-header-icon-fg"]=($e=n["--persona-components-header-iconForeground"])!=null?$e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Pt=n["--persona-components-header-titleForeground"])!=null?Pt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Gt=n["--persona-components-header-subtitleForeground"])!=null?Gt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Yt=n["--persona-components-header-actionIconForeground"])!=null?Yt:n["--persona-muted"];let r=(Ln=e.components)==null?void 0:Ln.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(V=e.components)==null?void 0:V.introCard;n["--persona-intro-card-bg"]=(Ht=n["--persona-components-introCard-background"])!=null?Ht:n["--persona-surface"],n["--persona-intro-card-radius"]=(le=n["--persona-components-introCard-borderRadius"])!=null?le:"1rem",n["--persona-intro-card-padding"]=(Ae=n["--persona-components-introCard-padding"])!=null?Ae:"1.5rem",n["--persona-intro-card-shadow"]=(Tt=(_e=s==null?void 0:s.shadow)!=null?_e:n["--persona-components-introCard-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(sn=n["--persona-components-input-background"])!=null?sn:n["--persona-surface"],n["--persona-input-placeholder"]=(an=n["--persona-components-input-placeholder"])!=null?an:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Cn=n["--persona-components-message-user-background"])!=null?Cn:n["--persona-accent"],n["--persona-message-user-text"]=(Nt=n["--persona-components-message-user-text"])!=null?Nt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(at=n["--persona-components-message-user-shadow"])!=null?at:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Dt=n["--persona-components-message-assistant-background"])!=null?Dt:n["--persona-surface"],n["--persona-message-assistant-text"]=(pt=n["--persona-components-message-assistant-text"])!=null?pt:n["--persona-text"],n["--persona-message-assistant-border"]=(Zt=n["--persona-components-message-assistant-border"])!=null?Zt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(or=n["--persona-components-message-assistant-shadow"])!=null?or:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(ln=(Pn=n["--persona-components-scrollToBottom-background"])!=null?Pn:n["--persona-button-primary-bg"])!=null?ln:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Er=(Fn=n["--persona-components-scrollToBottom-foreground"])!=null?Fn:n["--persona-button-primary-fg"])!=null?Er:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(vt=n["--persona-components-scrollToBottom-border"])!=null?vt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(qn=n["--persona-components-scrollToBottom-size"])!=null?qn:"40px",n["--persona-scroll-to-bottom-radius"]=(hr=(Ur=(Mr=n["--persona-components-scrollToBottom-borderRadius"])!=null?Mr:n["--persona-button-radius"])!=null?Ur:n["--persona-radius-full"])!=null?hr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Oo=(bt=n["--persona-components-scrollToBottom-shadow"])!=null?bt:n["--persona-palette-shadows-sm"])!=null?Oo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(kr=n["--persona-components-scrollToBottom-padding"])!=null?kr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Fo=n["--persona-components-scrollToBottom-gap"])!=null?Fo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(ms=(_n=n["--persona-components-scrollToBottom-fontSize"])!=null?_n:n["--persona-palette-typography-fontSize-sm"])!=null?ms:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(lo=n["--persona-components-scrollToBottom-iconSize"])!=null?lo:"14px",n["--persona-tool-bubble-shadow"]=(qr=n["--persona-components-toolBubble-shadow"])!=null?qr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(co=n["--persona-components-reasoningBubble-shadow"])!=null?co:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(po=n["--persona-components-composer-shadow"])!=null?po:"none",n["--persona-md-inline-code-bg"]=(_o=n["--persona-components-markdown-inlineCode-background"])!=null?_o:n["--persona-container"],n["--persona-md-inline-code-color"]=($o=n["--persona-components-markdown-inlineCode-foreground"])!=null?$o:n["--persona-text"],n["--persona-md-link-color"]=(Ct=(uo=n["--persona-components-markdown-link-foreground"])!=null?uo:n["--persona-accent"])!=null?Ct:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(zn=n["--persona-components-markdown-codeBlock-background"])!=null?zn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Vn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Vn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(In=n["--persona-components-markdown-codeBlock-textColor"])!=null?In:"inherit",n["--persona-md-table-header-bg"]=(Et=n["--persona-components-markdown-table-headerBackground"])!=null?Et:n["--persona-container"],n["--persona-md-table-border-color"]=(sr=n["--persona-components-markdown-table-borderColor"])!=null?sr:n["--persona-border"],n["--persona-md-hr-color"]=(ar=n["--persona-components-markdown-hr-color"])!=null?ar:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Kn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Kn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(mo=n["--persona-components-markdown-blockquote-background"])!=null?mo:"transparent",n["--persona-md-blockquote-text-color"]=(zr=n["--persona-components-markdown-blockquote-textColor"])!=null?zr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(go=n["--persona-components-collapsibleWidget-container"])!=null?go:n["--persona-surface"],n["--cw-surface"]=(Gn=n["--persona-components-collapsibleWidget-surface"])!=null?Gn:n["--persona-surface"],n["--cw-border"]=(Ot=n["--persona-components-collapsibleWidget-border"])!=null?Ot:n["--persona-border"],n["--persona-message-border"]=(Rn=n["--persona-components-message-border"])!=null?Rn:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let xe=x.toolbar;xe.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,n["--persona-dropdown-bg"]=(ir=n["--persona-dropdown-bg"])!=null?ir:xe.copyMenuBackground),xe.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,n["--persona-dropdown-border"]=(fo=n["--persona-dropdown-border"])!=null?fo:xe.copyMenuBorder),xe.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,n["--persona-dropdown-shadow"]=(Vr=n["--persona-dropdown-shadow"])!=null?Vr:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(ho=n["--persona-dropdown-radius"])!=null?ho:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Lr=n["--persona-dropdown-item-hover-bg"])!=null?Lr:xe.copyMenuItemHoverBackground),xe.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(x!=null&&x.tab){let xe=x.tab;xe.background&&(n["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(n["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(n["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(n["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(n["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(n["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(n["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(x!=null&&x.pane){let xe=x.pane;if(xe.toolbarBackground){let ut=(Jn=$s(e,xe.toolbarBackground))!=null?Jn:xe.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ut}}return n}var dg={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 gy={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"}}},pg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ia=()=>{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"},fy=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ia()},tc=e=>fy(e),hy=e=>js(e),yy=e=>{var n;let t=js(void 0,{validate:!1});return js({...e,palette:{...t.palette,colors:{...gy.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Us=e=>{let t=tc(e),n=pg(e==null?void 0:e.theme),r=pg(e==null?void 0:e.darkTheme);return t==="dark"?yy(Pa(n!=null?n:{},r!=null?r:{})):hy(n)},by=e=>Fi(e),Ro=(e,t)=>{let n=Us(t),r=by(n);for(let[s,o]of Object.entries(r))e.style.setProperty(s,o)},_i=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ia())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Ia());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var ug=require("idiomorph"),$i=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;ug.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var ji={index:-1,draft:""};function mg(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...ji}}}function gg(e,t){var n,r,s,o,a,i,d,c,p,m,g,f,x,v,A,M,B,D,k,H,S,I,N,O,L,j,z,oe,ke,Ke,Ce,We,Ne,be,Be,ue,Q,ne;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(g=(m=e.approval)==null?void 0:m.status)!=null?g:"",(x=(f=e.toolCall)==null?void 0:f.status)!=null?x:"",(A=(v=e.toolCall)==null?void 0:v.name)!=null?A:"",(D=(B=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:B.length)!=null?D:0,(I=(S=(H=(k=e.toolCall)==null?void 0:k.chunks)==null?void 0:H[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?I:"",typeof((N=e.toolCall)==null?void 0:N.args)=="string"?e.toolCall.args.length:(O=e.toolCall)!=null&&O.args?JSON.stringify(e.toolCall.args).length:0,(z=(j=(L=e.reasoning)==null?void 0:L.chunks)==null?void 0:j.length)!=null?z:0,(Ce=(Ke=(ke=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:ke[e.reasoning.chunks.length-1])==null?void 0:Ke.length)!=null?Ce:0,(Be=(be=(Ne=(We=e.reasoning)==null?void 0:We.chunks)==null?void 0:Ne[e.reasoning.chunks.length-1])==null?void 0:be.slice(-32))!=null?Be:"",(Q=(ue=e.contentParts)==null?void 0:ue.length)!=null?Q:0,(ne=e.stopReason)!=null?ne:"",t].join("\0")}function fg(){return new Map}function hg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function yg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function bg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ui(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function oo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ls(e,t){return oo(e)-e.scrollTop<=t}function qi(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function zi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}function xg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function vg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function wg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Mn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},kn=1e5,Wo=kn+1;var Ra={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},xy=["pre","code","a","script","style"],Vi=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Ra.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ra.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ra.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Ra.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Ra.buffer}},Sg=[{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"}],Wa=new Map;for(let e of Sg)Wa.set(e.name,e);var Ag=e=>{Wa.set(e.name,e)},Tg=e=>{Sg.some(t=>t.name===e)||Wa.delete(e)},Eg=()=>Array.from(Wa.keys()),Ha=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=Wa.get(e))!=null?r:null},Ki=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
17
+ `);return o<0?"":e.slice(0,o)}return e},vy=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},wy=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},nc=/\s/,Cy=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Sy=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(nc.test(o[i])){let c=i;for(;c<o.length&&nc.test(o[c]);)c+=1;a.appendChild(r.createTextNode(o.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<o.length&&!nc.test(o[p]);)c.appendChild(vy(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}s.replaceChild(a,e)},Ay=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(wy(r,c,t,n.value)),n.value+=1));s.replaceChild(a,e)},Ba=(e,t,n,r)=>{var m,g;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((m=r==null?void 0:r.skipTags)!=null?m:xy).map(f=>f.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Cy(d,o)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?Sy:Ay;for(let f of i)p(f,n,c);return s.innerHTML},Gi=(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},Da=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Cg=new WeakMap,Ty=(e,t)=>{var o;if(!e.styles)return;let n=Cg.get(t);if(n||(n=new Set,Cg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},rc=new WeakMap,Ey=(e,t)=>{if(!e.onAttach)return;let n=rc.get(t);if(n||(n=new Map,rc.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Mg=e=>{let t=rc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},oc=(e,t)=>{Ty(e,t),Ey(e,t)};function sc(e,t=kn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var Na=0,Ho=null;function ac(e=document){var n;if(Na++,Na===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;Ho={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,Na=Math.max(0,Na-1),Na===0&&Ho)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=Ho.originalOverflow,s.style.position=Ho.originalPosition,s.style.top=Ho.originalTop,s.style.width=Ho.originalWidth,o.scrollTo(0,Ho.scrollY),Ho=null}}}var Oa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},un=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Bo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},nr=e=>{var n,r,s,o,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:Oa.side,width:(s=t==null?void 0:t.width)!=null?s:Oa.width,animate:(o=t==null?void 0:t.animate)!=null?o:Oa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Oa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Oa.maxHeight}};var Ar={"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 My="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ji=(e,t={})=>{var A,M,B,D,k,H;let{showClose:n=!0,wrapperClassName:r=My,buttonSize:s,iconSize:o="28px"}=t,a=(A=e==null?void 0:e.launcher)!=null?A:{},i=(M=s!=null?s:a.closeButtonSize)!=null?M:"32px",d=y("div",r),c=(B=a.closeButtonTooltipText)!=null?B:"Close chat",p=(D=a.closeButtonShowTooltip)!=null?D:!0,m=(k=a.closeButtonIconName)!=null?k:"x",g=(H=a.closeButtonIconText)!=null?H:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),x=Lt("button",{className:ba("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||On.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=ve(m,o,"currentColor",1);if(v?(v.style.display="block",x.appendChild(v)):x.textContent=g,d.appendChild(x),p&&c){let S=null,I=()=>{if(S)return;let O=x.ownerDocument,L=O.body;if(!L)return;S=$r(O,"div","persona-clear-chat-tooltip"),S.textContent=c;let j=$r(O,"div");j.className="persona-clear-chat-tooltip-arrow",S.appendChild(j);let z=x.getBoundingClientRect();S.style.position="fixed",S.style.zIndex=String(Wo),S.style.left=`${z.left+z.width/2}px`,S.style.top=`${z.top-8}px`,S.style.transform="translate(-50%, -100%)",L.appendChild(S)},N=()=>{S&&S.parentNode&&(S.parentNode.removeChild(S),S=null)};d.addEventListener("mouseenter",I),d.addEventListener("mouseleave",N),x.addEventListener("focus",I),x.addEventListener("blur",N),d._cleanupTooltip=()=>{N(),d.removeEventListener("mouseenter",I),d.removeEventListener("mouseleave",N),x.removeEventListener("focus",I),x.removeEventListener("blur",N)}}return{button:x,wrapper:d}},ky="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Qi=(e,t={})=>{var S,I,N,O,L,j,z,oe,ke,Ke,Ce,We,Ne;let{wrapperClassName:n=ky,buttonSize:r,iconSize:s="20px"}=t,a=(I=((S=e==null?void 0:e.launcher)!=null?S:{}).clearChat)!=null?I:{},i=(N=r!=null?r:a.size)!=null?N:"32px",d=(O=a.iconName)!=null?O:"refresh-cw",c=(L=a.iconColor)!=null?L:"",p=(j=a.backgroundColor)!=null?j:"",m=(z=a.borderWidth)!=null?z:"",g=(oe=a.borderColor)!=null?oe:"",f=(ke=a.borderRadius)!=null?ke:"",x=(Ke=a.paddingX)!=null?Ke:"",v=(Ce=a.paddingY)!=null?Ce:"",A=(We=a.tooltipText)!=null?We:"Clear chat",M=(Ne=a.showTooltip)!=null?Ne:!0,B=y("div",n),D=!!(m||g),k=Lt("button",{className:ba("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!D&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":A},style:{height:i,width:i,color:c||On.actionIconColor,backgroundColor:p||void 0,border:D?`${m||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),H=ve(d,s,"currentColor",1);if(H&&(H.style.display="block",k.appendChild(H)),B.appendChild(k),M&&A){let be=null,Be=()=>{if(be)return;let Q=k.ownerDocument,ne=Q.body;if(!ne)return;be=$r(Q,"div","persona-clear-chat-tooltip"),be.textContent=A;let pe=$r(Q,"div");pe.className="persona-clear-chat-tooltip-arrow",be.appendChild(pe);let me=k.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(Wo),be.style.left=`${me.left+me.width/2}px`,be.style.top=`${me.top-8}px`,be.style.transform="translate(-50%, -100%)",ne.appendChild(be)},ue=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};B.addEventListener("mouseenter",Be),B.addEventListener("mouseleave",ue),k.addEventListener("focus",Be),k.addEventListener("blur",ue),B._cleanupTooltip=()=>{ue(),B.removeEventListener("mouseenter",Be),B.removeEventListener("mouseleave",ue),k.removeEventListener("focus",Be),k.removeEventListener("blur",ue)}}return{button:k,wrapper:B}};var On={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))"},so=e=>{var H,S,I,N,O,L,j,z,oe,ke,Ke,Ce,We,Ne,be,Be;let{config:t,showClose:n=!0}=e,r=Lt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),s=(H=t==null?void 0:t.launcher)!=null?H:{},o=(S=s.headerIconSize)!=null?S:"48px",a=(I=s.closeButtonPlacement)!=null?I:"inline",i=(N=s.headerIconHidden)!=null?N:!1,d=s.headerIconName,c=Lt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:o,width:o,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let ue=parseFloat(o)||24,Q=ve(d,ue*.6,"currentColor",1);Q?c.replaceChildren(Q):c.textContent=(L=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?L:"\u{1F4AC}"}else if((j=t==null?void 0:t.launcher)!=null&&j.iconUrl){let ue=y("img");ue.src=t.launcher.iconUrl,ue.alt="",ue.className="persona-rounded-xl persona-object-cover",ue.style.height=o,ue.style.width=o,c.replaceChildren(ue)}else c.textContent=(oe=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?oe:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Lt("span",{className:"persona-text-base persona-font-semibold",text:(Ke=(ke=t==null?void 0:t.launcher)==null?void 0:ke.title)!=null?Ke:"Chat Assistant",style:{color:On.titleColor}}),g=Lt("span",{className:"persona-text-xs",text:(We=(Ce=t==null?void 0:t.launcher)==null?void 0:Ce.subtitle)!=null?We:"Here to help you get answers fast",style:{color:On.subtitleColor}});p.append(m,g),i?r.append(p):r.append(c,p);let f=(Ne=s.clearChat)!=null?Ne:{},x=(be=f.enabled)!=null?be:!0,v=(Be=f.placement)!=null?Be:"inline",A=null,M=null;if(x){let Q=Qi(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});A=Q.button,M=Q.wrapper,v==="top-right"&&(M.style.right="48px"),v==="inline"&&r.appendChild(M)}let B=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&v==="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:D,wrapper:k}=Ji(t,{showClose:n,wrapperClassName:B});return a!=="top-right"&&r.appendChild(k),{header:r,iconHolder:c,headerTitle:m,headerSubtitle:g,closeButton:D,closeButtonWrapper:k,clearChatButton:A,clearChatButtonWrapper:M}},cs=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Do(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Wo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let A=document.createElement("hr");a.appendChild(A)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",f.id),f.destructive&&x.setAttribute("data-destructive",""),f.icon){let A=ve(f.icon,16,"currentColor",1.5);A&&x.appendChild(A)}let v=document.createElement("span");v.textContent=f.label,x.appendChild(v),x.addEventListener("click",A=>{A.stopPropagation(),p(),n(f.id)}),a.appendChild(x)}let i=null;function d(){if(!o)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=x=>{!a.contains(x.target)&&!r.contains(x.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?c():p()}function g(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:m,destroy:g}}function Kt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=ve(t,r!=null?r:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function Fa(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let g=ve(t,o!=null?o:14,"currentColor",2);g&&p.appendChild(g)}let m=y("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))p.setAttribute(g,f);return p}function _a(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=y("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let m;p.icon?m=Kt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=y("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function c(p){a=p,d()}return{element:o,setSelected:c}}function Xi(e){var f,x;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let m=ve(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",c.appendChild(m)),d&&(c.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",c.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,A;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(A=d.border)!=null?A:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=Do({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),s(v)},anchor:c,position:o,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",v=>{v.stopPropagation();let A=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",A?"false":"true"),g.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let v=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var ic=e=>{var r;let t=so({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function Ly(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=ve(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=y("div","persona-relative");d.appendChild(i);let c=Do({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var lc=e=>{var B,D,k,H,S,I,N,O,L;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(B=t==null?void 0:t.launcher)!=null?B:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,c,p;if(d)c=Xi({label:(D=a.title)!=null?D:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=On.titleColor,p=(k=c.querySelector(".persona-combo-btn-label"))!=null?k:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=On.titleColor,p.textContent=(H=a.title)!=null?H:"Chat Assistant",c.appendChild(p),Ly(c,s==null?void 0:s.trailingActions,(S=s==null?void 0:s.onAction)!=null?S:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let z=s.onTitleClick;c.addEventListener("click",oe=>{oe.target.closest("button")||z()}),c.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),z())})}let j=s==null?void 0:s.titleRowHover;j&&(c.style.borderRadius=(I=j.borderRadius)!=null?I:"10px",c.style.padding=(N=j.padding)!=null?N:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var z,oe;c.style.backgroundColor=(z=j.background)!=null?z:"",c.style.borderColor=(oe=j.border)!=null?oe:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let m=(O=a.closeButtonSize)!=null?O:"32px",g=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=m,f.style.width=m,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||On.actionIconColor;let x=(L=a.closeButtonIconName)!=null?L:"x",v=ve(x,"28px","currentColor",1);v?f.appendChild(v):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let A=y("div");A.style.display="none";let M=y("span");return M.style.display="none",{header:i,iconHolder:A,headerTitle:p,headerSubtitle:M,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Yi={default:ic,minimal:lc},cc=e=>{var t;return(t=Yi[e])!=null?t:Yi.default},qs=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let m=y("span"),g=y("span"),f=y("button");f.style.display="none";let x=y("div");return x.style.display="none",{header:c,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:f,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=cc(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Zi=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:o}},el=e=>{var H,S,I,N,O,L,j,z,oe,ke,Ke,Ce;let t=(H=e==null?void 0:e.sendButton)!=null?H:{},n=(S=t.useIcon)!=null?S:!1,r=(I=t.iconText)!=null?I:"\u2191",s=t.iconName,o=(N=t.stopIconName)!=null?N:"square",a=(O=t.tooltipText)!=null?O:"Send message",i=(L=t.stopTooltipText)!=null?L:"Stop generating",d=(z=(j=e==null?void 0:e.copy)==null?void 0:j.sendButtonLabel)!=null?z:"Send",c=(ke=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?ke:"Stop",p=(Ke=t.showTooltip)!=null?Ke:!1,m=(Ce=t.size)!=null?Ce:"40px",g=t.backgroundColor,f=t.textColor,x=y("div","persona-send-button-wrapper"),v=Lt("button",{className:ba("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||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}}),A=null,M=null;if(n){let We=parseFloat(m)||24,Ne=(f==null?void 0:f.trim())||"currentColor";s?(A=ve(s,We,Ne,2),A?v.appendChild(A):v.textContent=r):v.textContent=r,M=ve(o,We,Ne,2)}else v.textContent=d;let B=null;p&&a&&(B=y("div","persona-send-button-tooltip"),B.textContent=a,x.appendChild(B)),v.setAttribute("aria-label",a),x.appendChild(v);let D="send";return{button:v,wrapper:x,setMode:We=>{if(We===D)return;D=We;let Ne=We==="stop"?i:a;if(v.setAttribute("aria-label",Ne),B&&(B.textContent=Ne),n){if(A&&M){let be=We==="stop"?M:A;v.replaceChildren(be)}}else v.textContent=We==="stop"?c:d}}},tl=e=>{var B,D,k,H,S,I,N,O,L,j,z,oe;let t=(B=e==null?void 0:e.voiceRecognition)!=null?B:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((D=t.provider)==null?void 0:D.type)==="runtype";if(!(r||s))return null;let a=(H=(k=e==null?void 0:e.sendButton)==null?void 0:k.size)!=null?H:"40px",i=(S=t.iconName)!=null?S:"mic",d=(I=t.iconSize)!=null?I:a,c=parseFloat(d)||24,p=(O=t.backgroundColor)!=null?O:(N=e==null?void 0:e.sendButton)==null?void 0:N.backgroundColor,m=(j=t.iconColor)!=null?j:(L=e==null?void 0:e.sendButton)==null?void 0:L.textColor,g=y("div","persona-send-button-wrapper"),f=Lt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=ve(i,c,m||"currentColor",1.5);v?f.appendChild(v):f.textContent="\u{1F3A4}",g.appendChild(f);let A=(z=t.tooltipText)!=null?z:"Start voice recognition";if(((oe=t.showTooltip)!=null?oe:!1)&&A){let ke=y("div","persona-send-button-tooltip");ke.textContent=A,g.appendChild(ke)}return{button:f,wrapper:g}},nl=e=>{var x,v,A,M,B,D,k,H;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let n=(A=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?A:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let s=y("input");s.type="file",s.setAttribute("data-persona-composer-attachment-input",""),s.accept=((M=t.allowedTypes)!=null?M:ro).join(","),s.multiple=((B=t.maxFiles)!=null?B:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=(D=t.buttonIconName)!=null?D:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),p=Lt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(k=t.buttonTooltipText)!=null?k:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let m=ve(o,d,"currentColor",1.5);m?p.appendChild(m):p.textContent="\u{1F4CE}",p.addEventListener("click",S=>{S.preventDefault(),s.click()}),c.appendChild(p);let g=(H=t.buttonTooltipText)!=null?H:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,c.appendChild(f),{button:p,wrapper:c,input:s,previewsContainer:r}},rl=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=o,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=o;return r},ol=()=>Lt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var zs=e=>{var x,v,A,M,B,D;let{config:t}=e,n=Lt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=ol(),s=Lt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:o,attachAutoResize:a}=Zi(t);a();let i=el(t),d=tl(t),c=nl(t),p=rl(t);c&&(c.previewsContainer.style.gap="8px",s.append(c.previewsContainer,c.input)),s.append(o);let m=Lt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),m.append(g,f),s.append(m),s.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(c==null?void 0:c.button)&&k.target!==(c==null?void 0:c.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(A=c==null?void 0:c.button)!=null?A:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(B=c==null?void 0:c.input)!=null?B:null,attachmentPreviewsContainer:(D=c==null?void 0:c.previewsContainer)!=null?D:null,actionsRow:m,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var kg=()=>{let e=Lt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=ve("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),s=y("span","persona-pill-peek__caret"),o=ve("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},Lg=e=>{var x,v,A,M,B,D;let{config:t}=e,n=Lt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ol();r.style.display="none";let s=rl(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=Zi(t);o.style.maxHeight="100px",a();let i=el(t),d=tl(t),c=nl(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Lt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&m.append(c.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(c==null?void 0:c.button)&&k.target!==(c==null?void 0:c.wrapper)&&o.focus()}),c&&p.append(c.input),p.append(m,o,g),c&&n.append(c.previewsContainer),n.append(p,r,s);let f=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:s,attachmentButton:(A=c==null?void 0:c.button)!=null?A:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(B=c==null?void 0:c.input)!=null?B:null,attachmentPreviewsContainer:(D=c==null?void 0:c.previewsContainer)!=null?D:null,actionsRow:f,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var Pg=e=>{var p,m,g,f,x,v,A,M,B,D,k,H,S,I,N,O,L;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=un(e);if(Bo(e)){let j=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},z=y("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(x=j.expandedSize)!=null?x:"anchored",z.style.zIndex=String((A=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?A:kn);let oe=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",z.appendChild(oe);let ke=y("div","persona-widget-pill-root");return ke.setAttribute("data-persona-composer-bar",""),ke.dataset.state="collapsed",ke.dataset.expandedSize=(M=j.expandedSize)!=null?M:"anchored",ke.style.zIndex=String((D=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?D:kn),{wrapper:z,panel:oe,pillRoot:ke}}if(n){let j=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(z),{wrapper:j,panel:z}}if(!t){let j=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(H=(k=e==null?void 0:e.launcher)==null?void 0:k.width)!=null?H:"100%";return j.style.width=oe,z.style.width="100%",j.appendChild(z),{wrapper:j,panel:z}}let s=(S=e==null?void 0:e.launcher)!=null?S:{},o=s.position&&Ar[s.position]?Ar[s.position]:Ar["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((N=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?N:kn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(L=(O=e==null?void 0:e.launcher)==null?void 0:O.width)!=null?L:e==null?void 0:e.launcherWidth,c=d!=null?d:tr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Py=(e,t)=>{var k,H,S,I,N,O,L,j,z;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=Ji(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(S=(H=(k=e==null?void 0:e.launcher)==null?void 0:k.clearChat)==null?void 0:H.enabled)!=null?S:!0,a=null,i=null;if(o){let oe=Qi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Lt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Lt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let p=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(N=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?N:"Hello \u{1F44B}"}),m=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(L=(O=e==null?void 0:e.copy)==null?void 0:O.welcomeSubtitle)!=null?L:"Ask anything about your account or products."}),g=Lt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,m),f=y("div","persona-flex persona-flex-col persona-gap-3"),x=(j=e==null?void 0:e.layout)==null?void 0:j.contentMaxWidth;x&&(f.style.maxWidth=x,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,f);let A=Lt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),M=Lg({config:e}),{root:B,textNode:D}=kg();return n.append(d,s,c,A),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:f,composerOverlay:A,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:p,introSubtitle:m,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode,peekBanner:B,peekTextNode:D}},Ig=(e,t=!0)=>{var A,M,B,D,k,H,S,I,N;if(Bo(e))return Py(e,t);let n=Lt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(A=e==null?void 0:e.layout)==null?void 0:A.header,s=((M=e==null?void 0:e.layout)==null?void 0:M.showHeader)!==!1,o=r?qs(e,r,{showClose:t}):so({config:e,showClose:t}),a=Lt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(D=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?D:"Hello \u{1F44B}"}),d=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(H=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeSubtitle)!=null?H:"Ask anything about your account or products."}),c=Lt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:un(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),m=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let f=zs({config:e}),x=((N=e==null?void 0:e.layout)==null?void 0:N.showFooter)!==!1;s?cs(n,o,e):(o.header.style.display="none",cs(n,o,e)),n.append(a);let v=Lt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return x||(f.footer.style.display="none"),n.append(f.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:d,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var dc=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
18
18
  <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>
19
19
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
20
20
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -22,14 +22,14 @@ _Details: ${n.message}_`:r}var La=e=>({isError:!0,content:[{type:"text",text:e}]
22
22
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
23
23
  </span>
24
24
  <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>
25
- `,n.addEventListener("click",t);let r=o=>{var D,k,H,S,I,N,O,L,j,z,oe,ke,Ke;let a=(D=o.launcher)!=null?D:{},i=un(o),d=n.querySelector("[data-role='launcher-title']");if(d){let Ce=(k=a.title)!=null?k:"Chat Assistant";d.textContent=Ce,d.setAttribute("title",Ce)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let Ce=(H=a.subtitle)!=null?H:"Here to help you get answers fast";c.textContent=Ce,c.setAttribute("title",Ce)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let Ce=(S=a.agentIconSize)!=null?S:"40px";if(m.style.height=Ce,m.style.width=Ce,m.innerHTML="",a.agentIconName){let We=parseFloat(Ce)||24,Ne=ve(a.agentIconName,We*.6,"var(--persona-text-inverse, #ffffff)",2);Ne?(m.appendChild(Ne),m.style.display=""):(m.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(N=a.agentIconText)!=null?N:"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let Ce=(O=a.agentIconSize)!=null?O:"40px";g.style.height=Ce,g.style.width=Ce,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let Ce=(L=a.callToActionIconSize)!=null?L:"32px";f.style.height=Ce,f.style.width=Ce,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let We=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,We=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Ne=parseFloat(Ce)||24,be=Math.max(Ne-We,8),Be=ve(a.callToActionIconName,be,"currentColor",2);Be?f.appendChild(Be):f.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else f.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let x=a.position&&Sr[a.position]?Sr[a.position]:Sr["bottom-right"],v="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",A="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?A:`${v} ${x}`,i||(n.style.zIndex=String((oe=a.zIndex)!=null?oe:kn));let M="1px solid var(--persona-border, #e5e7eb)",B="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(ke=a.border)!=null?ke:M,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:B,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(Ke=a.collapsedMaxWidth)!=null?Ke:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var Ig=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:s}=Lg(e),o=Pg(e,t),a={wrapper:n,panel:r,pillRoot:s},i={container:o.container,body:o.body,messagesWrapper:o.messagesWrapper,composerOverlay:o.composerOverlay,introTitle:o.introTitle,introSubtitle:o.introSubtitle},d={element:o.header,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper},c={footer:o.footer,form:o.composerForm,textarea:o.textarea,sendButton:o.sendButton,sendButtonWrapper:o.sendButtonWrapper,micButton:o.micButton,micButtonWrapper:o.micButtonWrapper,statusText:o.statusText,suggestions:o.suggestions,attachmentButton:o.attachmentButton,attachmentButtonWrapper:o.attachmentButtonWrapper,attachmentInput:o.attachmentInput,attachmentPreviewsContainer:o.attachmentPreviewsContainer,actionsRow:o.actionsRow,leftActions:o.leftActions,rightActions:o.rightActions,setSendButtonMode:o.setSendButtonMode,peekBanner:o.peekBanner,peekTextNode:o.peekTextNode};return{shell:a,panelElements:o,transcript:i,header:d,composer:c,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},pc=({config:e,plugins:t,onToggle:n})=>{let r=t.find(o=>o.renderLauncher);if(r!=null&&r.renderLauncher){let o=r.renderLauncher({config:e,defaultRenderer:()=>dc(e,n).element,onToggle:n});if(o)return{instance:null,element:o}}let s=dc(e,n);return{instance:s,element:s.element}};var Py=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}},Iy=(e,t)=>{if(!e)return null;let n=Py(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},Ry=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Wy=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},uc=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(":"))},mc=320,Wg=320,Hy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),By=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Dy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Ny=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Oy=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let c=y("img");c.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${mc}px`,c.style.maxHeight=`${Wg}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),Wy(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},Fy=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!uc(r.audio))return;let s=y("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${mc}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},_y=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!uc(r.video))return;let s=y("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${mc}px`,s.style.maxHeight=`${Wg}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},$y=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!uc(r.data))return;let s=y("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},cs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},gc=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:cs};if(t){let s=t(r);if(s!==null)return s}return cs()},jy=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=y("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Rg=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),s=new Date(e.createdAt);return t.format?r.textContent=t.format(s):r.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Uy=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},fc=(e,t,n)=>{var x,v,A,M,B,D,k;let r=(x=t.showCopy)!=null?x:!0,s=(v=t.showUpvote)!=null?v:!0,o=(A=t.showDownvote)!=null?A:!0,a=(M=t.showReadAloud)!=null?M:!1;if(!r&&!s&&!o&&!a){let H=y("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let i=(B=t.visibility)!=null?B:"hover",d=(D=t.align)!=null?D:"right",c=(k=t.layout)!=null?k:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${m} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(H,S,I)=>{let N=Kt({icon:H,label:S,size:14,className:"persona-message-action-btn"});return N.setAttribute("data-action",I),N};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),s&&g.appendChild(f("thumbs-up","Upvote","upvote")),o&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},Vs=(e,t,n,r,s,o)=>{var ue,Q,ne,pe,me,K,ae,He,Y,ee,ie,Se,tt,Qe,Oe,fe,nt;let a=n!=null?n:{},i=(ue=a.layout)!=null?ue:"bubble",d=a.avatar,c=a.timestamp,p=(Q=d==null?void 0:d.show)!=null?Q:!1,m=(ne=c==null?void 0:c.show)!=null?ne:!1,g=(pe=d==null?void 0:d.position)!=null?pe:"left",f=(me=c==null?void 0:c.position)!=null?me:"below",x=Uy(e.role,i),v=y("div",x.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let A=Hy(e),M=(ae=(K=e.content)==null?void 0:K.trim())!=null?ae:"",D=A.length>0&&M===Pi,k=Vi((Y=(He=o==null?void 0:o.widgetConfig)==null?void 0:He.features)==null?void 0:Y.streamAnimation),H=(Se=(ie=(ee=o==null?void 0:o.widgetConfig)==null?void 0:ee.features)==null?void 0:ie.streamAnimation)==null?void 0:Se.plugins,S=e.role==="assistant"&&k.type!=="none"?Ha(k.type,H):null,I=e.role==="assistant"&&((tt=S==null?void 0:S.isAnimating)==null?void 0:tt.call(S,e))===!0,N=e.role==="assistant"&&S!==null&&(!!e.streaming||I);N&&(S!=null&&S.bubbleClass)&&v.classList.add(S.bubbleClass);let O=document.createElement("div");O.classList.add("persona-message-content"),N&&S&&(S.containerClass&&O.classList.add(S.containerClass),O.style.setProperty("--persona-stream-step",`${k.speed}ms`),O.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let L=N?Ki((Qe=e.content)!=null?Qe:"",k.buffer,S,e,!!e.streaming):(Oe=e.content)!=null?Oe:"",j=t({text:L,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=j;N&&(S==null?void 0:S.wrap)==="char"?z=Ba(j,"char",e.id,{skipTags:S.skipTags}):N&&(S==null?void 0:S.wrap)==="word"&&(z=Ba(j,"word",e.id,{skipTags:S.skipTags}));let oe=null;if(D?(oe=document.createElement("div"),oe.innerHTML=z,oe.style.display="none",O.appendChild(oe)):O.innerHTML=z,N&&(S!=null&&S.useCaret)&&!D&&M){let te=Gi(),ge=O.querySelectorAll(".persona-stream-char, .persona-stream-word"),Me=ge[ge.length-1];if(Me!=null&&Me.parentNode)Me.parentNode.insertBefore(te,Me.nextSibling);else{let Ze=O.lastElementChild;Ze?Ze.appendChild(te):O.appendChild(te)}}if(m&&f==="inline"&&e.createdAt){let te=Rg(e,c,"span");te.classList.add("persona-timestamp-inline");let ge=O.lastElementChild;ge?ge.appendChild(te):O.appendChild(te)}if(A.length>0){let te=Oy(A,!D&&!!M,()=>{D&&oe&&(oe.style.display="")});te?v.appendChild(te):D&&oe&&(oe.style.display="")}let ke=By(e);if(ke.length>0){let te=Fy(ke);te&&v.appendChild(te)}let Ke=Dy(e);if(Ke.length>0){let te=_y(Ke);te&&v.appendChild(te)}let Ce=Ny(e);if(Ce.length>0){let te=$y(Ce);te&&v.appendChild(te)}if(v.appendChild(O),m&&f==="below"&&e.createdAt){let te=Rg(e,c);te.classList.add("persona-mt-1"),v.appendChild(te)}let We=e.role==="assistant"?Iy(e.stopReason,(nt=(fe=o==null?void 0:o.widgetConfig)==null?void 0:fe.copy)==null?void 0:nt.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let te=!!(L&&L.trim()),ge=k.placeholder==="skeleton",Me=ge&&k.buffer==="line"&&te;if(te)Me&&v.appendChild(Da());else if(ge)v.appendChild(Da());else{let Ze=gc("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Ze&&v.appendChild(Ze)}}if(We&&e.stopReason&&!e.streaming&&(M||(O.style.display="none"),v.appendChild(Ry(e.stopReason,We))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let te=fc(e,r,s);v.appendChild(te)}if(!p||e.role==="system")return v;let be=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Be=jy(d,e.role);return g==="right"||g==="left"&&e.role==="user"?be.append(v,Be):be.append(Be,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),be},Hg=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Vs(e,t,n,r,s,o)};var Ks=new Set,qy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zy=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},Bg=(e,t)=>{let n=Ks.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),o=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=ve(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",o&&(o.style.display=n?"none":o.textContent||o.childNodes.length?"":"none")},hc=(e,t)=>{var Ke,Ce,We,Ne,be,Be,ue,Q,ne,pe,me;let n=e.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let s=(Ce=(Ke=t==null?void 0:t.features)==null?void 0:Ke.reasoningDisplay)!=null?Ce:{},o=s.expandable!==!1,a=o&&Ks.has(e.id),i=n.status!=="complete",d=zy(e,(We=s.previewMaxLines)!=null?We:3),c=y("button",o?"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");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),m=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=(Ne=t==null?void 0:t.reasoning)!=null?Ne:{},x=String((be=n.startedAt)!=null?be:Date.now()),v=()=>{let K=y("span","");return K.setAttribute("data-tool-elapsed",x),K.textContent=Ci(n),K},A=(Be=f.renderCollapsedSummary)==null?void 0:Be.call(f,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ci(n),createElapsedElement:v});typeof A=="string"&&A.trim()?(m.textContent=A,p.appendChild(m)):A instanceof HTMLElement?p.appendChild(A):(m.textContent=g,p.appendChild(m));let M=y("span","persona-text-xs persona-text-persona-primary");M.textContent=Hm(n),p.appendChild(M);let B=(ue=s.loadingAnimation)!=null?ue:"none",D=f.activeTextTemplate,k=f.completeTextTemplate,H=i?D:k,S=A instanceof HTMLElement,I=(K,ae,He)=>{let Y=He;for(let ee of ae){let ie=y("span","persona-tool-char");ie.style.setProperty("--char-index",String(Y)),ie.textContent=ee===" "?"\xA0":ee,K.appendChild(ie),Y++}return Y},N=(K,ae)=>{m.textContent="";let He=Si(K,""),Y=0;for(let ee of He){let ie=ee.styles.length>0?(()=>{let Se=y("span",ee.styles.map(tt=>`persona-tool-text-${tt}`).join(" "));return m.appendChild(Se),Se})():m;if(ee.isDuration&&i)ie.appendChild(v());else{let Se=ee.isDuration?Ci(n):ee.text;ae?Y=I(ie,Se,Y):ie.appendChild(document.createTextNode(Se))}}};if(!S&&H)if(M.style.display="none",m.style.display="",i&&B!=="none"){let K=(Q=f.loadingAnimationDuration)!=null?Q:2e3;m.setAttribute("data-preserve-animation","true"),B==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`),N(H,!1)):(m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`),B==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),N(H,!0))}else N(H,!1);else if(!S&&i&&B!=="none"){m.style.display="";let K=(ne=f.loadingAnimationDuration)!=null?ne:2e3;if(m.setAttribute("data-preserve-animation","true"),B==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`),B==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let ae=m.textContent||g;m.textContent="",I(m,ae,0)}n.status==="complete"&&(m.style.display="none")}else S||(n.status==="complete"?m.style.display="none":m.style.display="");let O=null;if(o){O=y("div","persona-flex persona-items-center");let ae=ve(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?O.appendChild(ae):O.textContent=a?"Hide":"Show";let He=y("div","persona-flex persona-items-center persona-ml-auto");He.append(O),c.append(p,He)}else c.append(p);let L=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(L.setAttribute("data-persona-collapsed-preview","reasoning"),L.style.display="none",L.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let K=(me=(pe=t==null?void 0:t.reasoning)==null?void 0:pe.renderCollapsedPreview)==null?void 0:me.call(pe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});qy(L,K)||(L.textContent=d),L.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(c,L),r;let j=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let z=n.chunks.join(""),oe=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=z||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(oe),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),O){O.innerHTML="";let ae=ve(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?O.appendChild(ae):O.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",L.style.display=a?"none":L.textContent||L.childNodes.length?"":"none"})(),r.append(c,L,j),r};var Gs=new Set,Vy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Ky=(e,t)=>{var o;let n=e.toolCall;if(!n)return"";let r=((o=n.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
+ `,n.addEventListener("click",t);let r=o=>{var D,k,H,S,I,N,O,L,j,z,oe,ke,Ke;let a=(D=o.launcher)!=null?D:{},i=un(o),d=n.querySelector("[data-role='launcher-title']");if(d){let Ce=(k=a.title)!=null?k:"Chat Assistant";d.textContent=Ce,d.setAttribute("title",Ce)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let Ce=(H=a.subtitle)!=null?H:"Here to help you get answers fast";c.textContent=Ce,c.setAttribute("title",Ce)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let Ce=(S=a.agentIconSize)!=null?S:"40px";if(m.style.height=Ce,m.style.width=Ce,m.innerHTML="",a.agentIconName){let We=parseFloat(Ce)||24,Ne=ve(a.agentIconName,We*.6,"var(--persona-text-inverse, #ffffff)",2);Ne?(m.appendChild(Ne),m.style.display=""):(m.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(N=a.agentIconText)!=null?N:"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let Ce=(O=a.agentIconSize)!=null?O:"40px";g.style.height=Ce,g.style.width=Ce,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let Ce=(L=a.callToActionIconSize)!=null?L:"32px";f.style.height=Ce,f.style.width=Ce,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let We=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,We=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Ne=parseFloat(Ce)||24,be=Math.max(Ne-We,8),Be=ve(a.callToActionIconName,be,"currentColor",2);Be?f.appendChild(Be):f.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else f.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let x=a.position&&Ar[a.position]?Ar[a.position]:Ar["bottom-right"],v="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",A="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?A:`${v} ${x}`,i||(n.style.zIndex=String((oe=a.zIndex)!=null?oe:kn));let M="1px solid var(--persona-border, #e5e7eb)",B="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(ke=a.border)!=null?ke:M,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:B,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(Ke=a.collapsedMaxWidth)!=null?Ke:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var Rg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:s}=Pg(e),o=Ig(e,t),a={wrapper:n,panel:r,pillRoot:s},i={container:o.container,body:o.body,messagesWrapper:o.messagesWrapper,composerOverlay:o.composerOverlay,introTitle:o.introTitle,introSubtitle:o.introSubtitle},d={element:o.header,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper},c={footer:o.footer,form:o.composerForm,textarea:o.textarea,sendButton:o.sendButton,sendButtonWrapper:o.sendButtonWrapper,micButton:o.micButton,micButtonWrapper:o.micButtonWrapper,statusText:o.statusText,suggestions:o.suggestions,attachmentButton:o.attachmentButton,attachmentButtonWrapper:o.attachmentButtonWrapper,attachmentInput:o.attachmentInput,attachmentPreviewsContainer:o.attachmentPreviewsContainer,actionsRow:o.actionsRow,leftActions:o.leftActions,rightActions:o.rightActions,setSendButtonMode:o.setSendButtonMode,peekBanner:o.peekBanner,peekTextNode:o.peekTextNode};return{shell:a,panelElements:o,transcript:i,header:d,composer:c,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},pc=({config:e,plugins:t,onToggle:n})=>{let r=t.find(o=>o.renderLauncher);if(r!=null&&r.renderLauncher){let o=r.renderLauncher({config:e,defaultRenderer:()=>dc(e,n).element,onToggle:n});if(o)return{instance:null,element:o}}let s=dc(e,n);return{instance:s,element:s.element}};var Iy=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}},Ry=(e,t)=>{if(!e)return null;let n=Iy(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},Wy=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Hy=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},uc=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(":"))},mc=320,Hg=320,By=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Dy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ny=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Oy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Fy=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let c=y("img");c.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${mc}px`,c.style.maxHeight=`${Hg}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),Hy(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},_y=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!uc(r.audio))return;let s=y("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${mc}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},$y=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!uc(r.video))return;let s=y("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${mc}px`,s.style.maxHeight=`${Hg}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},jy=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!uc(r.data))return;let s=y("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ds=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},gc=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ds};if(t){let s=t(r);if(s!==null)return s}return ds()},Uy=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=y("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Wg=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),s=new Date(e.createdAt);return t.format?r.textContent=t.format(s):r.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},qy=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},fc=(e,t,n)=>{var x,v,A,M,B,D,k;let r=(x=t.showCopy)!=null?x:!0,s=(v=t.showUpvote)!=null?v:!0,o=(A=t.showDownvote)!=null?A:!0,a=(M=t.showReadAloud)!=null?M:!1;if(!r&&!s&&!o&&!a){let H=y("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let i=(B=t.visibility)!=null?B:"hover",d=(D=t.align)!=null?D:"right",c=(k=t.layout)!=null?k:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${m} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(H,S,I)=>{let N=Kt({icon:H,label:S,size:14,className:"persona-message-action-btn"});return N.setAttribute("data-action",I),N};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),s&&g.appendChild(f("thumbs-up","Upvote","upvote")),o&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},Vs=(e,t,n,r,s,o)=>{var ue,Q,ne,pe,me,K,ae,He,Y,ee,ie,Se,tt,Qe,Oe,fe,nt;let a=n!=null?n:{},i=(ue=a.layout)!=null?ue:"bubble",d=a.avatar,c=a.timestamp,p=(Q=d==null?void 0:d.show)!=null?Q:!1,m=(ne=c==null?void 0:c.show)!=null?ne:!1,g=(pe=d==null?void 0:d.position)!=null?pe:"left",f=(me=c==null?void 0:c.position)!=null?me:"below",x=qy(e.role,i),v=y("div",x.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let A=By(e),M=(ae=(K=e.content)==null?void 0:K.trim())!=null?ae:"",D=A.length>0&&M===Pi,k=Vi((Y=(He=o==null?void 0:o.widgetConfig)==null?void 0:He.features)==null?void 0:Y.streamAnimation),H=(Se=(ie=(ee=o==null?void 0:o.widgetConfig)==null?void 0:ee.features)==null?void 0:ie.streamAnimation)==null?void 0:Se.plugins,S=e.role==="assistant"&&k.type!=="none"?Ha(k.type,H):null,I=e.role==="assistant"&&((tt=S==null?void 0:S.isAnimating)==null?void 0:tt.call(S,e))===!0,N=e.role==="assistant"&&S!==null&&(!!e.streaming||I);N&&(S!=null&&S.bubbleClass)&&v.classList.add(S.bubbleClass);let O=document.createElement("div");O.classList.add("persona-message-content"),N&&S&&(S.containerClass&&O.classList.add(S.containerClass),O.style.setProperty("--persona-stream-step",`${k.speed}ms`),O.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let L=N?Ki((Qe=e.content)!=null?Qe:"",k.buffer,S,e,!!e.streaming):(Oe=e.content)!=null?Oe:"",j=t({text:L,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=j;N&&(S==null?void 0:S.wrap)==="char"?z=Ba(j,"char",e.id,{skipTags:S.skipTags}):N&&(S==null?void 0:S.wrap)==="word"&&(z=Ba(j,"word",e.id,{skipTags:S.skipTags}));let oe=null;if(D?(oe=document.createElement("div"),oe.innerHTML=z,oe.style.display="none",O.appendChild(oe)):O.innerHTML=z,N&&(S!=null&&S.useCaret)&&!D&&M){let te=Gi(),ge=O.querySelectorAll(".persona-stream-char, .persona-stream-word"),Me=ge[ge.length-1];if(Me!=null&&Me.parentNode)Me.parentNode.insertBefore(te,Me.nextSibling);else{let Ze=O.lastElementChild;Ze?Ze.appendChild(te):O.appendChild(te)}}if(m&&f==="inline"&&e.createdAt){let te=Wg(e,c,"span");te.classList.add("persona-timestamp-inline");let ge=O.lastElementChild;ge?ge.appendChild(te):O.appendChild(te)}if(A.length>0){let te=Fy(A,!D&&!!M,()=>{D&&oe&&(oe.style.display="")});te?v.appendChild(te):D&&oe&&(oe.style.display="")}let ke=Dy(e);if(ke.length>0){let te=_y(ke);te&&v.appendChild(te)}let Ke=Ny(e);if(Ke.length>0){let te=$y(Ke);te&&v.appendChild(te)}let Ce=Oy(e);if(Ce.length>0){let te=jy(Ce);te&&v.appendChild(te)}if(v.appendChild(O),m&&f==="below"&&e.createdAt){let te=Wg(e,c);te.classList.add("persona-mt-1"),v.appendChild(te)}let We=e.role==="assistant"?Ry(e.stopReason,(nt=(fe=o==null?void 0:o.widgetConfig)==null?void 0:fe.copy)==null?void 0:nt.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let te=!!(L&&L.trim()),ge=k.placeholder==="skeleton",Me=ge&&k.buffer==="line"&&te;if(te)Me&&v.appendChild(Da());else if(ge)v.appendChild(Da());else{let Ze=gc("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Ze&&v.appendChild(Ze)}}if(We&&e.stopReason&&!e.streaming&&(M||(O.style.display="none"),v.appendChild(Wy(e.stopReason,We))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let te=fc(e,r,s);v.appendChild(te)}if(!p||e.role==="system")return v;let be=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Be=Uy(d,e.role);return g==="right"||g==="left"&&e.role==="user"?be.append(v,Be):be.append(Be,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),be},Bg=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Vs(e,t,n,r,s,o)};var Ks=new Set,zy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Vy=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},Dg=(e,t)=>{let n=Ks.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),o=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=ve(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",o&&(o.style.display=n?"none":o.textContent||o.childNodes.length?"":"none")},hc=(e,t)=>{var Ke,Ce,We,Ne,be,Be,ue,Q,ne,pe,me;let n=e.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let s=(Ce=(Ke=t==null?void 0:t.features)==null?void 0:Ke.reasoningDisplay)!=null?Ce:{},o=s.expandable!==!1,a=o&&Ks.has(e.id),i=n.status!=="complete",d=Vy(e,(We=s.previewMaxLines)!=null?We:3),c=y("button",o?"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");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),m=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=(Ne=t==null?void 0:t.reasoning)!=null?Ne:{},x=String((be=n.startedAt)!=null?be:Date.now()),v=()=>{let K=y("span","");return K.setAttribute("data-tool-elapsed",x),K.textContent=Ci(n),K},A=(Be=f.renderCollapsedSummary)==null?void 0:Be.call(f,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ci(n),createElapsedElement:v});typeof A=="string"&&A.trim()?(m.textContent=A,p.appendChild(m)):A instanceof HTMLElement?p.appendChild(A):(m.textContent=g,p.appendChild(m));let M=y("span","persona-text-xs persona-text-persona-primary");M.textContent=Hm(n),p.appendChild(M);let B=(ue=s.loadingAnimation)!=null?ue:"none",D=f.activeTextTemplate,k=f.completeTextTemplate,H=i?D:k,S=A instanceof HTMLElement,I=(K,ae,He)=>{let Y=He;for(let ee of ae){let ie=y("span","persona-tool-char");ie.style.setProperty("--char-index",String(Y)),ie.textContent=ee===" "?"\xA0":ee,K.appendChild(ie),Y++}return Y},N=(K,ae)=>{m.textContent="";let He=Si(K,""),Y=0;for(let ee of He){let ie=ee.styles.length>0?(()=>{let Se=y("span",ee.styles.map(tt=>`persona-tool-text-${tt}`).join(" "));return m.appendChild(Se),Se})():m;if(ee.isDuration&&i)ie.appendChild(v());else{let Se=ee.isDuration?Ci(n):ee.text;ae?Y=I(ie,Se,Y):ie.appendChild(document.createTextNode(Se))}}};if(!S&&H)if(M.style.display="none",m.style.display="",i&&B!=="none"){let K=(Q=f.loadingAnimationDuration)!=null?Q:2e3;m.setAttribute("data-preserve-animation","true"),B==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`),N(H,!1)):(m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`),B==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),N(H,!0))}else N(H,!1);else if(!S&&i&&B!=="none"){m.style.display="";let K=(ne=f.loadingAnimationDuration)!=null?ne:2e3;if(m.setAttribute("data-preserve-animation","true"),B==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${K}ms`),B==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let ae=m.textContent||g;m.textContent="",I(m,ae,0)}n.status==="complete"&&(m.style.display="none")}else S||(n.status==="complete"?m.style.display="none":m.style.display="");let O=null;if(o){O=y("div","persona-flex persona-items-center");let ae=ve(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?O.appendChild(ae):O.textContent=a?"Hide":"Show";let He=y("div","persona-flex persona-items-center persona-ml-auto");He.append(O),c.append(p,He)}else c.append(p);let L=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(L.setAttribute("data-persona-collapsed-preview","reasoning"),L.style.display="none",L.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let K=(me=(pe=t==null?void 0:t.reasoning)==null?void 0:pe.renderCollapsedPreview)==null?void 0:me.call(pe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});zy(L,K)||(L.textContent=d),L.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(c,L),r;let j=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let z=n.chunks.join(""),oe=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=z||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(oe),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),O){O.innerHTML="";let ae=ve(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?O.appendChild(ae):O.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",L.style.display=a?"none":L.textContent||L.childNodes.length?"":"none"})(),r.append(c,L,j),r};var Gs=new Set,Ky=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Gy=(e,t)=>{var o;let n=e.toolCall;if(!n)return"";let r=((o=n.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
27
27
  `);let s=Ds(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
28
- `):""},Gy=(e,t)=>{var p,m,g,f,x;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=Ky(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?Bm(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(f=t==null?void 0:t.toolCall)!=null?f:{},c=a;return s==="tool-name"?c=((x=n.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(c=o),i&&d.activeTextTemplate?c=Vl(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Vl(n,d.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},Dg=(e,t,n)=>{var p;let r=Gs.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let m=s.toggleTextColor||s.headerTextColor||"currentColor",g=ve(r?"chevron-up":"chevron-down",16,m,2);g?c.appendChild(g):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},yc=(e,t)=>{var z,oe,ke,Ke,Ce,We,Ne,be,Be;let n=e.toolCall,r=(z=t==null?void 0:t.toolCall)!=null?z:{},s=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let o=(ke=(oe=t==null?void 0:t.features)==null?void 0:oe.toolCallDisplay)!=null?ke:{},a=o.expandable!==!1,i=a&&Gs.has(e.id),{summary:d,previewText:c,isActive:p}=Gy(e,t),m=y("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");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let x=String((Ke=n.startedAt)!=null?Ke:Date.now()),v=()=>{let ue=y("span","");return ue.setAttribute("data-tool-elapsed",x),ue.textContent=Ta(n),ue},A=(We=r.renderCollapsedSummary)==null?void 0:We.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(Ce=o.collapsedMode)!=null?Ce:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Ta(n),createElapsedElement:v});typeof A=="string"&&A.trim()?(f.textContent=A,g.appendChild(f)):A instanceof HTMLElement?g.appendChild(A):(f.textContent=d,g.appendChild(f));let M=(Ne=o.loadingAnimation)!=null?Ne:"none",B=r.activeTextTemplate,D=r.completeTextTemplate,k=p?B:D,H=A instanceof HTMLElement,S=(ue,Q,ne)=>{let pe=ne;for(let me of Q){let K=y("span","persona-tool-char");K.style.setProperty("--char-index",String(pe)),K.textContent=me===" "?"\xA0":me,ue.appendChild(K),pe++}return pe},I=(ue,Q)=>{var K;f.textContent="";let ne=((K=n.name)==null?void 0:K.trim())||"tool",pe=Si(ue,ne),me=0;for(let ae of pe){let He=ae.styles.length>0?(()=>{let Y=y("span",ae.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(Y),Y})():f;if(ae.isDuration&&p)He.appendChild(v());else{let Y=ae.isDuration?Ta(n):ae.text;Q?me=S(He,Y,me):He.appendChild(document.createTextNode(Y))}}};if(!H)if(p&&M!=="none"){let ue=(be=r.loadingAnimationDuration)!=null?be:2e3;if(f.setAttribute("data-preserve-animation","true"),M==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),k&&I(k,!1);else if(f.classList.add(`persona-tool-loading-${M}`),f.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),M==="shimmer-color"&&(r.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),k)I(k,!0);else{let Q=f.textContent||d;f.textContent="",S(f,Q,0)}}else k&&I(k,!1);let N=null;if(a){N=y("div","persona-flex persona-items-center");let ue=r.toggleTextColor||r.headerTextColor||"currentColor",Q=ve(i?"chevron-up":"chevron-down",16,ue,2);Q?N.appendChild(Q):N.textContent=i?"Hide":"Show";let ne=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ne.append(N),m.append(g,ne)}else m.append(g);let O=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","tool"),O.style.display="none",O.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let ue=(Be=r.renderCollapsedPreview)==null?void 0:Be.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});Vy(O,ue)||(O.textContent=c),O.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,O),s;let L=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(L.style.display=i?"":"none",r.contentBackgroundColor&&(L.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(L.style.color=r.contentTextColor),r.contentPaddingX&&(L.style.paddingLeft=r.contentPaddingX,L.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(L.style.paddingTop=r.contentPaddingY,L.style.paddingBottom=r.contentPaddingY),n.name){let ue=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ue.style.color=r.contentTextColor:r.headerTextColor&&(ue.style.color=r.headerTextColor),ue.textContent=n.name,L.appendChild(ue)}if(n.args!==void 0){let ue=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Arguments";let ne=y("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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ne.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ne.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ne.style.color=r.codeBlockTextColor),ne.textContent=Ds(n.args),ue.append(Q,ne),L.appendChild(ue)}if(n.chunks&&n.chunks.length){let ue=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Activity";let ne=y("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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ne.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ne.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ne.style.color=r.codeBlockTextColor),ne.textContent=n.chunks.join(""),ue.append(Q,ne),L.appendChild(ue)}if(n.status==="complete"&&n.result!==void 0){let ue=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Result";let ne=y("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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ne.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ne.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ne.style.color=r.codeBlockTextColor),ne.textContent=Ds(n.result),ue.append(Q,ne),L.appendChild(ue)}if(n.status==="complete"&&typeof n.duration=="number"){let ue=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ue.style.color=r.contentTextColor),ue.textContent=`Duration: ${n.duration}ms`,L.appendChild(ue)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),N){N.innerHTML="";let ue=r.toggleTextColor||r.headerTextColor||"currentColor",Q=ve(i?"chevron-up":"chevron-down",16,ue,2);Q?N.appendChild(Q):N.textContent=i?"Hide":"Show"}L.style.display=i?"":"none",O.style.display=i?"none":O.textContent||O.childNodes.length?"":"none"})(),s.append(m,O,L),s};var sl=new Map,Jy=e=>{let n=(e.startsWith(Yr)?e.slice(Yr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Ng=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Og=(e,t)=>{var r,s,o;let n=(s=(r=Ng(t))==null?void 0:r.detailsDisplay)!=null?s:"collapsed";return(o=sl.get(e))!=null?o:n==="expanded"},Fg=(e,t,n)=>{var a,i;let r=Ng(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let o=e.querySelector("[data-approval-details-chevron]");if(o){o.innerHTML="";let d=ve(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&o.appendChild(d)}},_g=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let o=Og(e,n);Fg(r,o,n),s.style.display=o?"":"none"};var al=(e,t)=>{var I,N,O,L,j,z,oe,ke,Ke,Ce,We,Ne,be,Be,ue;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(I=r==null?void 0:r.backgroundColor)!=null?I:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(N=r==null?void 0:r.borderColor)!=null?N:"var(--persona-approval-border, #fef08a)",o.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(O=r==null?void 0:r.titleColor)!=null?O:"currentColor",p=ve(d,20,c,2);p&&i.appendChild(p);let m=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(f.style.color=r.titleColor),f.textContent=(L=r==null?void 0:r.title)!=null?L:"Approval Required",g.appendChild(f),!s){let Q=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");Q.setAttribute("data-approval-status",n.status),n.status==="approved"?(Q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",Q.style.color="var(--persona-palette-colors-success-700, #15803d)",Q.textContent="Approved"):n.status==="denied"?(Q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",Q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",Q.textContent="Denied"):n.status==="timeout"&&(Q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",Q.style.color="var(--persona-palette-colors-warning-700, #b45309)",Q.textContent="Timeout"),g.appendChild(Q)}m.appendChild(g);let v=n.toolType==="webmcp"||n.toolName.startsWith(Yr)?Bl(n.toolName):void 0,A=(j=r==null?void 0:r.formatDescription)==null?void 0:j.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),M=!n.toolName,B=A||(M?n.description:`The assistant wants to use \u201C${v!=null?v:Jy(n.toolName)}\u201D.`),D=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(D.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(D.style.color=r.descriptionColor),D.textContent=B,m.appendChild(D),n.reason){let Q=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");Q.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?Q.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor);let ne=y("span","persona-font-medium");ne.textContent=`${(z=r==null?void 0:r.reasonLabel)!=null?z:"Agent's stated reason:"} `,Q.appendChild(ne),Q.appendChild(document.createTextNode(n.reason)),m.appendChild(Q)}let k=(oe=r==null?void 0:r.detailsDisplay)!=null?oe:"collapsed",H=!!n.description&&!M,S=H||!!n.parameters;if(k!=="hidden"&&S){let Q=Og(e.id,t),ne=y("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");ne.type="button",ne.setAttribute("data-expand-header","true"),ne.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ne.style.color=r.descriptionColor);let pe=y("span");pe.setAttribute("data-approval-details-label","true");let me=y("span","persona-inline-flex persona-items-center");me.setAttribute("data-approval-details-chevron","true"),ne.append(pe,me),Fg(ne,Q,t),m.appendChild(ne);let K=y("div");if(K.setAttribute("data-approval-details","true"),K.style.display=Q?"":"none",H){let ae=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor),ae.textContent=n.description,K.appendChild(ae)}if(n.parameters){let ae=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(ae.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ae.style.color=r.parameterTextColor),ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",ae.textContent=Ds(n.parameters),K.appendChild(ae)}m.appendChild(K)}if(s){let Q=y("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let ne=y("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");ne.type="button",ne.style.backgroundColor=(ke=r==null?void 0:r.approveButtonColor)!=null?ke:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(Ke=r==null?void 0:r.approveButtonTextColor)!=null?Ke:"#ffffff",ne.setAttribute("data-approval-action","approve");let pe=ve("shield-check",14,(Ce=r==null?void 0:r.approveButtonTextColor)!=null?Ce:"#ffffff",2);pe&&(pe.style.marginRight="4px",ne.appendChild(pe));let me=document.createTextNode((We=r==null?void 0:r.approveLabel)!=null?We:"Approve");ne.appendChild(me);let K=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(Ne=r==null?void 0:r.denyButtonColor)!=null?Ne:"transparent",K.style.color=(be=r==null?void 0:r.denyButtonTextColor)!=null?be:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let ae=ve("shield-x",14,(Be=r==null?void 0:r.denyButtonTextColor)!=null?Be:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",K.appendChild(ae));let He=document.createTextNode((ue=r==null?void 0:r.denyLabel)!=null?ue:"Deny");K.appendChild(He),Q.append(ne,K),m.appendChild(Q)}return a.append(i,m),o.appendChild(a),o};var $g=e=>{let t=[],n=null;return{buttons:t,render:(s,o,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!s||!s.length||!p&&(i!=null?i:o?o.getMessages():[]).some(A=>A.role==="user"))return;let m=document.createDocumentFragment(),g=o?o.isStreaming():!1,f=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(s.forEach(x=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=x,v.disabled=g,d!=null&&d.fontFamily&&(v.style.fontFamily=f(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!o||o.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),o.sendMessage(x))}),m.appendChild(v),t.push(v)}),e.appendChild(m),p){let x=JSON.stringify(s);x!==n&&(n=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...s]},bubbles:!0,composed:!0})))}}}};var $a=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ja=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var Qy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Xy=new Set(["step_start","execution_start"]),Yy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Zy=new Set(["step_complete","agent_turn_complete"]),eb=new Set(["flow_complete","agent_complete"]),jg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),qg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ds=(e,t)=>{let n=e[t];return qg(n)?n:void 0};function bc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function il(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function tb(e,t){return typeof t.type=="string"?t.type:e}function nb(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 rb(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 Ug(e){var r,s,o,a,i;let t=ds(e,"result"),n=[ds(e,"tokens"),ds(e,"totalTokens"),t?ds(t,"tokens"):void 0,ds(e,"usage"),t?ds(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(s=(r=rr(d.output))!=null?r:rr(d.outputTokens))!=null?s:rr(d.completionTokens);if(c!==void 0)return c}return(i=(o=rr(e.outputTokens))!=null?o:rr(e.completionTokens))!=null?i:t?(a=rr(t.outputTokens))!=null?a:rr(t.completionTokens):void 0}function ob(e){var n,r,s,o,a;let t=ds(e,"result");return(a=(s=(r=(n=rr(e.executionTime))!=null?n:rr(e.executionTimeMs))!=null?r:rr(e.execution_time))!=null?s:rr(e.duration))!=null?a:t?(o=rr(t.executionTime))!=null?o:rr(t.executionTimeMs):void 0}function sb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ua=class{constructor(t=sb){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:il(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var o;if(!qg(n)){jg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=tb(t,n),s=this.now();if(Qy.has(r)){this.startRun(s);return}if(Xy.has(r)){this.run||this.startRun(s);return}if(Yy.has(r)){if(!rb(r,n))return;let a=nb(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+bc(i.visibleCharCount),c=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:il(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Zy.has(r)){if(!this.run)return;let a=this.run,i=Ug(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+bc(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:il(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(eb.has(r)){if(!this.run)return;let a=this.run,i=Ug(n),d=i!=null?i:a.exactOutputTokens+bc(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:il(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(jg.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=ob(n);return o!=null?o:r-t.startedAt}};function Js(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var ab={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)"}},ib={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},lb=["flowName","stepName","reasoningText","text","name","tool","toolName"],cb=100;function db(e,t){let n={...ab,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return ib}function pb(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function ub(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function mb(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function gb(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function fb(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 hb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function yb(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 bb(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function xc(e,t,n,r,s,o,a,i){var g;let d=s.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Js(c,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(f)return c.appendChild(f),c}return c.appendChild(m()),c;function m(){var z,oe;let f=y("div",""),x=y("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 v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),A=ve(d?"chevron-down":"chevron-right","14px","currentColor",2);A&&v.appendChild(A);let M=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=(z=r.timestampFormat)!=null?z:"relative";M.textContent=B==="relative"?pb(e.timestamp,n):ub(e.timestamp);let D=null;r.showSequenceNumbers!==!1&&(D=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),D.textContent=String(t+1));let k=db(e.type,r.badgeColors),H=y("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");H.style.backgroundColor=k.bg,H.style.color=k.text,H.style.borderColor=k.text+"50",H.textContent=e.type;let S=(oe=r.descriptionFields)!=null?oe:lb,I=mb(e.payload,S),N=null;I&&(N=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=I);let O=y("div","persona-flex-1 persona-min-w-0"),L=y("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"),j=ve("clipboard","12px","currentColor",1.5);return j&&L.appendChild(j),L.addEventListener("click",async ke=>{ke.stopPropagation(),await gb(fb(e)),L.innerHTML="";let Ke=ve("check","12px","currentColor",1.5);Ke&&L.appendChild(Ke),setTimeout(()=>{L.innerHTML="";let Ce=ve("clipboard","12px","currentColor",1.5);Ce&&L.appendChild(Ce)},1500)}),x.appendChild(v),x.appendChild(M),D&&x.appendChild(D),x.appendChild(H),N&&x.appendChild(N),x.appendChild(O),x.appendChild(L),f.appendChild(x),d&&f.appendChild(bb(e,a,i)),f}}function zg(e){var x,v,A,M,B;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(x=s==null?void 0:s.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(A=i==null?void 0:i.label)!=null?A:"",m=(B=(M=s==null?void 0:s.features)==null?void 0:M.eventStream)!=null?B:{},g=o.find(D=>D.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&s){let D=g.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>f().element,onClose:r});if(D)return{element:D,update:()=>{},destroy:()=>{}}}return f();function f(){let D=m.classNames,k=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Js(k,D==null?void 0:D.panel);let H=[],S="",I="",N=null,O=[],L={},j=0,z=Ui(),oe=0,ke=0,Ke=!1,Ce=null,We=!1,Ne=0,be=new Set,Be=new Map,ue="",Q="",ne=null,pe,me,K,ae,He,Y=null,ee=null,ie=null;function Se(){let le=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Ae=y("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");Js(Ae,D==null?void 0:D.headerBar);let _e=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(_e.textContent="Events",pe=y("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"),pe.textContent="0",a){ee=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let or=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");or.textContent="Throughput",Y=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Y.textContent="-- tok/s",ie=y("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 Pn=ee,ln=ie,Fn=()=>{if(!ln.textContent)return;let vt=Pn.getBoundingClientRect(),qn=le.getBoundingClientRect();ln.style.left=`${vt.left-qn.left}px`,ln.style.top=`${vt.bottom-qn.top+4}px`,ln.style.display="block"},Tr=()=>{ln.style.display="none"};ee.addEventListener("mouseenter",Fn),ee.addEventListener("mouseleave",Tr),ee.appendChild(or),ee.appendChild(Y)}let Tt=y("div","persona-flex-1");me=y("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 sn=y("option","");sn.value="",sn.textContent="All events",me.appendChild(sn),K=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),K.type="button",K.title="Copy All";let Cn=ve("clipboard-copy","12px","currentColor",1.5);Cn&&K.appendChild(Cn);let Nt=y("span","persona-text-xs");Nt.textContent="Copy All",K.appendChild(Nt),Ae.appendChild(_e),Ae.appendChild(pe),ee&&Ae.appendChild(ee),Ae.appendChild(Tt),Ae.appendChild(me),Ae.appendChild(K);let at=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Js(at,D==null?void 0:D.searchBar);let Dt=ve("search","14px","var(--persona-muted, #9ca3af)",1.5),pt=y("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&&pt.appendChild(Dt),ae=y("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"),Js(ae,D==null?void 0:D.searchInput),ae.type="text",ae.placeholder="Search event payloads...",He=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),He.type="button",He.style.display="none";let Zt=ve("x","12px","currentColor",2);return Zt&&He.appendChild(Zt),at.appendChild(pt),at.appendChild(ae),at.appendChild(He),le.appendChild(Ae),le.appendChild(at),ie&&le.appendChild(ie),le}let tt,Qe=o.find(le=>le.renderEventStreamToolbar);if(Qe!=null&&Qe.renderEventStreamToolbar&&s){let le=Qe.renderEventStreamToolbar({config:s,defaultRenderer:()=>Se(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Ae=>{S=Ae,Wt(),U()},onSearchChange:Ae=>{I=Ae,Wt(),U()}});tt=le!=null?le:Se()}else tt=Se();let Oe=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Oe.style.display="none";function fe(){if(!a||!Y||!ee)return;let le=a();Y.textContent=hb(le);let Ae=yb(le);ie&&(ie.textContent=Ae,Ae||(ie.style.display="none")),Ae?ee.setAttribute("aria-label",Ae):ee.removeAttribute("aria-label")}let nt=y("div","persona-flex-1 persona-min-h-0 persona-relative"),te=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");te.style.height="100%";let ge=y("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");Js(ge,D==null?void 0:D.scrollIndicator),ge.style.display="none",ge.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Me=ve(c,"14px","currentColor",2);Me&&ge.appendChild(Me);let Ze=y("span","");Ze.textContent=p,ge.appendChild(Ze);let Je=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Je.style.display="none",nt.appendChild(te),nt.appendChild(Je),nt.appendChild(ge),k.setAttribute("tabindex","0"),k.appendChild(tt),k.appendChild(Oe),k.appendChild(nt);function Pe(){let le=t.getAll(),Ae={};for(let Nt of le)Ae[Nt.type]=(Ae[Nt.type]||0)+1;let _e=Object.keys(Ae).sort(),Tt=_e.length!==O.length||!_e.every((Nt,at)=>Nt===O[at]),sn=!Tt&&_e.some(Nt=>Ae[Nt]!==L[Nt]),an=le.length!==Object.values(L).reduce((Nt,at)=>Nt+at,0);if(!Tt&&!sn&&!an||(O=_e,L=Ae,!me))return;let Cn=me.value;if(me.options[0].textContent="All events",Tt){for(;me.options.length>1;)me.remove(1);for(let Nt of _e){let at=y("option","");at.value=Nt,at.textContent=`${Nt} (${Ae[Nt]||0})`,me.appendChild(at)}Cn&&_e.includes(Cn)?me.value=Cn:Cn&&(me.value="",S="")}else for(let Nt=1;Nt<me.options.length;Nt++){let at=me.options[Nt];at.textContent=`${at.value} (${Ae[at.value]||0})`}}function Ge(){let le=t.getAll();if(S&&(le=le.filter(Ae=>Ae.type===S)),I){let Ae=I.toLowerCase();le=le.filter(_e=>_e.type.toLowerCase().includes(Ae)||_e.payload.toLowerCase().includes(Ae))}return le}function wn(){return S!==""||I!==""}function Wt(){j=0,oe=0,z.resume(),ge.style.display="none"}function mn(le){be.has(le)?be.delete(le):be.add(le),ne=le;let Ae=te.scrollTop,_e=z.isFollowing();We=!0,z.pause(),U(),te.scrollTop=Ae,_e&&z.resume(),We=!1}function Ar(){return is(te,50)}function U(){ke=Date.now(),Ke=!1,fe(),Pe();let le=t.getEvictedCount();le>0?(Oe.textContent=`${le.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",H=Ge();let Ae=H.length,_e=t.getSize()>0;pe&&(pe.textContent=String(t.getSize())),Ae===0&&_e&&wn()?(Je.textContent=I?`No events matching '${I}'`:"No events matching filter",Je.style.display="",te.style.display="none"):(Je.style.display="none",te.style.display=""),K&&(K.title=wn()?`Copy Filtered (${Ae})`:"Copy All"),d&&!z.isFollowing()&&Ae>j&&(oe+=Ae-j,Ze.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",ge.style.display=""),j=Ae;let Tt=t.getAll(),sn=Tt.length>0?Tt[0].timestamp:0,an=new Set(H.map(at=>at.id));for(let at of be)an.has(at)||be.delete(at);let Cn=S!==ue||I!==Q,Nt=Be.size===0&&H.length>0;if(Cn||Nt||H.length===0){te.innerHTML="",Be.clear();let at=document.createDocumentFragment();for(let Dt=0;Dt<H.length;Dt++){let pt=xc(H[Dt],Dt,sn,m,be,mn,o,s);Be.set(H[Dt].id,pt),at.appendChild(pt)}te.appendChild(at),ue=S,Q=I,ne=null}else{if(ne!==null){let Dt=Be.get(ne);if(Dt&&Dt.parentNode===te){let pt=H.findIndex(Zt=>Zt.id===ne);if(pt>=0){let Zt=xc(H[pt],pt,sn,m,be,mn,o,s);te.insertBefore(Zt,Dt),Dt.remove(),Be.set(ne,Zt)}}ne=null}let at=new Set(H.map(Dt=>Dt.id));for(let[Dt,pt]of Be)at.has(Dt)||(pt.remove(),Be.delete(Dt));for(let Dt=0;Dt<H.length;Dt++){let pt=H[Dt];if(!Be.has(pt.id)){let Zt=xc(pt,Dt,sn,m,be,mn,o,s);Be.set(pt.id,Zt),te.appendChild(Zt)}}}z.isFollowing()&&(te.scrollTop=te.scrollHeight)}function G(){if(Date.now()-ke>=cb){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),U();return}Ke||(Ke=!0,Ce=requestAnimationFrame(()=>{Ce=null,U()}))}let ye=(le,Ae)=>{if(!K)return;K.innerHTML="";let _e=ve(le,"12px","currentColor",1.5);_e&&K.appendChild(_e);let Tt=y("span","persona-text-xs");Tt.textContent="Copy All",K.appendChild(Tt),setTimeout(()=>{K.innerHTML="";let sn=ve("clipboard-copy","12px","currentColor",1.5);sn&&K.appendChild(sn);let an=y("span","persona-text-xs");an.textContent="Copy All",K.appendChild(an),K.disabled=!1},Ae)},Xe=async()=>{if(K){K.disabled=!0;try{let le;wn()?le=H:n?(le=await n(),le.length===0&&(le=t.getAll())):le=t.getAll();let Ae=le.map(_e=>{try{return JSON.parse(_e.payload)}catch{return _e.payload}});await navigator.clipboard.writeText(JSON.stringify(Ae,null,2)),ye("check",1500)}catch{ye("x",1500)}}},rt=()=>{me&&(S=me.value,Wt(),U())},Ue=()=>{!ae||!He||(He.style.display=ae.value?"":"none",N&&clearTimeout(N),N=setTimeout(()=>{I=ae.value,Wt(),U()},150))},$e=()=>{!ae||!He||(ae.value="",I="",He.style.display="none",N&&clearTimeout(N),Wt(),U())},Pt=()=>{if(We)return;let le=te.scrollTop,{action:Ae,nextLastScrollTop:_e}=qi({following:z.isFollowing(),currentScrollTop:le,lastScrollTop:Ne,nearBottom:Ar(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ne=_e,Ae==="resume"?(z.resume(),oe=0,ge.style.display="none"):Ae==="pause"&&(z.pause(),d&&(Ze.textContent=p,ge.style.display=""))},Gt=le=>{let Ae=zi({following:z.isFollowing(),deltaY:le.deltaY,nearBottom:Ar(),resumeWhenNearBottom:!0});Ae==="pause"?(z.pause(),d&&(Ze.textContent=p,ge.style.display="")):Ae==="resume"&&(z.resume(),oe=0,ge.style.display="none")},Yt=()=>{d&&(te.scrollTop=te.scrollHeight,z.resume(),oe=0,ge.style.display="none")},Ln=le=>{let Ae=le.target;if(!Ae||Ae.closest("button"))return;let _e=Ae.closest("[data-event-id]");if(!_e)return;let Tt=_e.getAttribute("data-event-id");Tt&&mn(Tt)},V=le=>{if((le.metaKey||le.ctrlKey)&&le.key==="f"){le.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}le.key==="Escape"&&(ae&&document.activeElement===ae?($e(),ae.blur(),k.focus()):r&&r())};K&&K.addEventListener("click",Xe),me&&me.addEventListener("change",rt),ae&&ae.addEventListener("input",Ue),He&&He.addEventListener("click",$e),te.addEventListener("scroll",Pt),te.addEventListener("wheel",Gt,{passive:!0}),te.addEventListener("click",Ln),ge.addEventListener("click",Yt),k.addEventListener("keydown",V);function Ht(){N&&clearTimeout(N),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ke=!1,Be.clear(),K&&K.removeEventListener("click",Xe),me&&me.removeEventListener("change",rt),ae&&ae.removeEventListener("input",Ue),He&&He.removeEventListener("click",$e),te.removeEventListener("scroll",Pt),te.removeEventListener("wheel",Gt),te.removeEventListener("click",Ln),ge.removeEventListener("click",Yt),k.removeEventListener("keydown",V)}return{element:k,update:G,destroy:Ht}}}function Vg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(f)}else m.textContent=a;if(c.append(p,m),i.append(d,c),s==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Kg=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>Vg(e,t)});if(p)return p}return Vg(e,t)};var vc=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},so=new vc;so.register("PersonaArtifactCard",Kg);function xb(e){var s;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function Gg(e,t){var me,K,ae,He;let n=(K=(me=e.features)==null?void 0:me.artifacts)==null?void 0:K.layout,s=((ae=n==null?void 0:n.toolbarPreset)!=null?ae:"default")==="document",o=(He=n==null?void 0:n.panePadding)==null?void 0:He.trim(),a=e.markdown?Yo(e.markdown):null,i=Is(e.sanitize),d=Y=>{let ee=a?a(Y):Fr(Y);return i?i(ee):ee},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};c&&c.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let m=y("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");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let g=y("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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&g.classList.add("persona-artifact-toolbar-document");let f=y("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let x=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let v="rendered",A=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=s?Kt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Kt({icon:"eye",label:"Rendered view"}),B=s?Kt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Kt({icon:"code-2",label:"Source"}),D=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),k=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,H=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,S=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(H&&S&&S.length>0),N=null,O,L=null,j=null;if(s&&(k||H)&&!I){if(O=k?Fa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H){let Y=ve("chevron-down",14,"currentColor",2);Y&&O.appendChild(Y)}}else s&&I?(N=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),O=k?Fa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L=Kt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),N.append(O,L)):s?O=Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):O=Kt({icon:"copy",label:"Copy"});let z=s?Kt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"refresh-cw",label:"Refresh"}),oe=s?Kt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"x",label:"Close"}),ke=()=>{var tt,Qe,Oe;let Y=(tt=Be.find(fe=>fe.id===ue))!=null?tt:Be[Be.length-1],ee=(Qe=Y==null?void 0:Y.id)!=null?Qe:null,ie=(Y==null?void 0:Y.artifactType)==="markdown"&&(Oe=Y.markdown)!=null?Oe:"",Se=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:ie,jsonPayload:Se,id:ee}},Ke=async()=>{var tt;let{markdown:Y,jsonPayload:ee}=ke(),ie=(tt=Be.find(Qe=>Qe.id===ue))!=null?tt:Be[Be.length-1],Se=(ie==null?void 0:ie.artifactType)==="markdown"?Y:ie?ee:"";try{await navigator.clipboard.writeText(Se)}catch{}};if(O.addEventListener("click",async()=>{let Y=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Y&&I){let{markdown:ee,jsonPayload:ie,id:Se}=ke();try{await Y({actionId:"primary",artifactId:Se,markdown:ee,jsonPayload:ie})}catch{}return}await Ke()}),L&&(S!=null&&S.length)){let Y=()=>{var ie;return(ie=m.closest("[data-persona-root]"))!=null?ie:document.body},ee=()=>{j=Bo({items:S.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:Se,jsonPayload:tt,id:Qe}=ke(),Oe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Oe?await Oe({actionId:ie,artifactId:Qe,markdown:Se,jsonPayload:tt}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(Se):ie==="json"||ie==="source"?await navigator.clipboard.writeText(tt):await navigator.clipboard.writeText(Se||tt)}catch{}},anchor:N!=null?N:L,position:"bottom-right",portal:Y()})};m.isConnected?ee():requestAnimationFrame(ee),L.addEventListener("click",ie=>{ie.stopPropagation(),j==null||j.toggle()})}z.addEventListener("click",async()=>{var Y;try{await((Y=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Y.call(n))}catch{}ne()}),oe.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let Ce=()=>{s&&(M.setAttribute("aria-pressed",v==="rendered"?"true":"false"),B.setAttribute("aria-pressed",v==="source"?"true":"false"))};M.addEventListener("click",()=>{v="rendered",Ce(),ne()}),B.addEventListener("click",()=>{v="source",Ce(),ne()});let We=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(g.replaceChildren(),A.append(M,B),N?D.append(N,z,oe):D.append(O,z,oe),g.append(A,We,D),Ce()):(g.appendChild(f),g.appendChild(x)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let Ne=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),be=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Ne.style.paddingLeft=o,Ne.style.paddingRight=o,be.style.padding=o),m.appendChild(g),m.appendChild(Ne),m.appendChild(be);let Be=[],ue=null,Q=!1,ne=()=>{var Se,tt,Qe,Oe;let Y=s&&Be.length<=1;Ne.classList.toggle("persona-hidden",Y),Ne.replaceChildren();for(let fe of Be){let nt=y("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");nt.type="button",nt.textContent=fe.title||fe.id.slice(0,8),fe.id===ue&&nt.classList.add("persona-bg-persona-container","persona-border-persona-border"),nt.addEventListener("click",()=>t.onSelect(fe.id)),Ne.appendChild(nt)}be.replaceChildren();let ee=ue&&Be.find(fe=>fe.id===ue)||Be[Be.length-1];if(!ee)return;if(s){let fe=ee.artifactType==="markdown"?"MD":(Se=ee.component)!=null?Se:"Component",te=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";We.textContent=`${te} \xB7 ${fe}`}else f.textContent="Artifacts";if(ee.artifactType==="markdown"){if(s&&v==="source"){let nt=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");nt.textContent=(tt=ee.markdown)!=null?tt:"",be.appendChild(nt);return}let fe=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");fe.innerHTML=d((Qe=ee.markdown)!=null?Qe:""),be.appendChild(fe);return}let ie=ee.component?so.get(ee.component):void 0;if(ie){let nt={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let te=ie((Oe=ee.props)!=null?Oe:{},nt);if(te){be.appendChild(te);return}}catch{}}be.appendChild(xb(ee))},pe=()=>{var ee;let Y=Be.length>0;if(m.classList.toggle("persona-hidden",!Y),c){let ie=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,tt=((ee=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&tt&&Q?(c.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:c,update(Y){var ee,ie,Se;Be=Y.artifacts,ue=(Se=(ie=Y.selectedId)!=null?ie:(ee=Y.artifacts[Y.artifacts.length-1])==null?void 0:ee.id)!=null?Se:null,Be.length>0&&(Q=!0),ne(),pe()},setMobileOpen(Y){Q=Y,!Y&&c?(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):pe()}}}function gr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Jg(e,t){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!gr(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function vb(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 ll(e,t){var d,c,p,m,g,f,x,v,A,M;if(!gr(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"),vb(e),Jg(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(f=n==null?void 0:n.paneBackground)==null?void 0:f.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(A=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:A.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:M.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Jg(e,t)}var Qg=["panel","seamless"];function cl(e,t){var i,d,c,p,m,g;for(let f of Qg)e.classList.remove(`persona-artifact-appearance-${f}`);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"),!gr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",s=Qg.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Xg(e,t){var n,r,s;return!t||!gr(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function wb(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Cb(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 Sb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Ab(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function Yg(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function Zg(e,t,n,r,s,o){let a=wb(s,200),i=Ab(t,n,r,200);i=Math.max(a,i);let d=Cb(o);return d!==null&&(i=Math.min(i,d)),Sb(e,a,i)}var ef={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"}},wc=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,v,A;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(v=ef[a])!=null?v:ef.init;o.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let M=y("p","persona-text-sm persona-text-persona-muted");M.textContent=i.description,d.appendChild(M)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(M=>{var S,I;let B=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");B.htmlFor=`${t.id}-${a}-${M.name}`;let D=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=M.label,B.appendChild(D);let k=(S=M.type)!=null?S:"text",H;k==="textarea"?(H=document.createElement("textarea"),H.rows=3):(H=document.createElement("input"),H.type=k),H.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",H.id=`${t.id}-${a}-${M.name}`,H.name=M.name,H.placeholder=(I=M.placeholder)!=null?I:"",M.required&&(H.required=!0),B.appendChild(H),p.appendChild(B)});let m=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("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");f.type="submit",f.textContent=(A=i.submitLabel)!=null?A:"Submit",m.appendChild(g),m.appendChild(f),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async M=>{var H,S;M.preventDefault();let B=(H=n.formEndpoint)!=null?H:"/form",D=new FormData(p),k={};D.forEach((I,N)=>{k[N]=I}),k.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let I=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let N=await I.json();g.textContent=(S=N.message)!=null?S:"Thanks! We'll be in touch soon.",N.success&&N.nextPrompt&&await r.sendMessage(String(N.nextPrompt))}catch(I){g.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Cc=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},qa=new Cc;var tf=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Tb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Eb=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},za=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Tb(e),n=Eb(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Sc=e=>typeof e=="string"?e:e==null?"":String(e),ps={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Sc(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=Sc(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Sc(n.text)}}},nf=e=>Array.isArray(e)?e.map(t=>String(t)):[],Va=e=>{let t=new Set(nf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(nf(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},m=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Mb=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}},kb=e=>e.map(t=>({...t,streaming:!1})),Lb=e=>e.map(t=>({...t,status:"complete"})),dl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Mb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?kb(n.messages):void 0,artifacts:n.artifacts?Lb(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Qs=require("partial-json");function Pb(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Ib(e,t){if(!Pb(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function pl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=(0,Qs.parse)(n,Qs.STR|Qs.OBJ),o=Ib(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function rf(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ul(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=so.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function of(){let e=pl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function sf(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 ml(e){let t=sf(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function gl(e){let t=sf(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Rb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function fl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Rb}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,f.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,f.appendChild(v),g.appendChild(f);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-csat",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Satisfaction rating from 1 to 5");let M=[];for(let S=1;S<=5;S++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${c[S-1]}`),I.title=c[S-1],I.dataset.rating=String(S),I.innerHTML=`
28
+ `):""},Jy=(e,t)=>{var p,m,g,f,x;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=Gy(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?Bm(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(f=t==null?void 0:t.toolCall)!=null?f:{},c=a;return s==="tool-name"?c=((x=n.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(c=o),i&&d.activeTextTemplate?c=Vl(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Vl(n,d.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},Ng=(e,t,n)=>{var p;let r=Gs.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let m=s.toggleTextColor||s.headerTextColor||"currentColor",g=ve(r?"chevron-up":"chevron-down",16,m,2);g?c.appendChild(g):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},yc=(e,t)=>{var z,oe,ke,Ke,Ce,We,Ne,be,Be;let n=e.toolCall,r=(z=t==null?void 0:t.toolCall)!=null?z:{},s=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let o=(ke=(oe=t==null?void 0:t.features)==null?void 0:oe.toolCallDisplay)!=null?ke:{},a=o.expandable!==!1,i=a&&Gs.has(e.id),{summary:d,previewText:c,isActive:p}=Jy(e,t),m=y("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");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let x=String((Ke=n.startedAt)!=null?Ke:Date.now()),v=()=>{let ue=y("span","");return ue.setAttribute("data-tool-elapsed",x),ue.textContent=Ta(n),ue},A=(We=r.renderCollapsedSummary)==null?void 0:We.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(Ce=o.collapsedMode)!=null?Ce:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Ta(n),createElapsedElement:v});typeof A=="string"&&A.trim()?(f.textContent=A,g.appendChild(f)):A instanceof HTMLElement?g.appendChild(A):(f.textContent=d,g.appendChild(f));let M=(Ne=o.loadingAnimation)!=null?Ne:"none",B=r.activeTextTemplate,D=r.completeTextTemplate,k=p?B:D,H=A instanceof HTMLElement,S=(ue,Q,ne)=>{let pe=ne;for(let me of Q){let K=y("span","persona-tool-char");K.style.setProperty("--char-index",String(pe)),K.textContent=me===" "?"\xA0":me,ue.appendChild(K),pe++}return pe},I=(ue,Q)=>{var K;f.textContent="";let ne=((K=n.name)==null?void 0:K.trim())||"tool",pe=Si(ue,ne),me=0;for(let ae of pe){let He=ae.styles.length>0?(()=>{let Y=y("span",ae.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(Y),Y})():f;if(ae.isDuration&&p)He.appendChild(v());else{let Y=ae.isDuration?Ta(n):ae.text;Q?me=S(He,Y,me):He.appendChild(document.createTextNode(Y))}}};if(!H)if(p&&M!=="none"){let ue=(be=r.loadingAnimationDuration)!=null?be:2e3;if(f.setAttribute("data-preserve-animation","true"),M==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),k&&I(k,!1);else if(f.classList.add(`persona-tool-loading-${M}`),f.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),M==="shimmer-color"&&(r.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),k)I(k,!0);else{let Q=f.textContent||d;f.textContent="",S(f,Q,0)}}else k&&I(k,!1);let N=null;if(a){N=y("div","persona-flex persona-items-center");let ue=r.toggleTextColor||r.headerTextColor||"currentColor",Q=ve(i?"chevron-up":"chevron-down",16,ue,2);Q?N.appendChild(Q):N.textContent=i?"Hide":"Show";let ne=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ne.append(N),m.append(g,ne)}else m.append(g);let O=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","tool"),O.style.display="none",O.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let ue=(Be=r.renderCollapsedPreview)==null?void 0:Be.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});Ky(O,ue)||(O.textContent=c),O.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,O),s;let L=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(L.style.display=i?"":"none",r.contentBackgroundColor&&(L.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(L.style.color=r.contentTextColor),r.contentPaddingX&&(L.style.paddingLeft=r.contentPaddingX,L.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(L.style.paddingTop=r.contentPaddingY,L.style.paddingBottom=r.contentPaddingY),n.name){let ue=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ue.style.color=r.contentTextColor:r.headerTextColor&&(ue.style.color=r.headerTextColor),ue.textContent=n.name,L.appendChild(ue)}if(n.args!==void 0){let ue=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Arguments";let ne=y("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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ne.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ne.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ne.style.color=r.codeBlockTextColor),ne.textContent=Ds(n.args),ue.append(Q,ne),L.appendChild(ue)}if(n.chunks&&n.chunks.length){let ue=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Activity";let ne=y("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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ne.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ne.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ne.style.color=r.codeBlockTextColor),ne.textContent=n.chunks.join(""),ue.append(Q,ne),L.appendChild(ue)}if(n.status==="complete"&&n.result!==void 0){let ue=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Result";let ne=y("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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ne.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ne.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ne.style.color=r.codeBlockTextColor),ne.textContent=Ds(n.result),ue.append(Q,ne),L.appendChild(ue)}if(n.status==="complete"&&typeof n.duration=="number"){let ue=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ue.style.color=r.contentTextColor),ue.textContent=`Duration: ${n.duration}ms`,L.appendChild(ue)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),N){N.innerHTML="";let ue=r.toggleTextColor||r.headerTextColor||"currentColor",Q=ve(i?"chevron-up":"chevron-down",16,ue,2);Q?N.appendChild(Q):N.textContent=i?"Hide":"Show"}L.style.display=i?"":"none",O.style.display=i?"none":O.textContent||O.childNodes.length?"":"none"})(),s.append(m,O,L),s};var sl=new Map,Qy=e=>{let n=(e.startsWith(Zr)?e.slice(Zr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Og=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Fg=(e,t)=>{var r,s,o;let n=(s=(r=Og(t))==null?void 0:r.detailsDisplay)!=null?s:"collapsed";return(o=sl.get(e))!=null?o:n==="expanded"},_g=(e,t,n)=>{var a,i;let r=Og(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let o=e.querySelector("[data-approval-details-chevron]");if(o){o.innerHTML="";let d=ve(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&o.appendChild(d)}},$g=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let o=Fg(e,n);_g(r,o,n),s.style.display=o?"":"none"};var al=(e,t)=>{var I,N,O,L,j,z,oe,ke,Ke,Ce,We,Ne,be,Be,ue;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(I=r==null?void 0:r.backgroundColor)!=null?I:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(N=r==null?void 0:r.borderColor)!=null?N:"var(--persona-approval-border, #fef08a)",o.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(O=r==null?void 0:r.titleColor)!=null?O:"currentColor",p=ve(d,20,c,2);p&&i.appendChild(p);let m=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(f.style.color=r.titleColor),f.textContent=(L=r==null?void 0:r.title)!=null?L:"Approval Required",g.appendChild(f),!s){let Q=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");Q.setAttribute("data-approval-status",n.status),n.status==="approved"?(Q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",Q.style.color="var(--persona-palette-colors-success-700, #15803d)",Q.textContent="Approved"):n.status==="denied"?(Q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",Q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",Q.textContent="Denied"):n.status==="timeout"&&(Q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",Q.style.color="var(--persona-palette-colors-warning-700, #b45309)",Q.textContent="Timeout"),g.appendChild(Q)}m.appendChild(g);let v=n.toolType==="webmcp"||n.toolName.startsWith(Zr)?Bl(n.toolName):void 0,A=(j=r==null?void 0:r.formatDescription)==null?void 0:j.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),M=!n.toolName,B=A||(M?n.description:`The assistant wants to use \u201C${v!=null?v:Qy(n.toolName)}\u201D.`),D=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(D.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(D.style.color=r.descriptionColor),D.textContent=B,m.appendChild(D),n.reason){let Q=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");Q.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?Q.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor);let ne=y("span","persona-font-medium");ne.textContent=`${(z=r==null?void 0:r.reasonLabel)!=null?z:"Agent's stated reason:"} `,Q.appendChild(ne),Q.appendChild(document.createTextNode(n.reason)),m.appendChild(Q)}let k=(oe=r==null?void 0:r.detailsDisplay)!=null?oe:"collapsed",H=!!n.description&&!M,S=H||!!n.parameters;if(k!=="hidden"&&S){let Q=Fg(e.id,t),ne=y("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");ne.type="button",ne.setAttribute("data-expand-header","true"),ne.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ne.style.color=r.descriptionColor);let pe=y("span");pe.setAttribute("data-approval-details-label","true");let me=y("span","persona-inline-flex persona-items-center");me.setAttribute("data-approval-details-chevron","true"),ne.append(pe,me),_g(ne,Q,t),m.appendChild(ne);let K=y("div");if(K.setAttribute("data-approval-details","true"),K.style.display=Q?"":"none",H){let ae=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor),ae.textContent=n.description,K.appendChild(ae)}if(n.parameters){let ae=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(ae.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ae.style.color=r.parameterTextColor),ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",ae.textContent=Ds(n.parameters),K.appendChild(ae)}m.appendChild(K)}if(s){let Q=y("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let ne=y("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");ne.type="button",ne.style.backgroundColor=(ke=r==null?void 0:r.approveButtonColor)!=null?ke:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(Ke=r==null?void 0:r.approveButtonTextColor)!=null?Ke:"#ffffff",ne.setAttribute("data-approval-action","approve");let pe=ve("shield-check",14,(Ce=r==null?void 0:r.approveButtonTextColor)!=null?Ce:"#ffffff",2);pe&&(pe.style.marginRight="4px",ne.appendChild(pe));let me=document.createTextNode((We=r==null?void 0:r.approveLabel)!=null?We:"Approve");ne.appendChild(me);let K=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(Ne=r==null?void 0:r.denyButtonColor)!=null?Ne:"transparent",K.style.color=(be=r==null?void 0:r.denyButtonTextColor)!=null?be:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let ae=ve("shield-x",14,(Be=r==null?void 0:r.denyButtonTextColor)!=null?Be:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",K.appendChild(ae));let He=document.createTextNode((ue=r==null?void 0:r.denyLabel)!=null?ue:"Deny");K.appendChild(He),Q.append(ne,K),m.appendChild(Q)}return a.append(i,m),o.appendChild(a),o};var jg=e=>{let t=[],n=null;return{buttons:t,render:(s,o,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!s||!s.length||!p&&(i!=null?i:o?o.getMessages():[]).some(A=>A.role==="user"))return;let m=document.createDocumentFragment(),g=o?o.isStreaming():!1,f=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(s.forEach(x=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=x,v.disabled=g,d!=null&&d.fontFamily&&(v.style.fontFamily=f(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!o||o.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),o.sendMessage(x))}),m.appendChild(v),t.push(v)}),e.appendChild(m),p){let x=JSON.stringify(s);x!==n&&(n=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...s]},bubbles:!0,composed:!0})))}}}};var $a=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ja=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var Xy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Yy=new Set(["step_start","execution_start"]),Zy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),eb=new Set(["step_complete","agent_turn_complete"]),tb=new Set(["flow_complete","agent_complete"]),Ug=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),zg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ps=(e,t)=>{let n=e[t];return zg(n)?n:void 0};function bc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function il(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function nb(e,t){return typeof t.type=="string"?t.type:e}function rb(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 ob(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 qg(e){var r,s,o,a,i;let t=ps(e,"result"),n=[ps(e,"tokens"),ps(e,"totalTokens"),t?ps(t,"tokens"):void 0,ps(e,"usage"),t?ps(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(s=(r=rr(d.output))!=null?r:rr(d.outputTokens))!=null?s:rr(d.completionTokens);if(c!==void 0)return c}return(i=(o=rr(e.outputTokens))!=null?o:rr(e.completionTokens))!=null?i:t?(a=rr(t.outputTokens))!=null?a:rr(t.completionTokens):void 0}function sb(e){var n,r,s,o,a;let t=ps(e,"result");return(a=(s=(r=(n=rr(e.executionTime))!=null?n:rr(e.executionTimeMs))!=null?r:rr(e.execution_time))!=null?s:rr(e.duration))!=null?a:t?(o=rr(t.executionTime))!=null?o:rr(t.executionTimeMs):void 0}function ab(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ua=class{constructor(t=ab){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:il(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var o;if(!zg(n)){Ug.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=nb(t,n),s=this.now();if(Xy.has(r)){this.startRun(s);return}if(Yy.has(r)){this.run||this.startRun(s);return}if(Zy.has(r)){if(!ob(r,n))return;let a=rb(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+bc(i.visibleCharCount),c=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:il(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(eb.has(r)){if(!this.run)return;let a=this.run,i=qg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+bc(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:il(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(tb.has(r)){if(!this.run)return;let a=this.run,i=qg(n),d=i!=null?i:a.exactOutputTokens+bc(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:il(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(Ug.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=sb(n);return o!=null?o:r-t.startedAt}};function Js(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var ib={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)"}},lb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},cb=["flowName","stepName","reasoningText","text","name","tool","toolName"],db=100;function pb(e,t){let n={...ib,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return lb}function ub(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function mb(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function gb(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function fb(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function hb(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 yb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function bb(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 xb(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function xc(e,t,n,r,s,o,a,i){var g;let d=s.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Js(c,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(f)return c.appendChild(f),c}return c.appendChild(m()),c;function m(){var z,oe;let f=y("div",""),x=y("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 v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),A=ve(d?"chevron-down":"chevron-right","14px","currentColor",2);A&&v.appendChild(A);let M=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=(z=r.timestampFormat)!=null?z:"relative";M.textContent=B==="relative"?ub(e.timestamp,n):mb(e.timestamp);let D=null;r.showSequenceNumbers!==!1&&(D=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),D.textContent=String(t+1));let k=pb(e.type,r.badgeColors),H=y("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");H.style.backgroundColor=k.bg,H.style.color=k.text,H.style.borderColor=k.text+"50",H.textContent=e.type;let S=(oe=r.descriptionFields)!=null?oe:cb,I=gb(e.payload,S),N=null;I&&(N=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=I);let O=y("div","persona-flex-1 persona-min-w-0"),L=y("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"),j=ve("clipboard","12px","currentColor",1.5);return j&&L.appendChild(j),L.addEventListener("click",async ke=>{ke.stopPropagation(),await fb(hb(e)),L.innerHTML="";let Ke=ve("check","12px","currentColor",1.5);Ke&&L.appendChild(Ke),setTimeout(()=>{L.innerHTML="";let Ce=ve("clipboard","12px","currentColor",1.5);Ce&&L.appendChild(Ce)},1500)}),x.appendChild(v),x.appendChild(M),D&&x.appendChild(D),x.appendChild(H),N&&x.appendChild(N),x.appendChild(O),x.appendChild(L),f.appendChild(x),d&&f.appendChild(xb(e,a,i)),f}}function Vg(e){var x,v,A,M,B;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(x=s==null?void 0:s.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(A=i==null?void 0:i.label)!=null?A:"",m=(B=(M=s==null?void 0:s.features)==null?void 0:M.eventStream)!=null?B:{},g=o.find(D=>D.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&s){let D=g.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>f().element,onClose:r});if(D)return{element:D,update:()=>{},destroy:()=>{}}}return f();function f(){let D=m.classNames,k=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Js(k,D==null?void 0:D.panel);let H=[],S="",I="",N=null,O=[],L={},j=0,z=Ui(),oe=0,ke=0,Ke=!1,Ce=null,We=!1,Ne=0,be=new Set,Be=new Map,ue="",Q="",ne=null,pe,me,K,ae,He,Y=null,ee=null,ie=null;function Se(){let le=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Ae=y("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");Js(Ae,D==null?void 0:D.headerBar);let _e=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(_e.textContent="Events",pe=y("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"),pe.textContent="0",a){ee=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let or=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");or.textContent="Throughput",Y=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Y.textContent="-- tok/s",ie=y("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 Pn=ee,ln=ie,Fn=()=>{if(!ln.textContent)return;let vt=Pn.getBoundingClientRect(),qn=le.getBoundingClientRect();ln.style.left=`${vt.left-qn.left}px`,ln.style.top=`${vt.bottom-qn.top+4}px`,ln.style.display="block"},Er=()=>{ln.style.display="none"};ee.addEventListener("mouseenter",Fn),ee.addEventListener("mouseleave",Er),ee.appendChild(or),ee.appendChild(Y)}let Tt=y("div","persona-flex-1");me=y("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 sn=y("option","");sn.value="",sn.textContent="All events",me.appendChild(sn),K=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),K.type="button",K.title="Copy All";let Cn=ve("clipboard-copy","12px","currentColor",1.5);Cn&&K.appendChild(Cn);let Nt=y("span","persona-text-xs");Nt.textContent="Copy All",K.appendChild(Nt),Ae.appendChild(_e),Ae.appendChild(pe),ee&&Ae.appendChild(ee),Ae.appendChild(Tt),Ae.appendChild(me),Ae.appendChild(K);let at=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Js(at,D==null?void 0:D.searchBar);let Dt=ve("search","14px","var(--persona-muted, #9ca3af)",1.5),pt=y("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&&pt.appendChild(Dt),ae=y("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"),Js(ae,D==null?void 0:D.searchInput),ae.type="text",ae.placeholder="Search event payloads...",He=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),He.type="button",He.style.display="none";let Zt=ve("x","12px","currentColor",2);return Zt&&He.appendChild(Zt),at.appendChild(pt),at.appendChild(ae),at.appendChild(He),le.appendChild(Ae),le.appendChild(at),ie&&le.appendChild(ie),le}let tt,Qe=o.find(le=>le.renderEventStreamToolbar);if(Qe!=null&&Qe.renderEventStreamToolbar&&s){let le=Qe.renderEventStreamToolbar({config:s,defaultRenderer:()=>Se(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Ae=>{S=Ae,Wt(),U()},onSearchChange:Ae=>{I=Ae,Wt(),U()}});tt=le!=null?le:Se()}else tt=Se();let Oe=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Oe.style.display="none";function fe(){if(!a||!Y||!ee)return;let le=a();Y.textContent=yb(le);let Ae=bb(le);ie&&(ie.textContent=Ae,Ae||(ie.style.display="none")),Ae?ee.setAttribute("aria-label",Ae):ee.removeAttribute("aria-label")}let nt=y("div","persona-flex-1 persona-min-h-0 persona-relative"),te=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");te.style.height="100%";let ge=y("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");Js(ge,D==null?void 0:D.scrollIndicator),ge.style.display="none",ge.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Me=ve(c,"14px","currentColor",2);Me&&ge.appendChild(Me);let Ze=y("span","");Ze.textContent=p,ge.appendChild(Ze);let Je=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Je.style.display="none",nt.appendChild(te),nt.appendChild(Je),nt.appendChild(ge),k.setAttribute("tabindex","0"),k.appendChild(tt),k.appendChild(Oe),k.appendChild(nt);function Pe(){let le=t.getAll(),Ae={};for(let Nt of le)Ae[Nt.type]=(Ae[Nt.type]||0)+1;let _e=Object.keys(Ae).sort(),Tt=_e.length!==O.length||!_e.every((Nt,at)=>Nt===O[at]),sn=!Tt&&_e.some(Nt=>Ae[Nt]!==L[Nt]),an=le.length!==Object.values(L).reduce((Nt,at)=>Nt+at,0);if(!Tt&&!sn&&!an||(O=_e,L=Ae,!me))return;let Cn=me.value;if(me.options[0].textContent="All events",Tt){for(;me.options.length>1;)me.remove(1);for(let Nt of _e){let at=y("option","");at.value=Nt,at.textContent=`${Nt} (${Ae[Nt]||0})`,me.appendChild(at)}Cn&&_e.includes(Cn)?me.value=Cn:Cn&&(me.value="",S="")}else for(let Nt=1;Nt<me.options.length;Nt++){let at=me.options[Nt];at.textContent=`${at.value} (${Ae[at.value]||0})`}}function Ge(){let le=t.getAll();if(S&&(le=le.filter(Ae=>Ae.type===S)),I){let Ae=I.toLowerCase();le=le.filter(_e=>_e.type.toLowerCase().includes(Ae)||_e.payload.toLowerCase().includes(Ae))}return le}function wn(){return S!==""||I!==""}function Wt(){j=0,oe=0,z.resume(),ge.style.display="none"}function mn(le){be.has(le)?be.delete(le):be.add(le),ne=le;let Ae=te.scrollTop,_e=z.isFollowing();We=!0,z.pause(),U(),te.scrollTop=Ae,_e&&z.resume(),We=!1}function Tr(){return ls(te,50)}function U(){ke=Date.now(),Ke=!1,fe(),Pe();let le=t.getEvictedCount();le>0?(Oe.textContent=`${le.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",H=Ge();let Ae=H.length,_e=t.getSize()>0;pe&&(pe.textContent=String(t.getSize())),Ae===0&&_e&&wn()?(Je.textContent=I?`No events matching '${I}'`:"No events matching filter",Je.style.display="",te.style.display="none"):(Je.style.display="none",te.style.display=""),K&&(K.title=wn()?`Copy Filtered (${Ae})`:"Copy All"),d&&!z.isFollowing()&&Ae>j&&(oe+=Ae-j,Ze.textContent=p?`${p}${oe>0?` (${oe})`:""}`:"",ge.style.display=""),j=Ae;let Tt=t.getAll(),sn=Tt.length>0?Tt[0].timestamp:0,an=new Set(H.map(at=>at.id));for(let at of be)an.has(at)||be.delete(at);let Cn=S!==ue||I!==Q,Nt=Be.size===0&&H.length>0;if(Cn||Nt||H.length===0){te.innerHTML="",Be.clear();let at=document.createDocumentFragment();for(let Dt=0;Dt<H.length;Dt++){let pt=xc(H[Dt],Dt,sn,m,be,mn,o,s);Be.set(H[Dt].id,pt),at.appendChild(pt)}te.appendChild(at),ue=S,Q=I,ne=null}else{if(ne!==null){let Dt=Be.get(ne);if(Dt&&Dt.parentNode===te){let pt=H.findIndex(Zt=>Zt.id===ne);if(pt>=0){let Zt=xc(H[pt],pt,sn,m,be,mn,o,s);te.insertBefore(Zt,Dt),Dt.remove(),Be.set(ne,Zt)}}ne=null}let at=new Set(H.map(Dt=>Dt.id));for(let[Dt,pt]of Be)at.has(Dt)||(pt.remove(),Be.delete(Dt));for(let Dt=0;Dt<H.length;Dt++){let pt=H[Dt];if(!Be.has(pt.id)){let Zt=xc(pt,Dt,sn,m,be,mn,o,s);Be.set(pt.id,Zt),te.appendChild(Zt)}}}z.isFollowing()&&(te.scrollTop=te.scrollHeight)}function G(){if(Date.now()-ke>=db){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),U();return}Ke||(Ke=!0,Ce=requestAnimationFrame(()=>{Ce=null,U()}))}let ye=(le,Ae)=>{if(!K)return;K.innerHTML="";let _e=ve(le,"12px","currentColor",1.5);_e&&K.appendChild(_e);let Tt=y("span","persona-text-xs");Tt.textContent="Copy All",K.appendChild(Tt),setTimeout(()=>{K.innerHTML="";let sn=ve("clipboard-copy","12px","currentColor",1.5);sn&&K.appendChild(sn);let an=y("span","persona-text-xs");an.textContent="Copy All",K.appendChild(an),K.disabled=!1},Ae)},Xe=async()=>{if(K){K.disabled=!0;try{let le;wn()?le=H:n?(le=await n(),le.length===0&&(le=t.getAll())):le=t.getAll();let Ae=le.map(_e=>{try{return JSON.parse(_e.payload)}catch{return _e.payload}});await navigator.clipboard.writeText(JSON.stringify(Ae,null,2)),ye("check",1500)}catch{ye("x",1500)}}},rt=()=>{me&&(S=me.value,Wt(),U())},Ue=()=>{!ae||!He||(He.style.display=ae.value?"":"none",N&&clearTimeout(N),N=setTimeout(()=>{I=ae.value,Wt(),U()},150))},$e=()=>{!ae||!He||(ae.value="",I="",He.style.display="none",N&&clearTimeout(N),Wt(),U())},Pt=()=>{if(We)return;let le=te.scrollTop,{action:Ae,nextLastScrollTop:_e}=qi({following:z.isFollowing(),currentScrollTop:le,lastScrollTop:Ne,nearBottom:Tr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ne=_e,Ae==="resume"?(z.resume(),oe=0,ge.style.display="none"):Ae==="pause"&&(z.pause(),d&&(Ze.textContent=p,ge.style.display=""))},Gt=le=>{let Ae=zi({following:z.isFollowing(),deltaY:le.deltaY,nearBottom:Tr(),resumeWhenNearBottom:!0});Ae==="pause"?(z.pause(),d&&(Ze.textContent=p,ge.style.display="")):Ae==="resume"&&(z.resume(),oe=0,ge.style.display="none")},Yt=()=>{d&&(te.scrollTop=te.scrollHeight,z.resume(),oe=0,ge.style.display="none")},Ln=le=>{let Ae=le.target;if(!Ae||Ae.closest("button"))return;let _e=Ae.closest("[data-event-id]");if(!_e)return;let Tt=_e.getAttribute("data-event-id");Tt&&mn(Tt)},V=le=>{if((le.metaKey||le.ctrlKey)&&le.key==="f"){le.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}le.key==="Escape"&&(ae&&document.activeElement===ae?($e(),ae.blur(),k.focus()):r&&r())};K&&K.addEventListener("click",Xe),me&&me.addEventListener("change",rt),ae&&ae.addEventListener("input",Ue),He&&He.addEventListener("click",$e),te.addEventListener("scroll",Pt),te.addEventListener("wheel",Gt,{passive:!0}),te.addEventListener("click",Ln),ge.addEventListener("click",Yt),k.addEventListener("keydown",V);function Ht(){N&&clearTimeout(N),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),Ke=!1,Be.clear(),K&&K.removeEventListener("click",Xe),me&&me.removeEventListener("change",rt),ae&&ae.removeEventListener("input",Ue),He&&He.removeEventListener("click",$e),te.removeEventListener("scroll",Pt),te.removeEventListener("wheel",Gt),te.removeEventListener("click",Ln),ge.removeEventListener("click",Yt),k.removeEventListener("keydown",V)}return{element:k,update:G,destroy:Ht}}}function Kg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(f)}else m.textContent=a;if(c.append(p,m),i.append(d,c),s==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Gg=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>Kg(e,t)});if(p)return p}return Kg(e,t)};var vc=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},ao=new vc;ao.register("PersonaArtifactCard",Gg);function vb(e){var s;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function Jg(e,t){var me,K,ae,He;let n=(K=(me=e.features)==null?void 0:me.artifacts)==null?void 0:K.layout,s=((ae=n==null?void 0:n.toolbarPreset)!=null?ae:"default")==="document",o=(He=n==null?void 0:n.panePadding)==null?void 0:He.trim(),a=e.markdown?Zo(e.markdown):null,i=Is(e.sanitize),d=Y=>{let ee=a?a(Y):_r(Y);return i?i(ee):ee},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};c&&c.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let m=y("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");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let g=y("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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&g.classList.add("persona-artifact-toolbar-document");let f=y("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let x=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let v="rendered",A=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=s?Kt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Kt({icon:"eye",label:"Rendered view"}),B=s?Kt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Kt({icon:"code-2",label:"Source"}),D=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),k=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,H=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,S=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(H&&S&&S.length>0),N=null,O,L=null,j=null;if(s&&(k||H)&&!I){if(O=k?Fa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H){let Y=ve("chevron-down",14,"currentColor",2);Y&&O.appendChild(Y)}}else s&&I?(N=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),O=k?Fa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L=Kt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),N.append(O,L)):s?O=Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):O=Kt({icon:"copy",label:"Copy"});let z=s?Kt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"refresh-cw",label:"Refresh"}),oe=s?Kt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"x",label:"Close"}),ke=()=>{var tt,Qe,Oe;let Y=(tt=Be.find(fe=>fe.id===ue))!=null?tt:Be[Be.length-1],ee=(Qe=Y==null?void 0:Y.id)!=null?Qe:null,ie=(Y==null?void 0:Y.artifactType)==="markdown"&&(Oe=Y.markdown)!=null?Oe:"",Se=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:ie,jsonPayload:Se,id:ee}},Ke=async()=>{var tt;let{markdown:Y,jsonPayload:ee}=ke(),ie=(tt=Be.find(Qe=>Qe.id===ue))!=null?tt:Be[Be.length-1],Se=(ie==null?void 0:ie.artifactType)==="markdown"?Y:ie?ee:"";try{await navigator.clipboard.writeText(Se)}catch{}};if(O.addEventListener("click",async()=>{let Y=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Y&&I){let{markdown:ee,jsonPayload:ie,id:Se}=ke();try{await Y({actionId:"primary",artifactId:Se,markdown:ee,jsonPayload:ie})}catch{}return}await Ke()}),L&&(S!=null&&S.length)){let Y=()=>{var ie;return(ie=m.closest("[data-persona-root]"))!=null?ie:document.body},ee=()=>{j=Do({items:S.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:Se,jsonPayload:tt,id:Qe}=ke(),Oe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Oe?await Oe({actionId:ie,artifactId:Qe,markdown:Se,jsonPayload:tt}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(Se):ie==="json"||ie==="source"?await navigator.clipboard.writeText(tt):await navigator.clipboard.writeText(Se||tt)}catch{}},anchor:N!=null?N:L,position:"bottom-right",portal:Y()})};m.isConnected?ee():requestAnimationFrame(ee),L.addEventListener("click",ie=>{ie.stopPropagation(),j==null||j.toggle()})}z.addEventListener("click",async()=>{var Y;try{await((Y=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Y.call(n))}catch{}ne()}),oe.addEventListener("click",()=>{var Y;p(),(Y=t.onDismiss)==null||Y.call(t)});let Ce=()=>{s&&(M.setAttribute("aria-pressed",v==="rendered"?"true":"false"),B.setAttribute("aria-pressed",v==="source"?"true":"false"))};M.addEventListener("click",()=>{v="rendered",Ce(),ne()}),B.addEventListener("click",()=>{v="source",Ce(),ne()});let We=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(g.replaceChildren(),A.append(M,B),N?D.append(N,z,oe):D.append(O,z,oe),g.append(A,We,D),Ce()):(g.appendChild(f),g.appendChild(x)),o&&(g.style.paddingLeft=o,g.style.paddingRight=o);let Ne=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),be=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Ne.style.paddingLeft=o,Ne.style.paddingRight=o,be.style.padding=o),m.appendChild(g),m.appendChild(Ne),m.appendChild(be);let Be=[],ue=null,Q=!1,ne=()=>{var Se,tt,Qe,Oe;let Y=s&&Be.length<=1;Ne.classList.toggle("persona-hidden",Y),Ne.replaceChildren();for(let fe of Be){let nt=y("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");nt.type="button",nt.textContent=fe.title||fe.id.slice(0,8),fe.id===ue&&nt.classList.add("persona-bg-persona-container","persona-border-persona-border"),nt.addEventListener("click",()=>t.onSelect(fe.id)),Ne.appendChild(nt)}be.replaceChildren();let ee=ue&&Be.find(fe=>fe.id===ue)||Be[Be.length-1];if(!ee)return;if(s){let fe=ee.artifactType==="markdown"?"MD":(Se=ee.component)!=null?Se:"Component",te=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";We.textContent=`${te} \xB7 ${fe}`}else f.textContent="Artifacts";if(ee.artifactType==="markdown"){if(s&&v==="source"){let nt=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");nt.textContent=(tt=ee.markdown)!=null?tt:"",be.appendChild(nt);return}let fe=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");fe.innerHTML=d((Qe=ee.markdown)!=null?Qe:""),be.appendChild(fe);return}let ie=ee.component?ao.get(ee.component):void 0;if(ie){let nt={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let te=ie((Oe=ee.props)!=null?Oe:{},nt);if(te){be.appendChild(te);return}}catch{}}be.appendChild(vb(ee))},pe=()=>{var ee;let Y=Be.length>0;if(m.classList.toggle("persona-hidden",!Y),c){let ie=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,tt=((ee=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&tt&&Q?(c.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:c,update(Y){var ee,ie,Se;Be=Y.artifacts,ue=(Se=(ie=Y.selectedId)!=null?ie:(ee=Y.artifacts[Y.artifacts.length-1])==null?void 0:ee.id)!=null?Se:null,Be.length>0&&(Q=!0),ne(),pe()},setMobileOpen(Y){Q=Y,!Y&&c?(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):pe()}}}function fr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Qg(e,t){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!fr(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function wb(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 ll(e,t){var d,c,p,m,g,f,x,v,A,M;if(!fr(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),wb(e),Qg(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(f=n==null?void 0:n.paneBackground)==null?void 0:f.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(A=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:A.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:M.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Qg(e,t)}var Xg=["panel","seamless"];function cl(e,t){var i,d,c,p,m,g;for(let f of Xg)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!fr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",s=Xg.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||o;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Yg(e,t){var n,r,s;return!t||!fr(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Cb(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Sb(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 Ab(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Tb(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function Zg(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function ef(e,t,n,r,s,o){let a=Cb(s,200),i=Tb(t,n,r,200);i=Math.max(a,i);let d=Sb(o);return d!==null&&(i=Math.min(i,d)),Ab(e,a,i)}var tf={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"}},wc=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,v,A;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(v=tf[a])!=null?v:tf.init;o.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let M=y("p","persona-text-sm persona-text-persona-muted");M.textContent=i.description,d.appendChild(M)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(M=>{var S,I;let B=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");B.htmlFor=`${t.id}-${a}-${M.name}`;let D=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=M.label,B.appendChild(D);let k=(S=M.type)!=null?S:"text",H;k==="textarea"?(H=document.createElement("textarea"),H.rows=3):(H=document.createElement("input"),H.type=k),H.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",H.id=`${t.id}-${a}-${M.name}`,H.name=M.name,H.placeholder=(I=M.placeholder)!=null?I:"",M.required&&(H.required=!0),B.appendChild(H),p.appendChild(B)});let m=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("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");f.type="submit",f.textContent=(A=i.submitLabel)!=null?A:"Submit",m.appendChild(g),m.appendChild(f),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async M=>{var H,S;M.preventDefault();let B=(H=n.formEndpoint)!=null?H:"/form",D=new FormData(p),k={};D.forEach((I,N)=>{k[N]=I}),k.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let I=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let N=await I.json();g.textContent=(S=N.message)!=null?S:"Thanks! We'll be in touch soon.",N.success&&N.nextPrompt&&await r.sendMessage(String(N.nextPrompt))}catch(I){g.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Cc=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},qa=new Cc;var nf=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Eb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Mb=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},za=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Eb(e),n=Mb(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Sc=e=>typeof e=="string"?e:e==null?"":String(e),us={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Sc(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=Sc(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Sc(n.text)}}},rf=e=>Array.isArray(e)?e.map(t=>String(t)):[],Va=e=>{let t=new Set(rf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(rf(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},m=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var kb=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}},Lb=e=>e.map(t=>({...t,streaming:!1})),Pb=e=>e.map(t=>({...t,status:"complete"})),dl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?kb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?Lb(n.messages):void 0,artifacts:n.artifacts?Pb(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Qs=require("partial-json");function Ib(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Rb(e,t){if(!Ib(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function pl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=(0,Qs.parse)(n,Qs.STR|Qs.OBJ),o=Rb(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function of(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ul(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=ao.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function sf(){let e=pl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function af(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 ml(e){let t=af(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function gl(e){let t=af(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Wb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function fl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Wb}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,f.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,f.appendChild(v),g.appendChild(f);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-csat",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Satisfaction rating from 1 to 5");let M=[];for(let S=1;S<=5;S++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${c[S-1]}`),I.title=c[S-1],I.dataset.rating=String(S),I.innerHTML=`
29
29
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
30
30
  <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>
31
31
  </svg>
32
- `,I.addEventListener("click",()=>{m=S,M.forEach((N,O)=>{let L=O<S;N.classList.toggle("selected",L),N.setAttribute("aria-checked",O===S-1?"true":"false")})}),M.push(I),A.appendChild(I)}g.appendChild(A);let B=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=o,B.rows=3,B.setAttribute("aria-label","Additional comments"),S.appendChild(B),g.appendChild(S)}let D=document.createElement("div");D.className="persona-feedback-actions";let k=document.createElement("button");k.type="button",k.className="persona-feedback-btn persona-feedback-btn-skip",k.textContent=i,k.addEventListener("click",()=>{n==null||n(),p.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(m===null){A.classList.add("persona-feedback-shake"),setTimeout(()=>A.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let S=(B==null?void 0:B.value.trim())||void 0;await t(m,S),p.remove()}catch(S){H.disabled=!1,H.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),D.appendChild(k),D.appendChild(H),g.appendChild(D),p.appendChild(g),p}function hl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,x.appendChild(v);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,x.appendChild(A),f.appendChild(x);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-nps",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Likelihood rating from 0 to 10");let B=document.createElement("div");B.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=c;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=p,B.appendChild(D),B.appendChild(k);let H=document.createElement("div");H.className="persona-feedback-numbers";let S=[];for(let j=0;j<=10;j++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${j} out of 10`),z.textContent=String(j),z.dataset.rating=String(j),j<=6?z.classList.add("persona-feedback-detractor"):j<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{g=j,S.forEach((oe,ke)=>{oe.classList.toggle("selected",ke===j),oe.setAttribute("aria-checked",ke===j?"true":"false")})}),S.push(z),H.appendChild(z)}M.appendChild(B),M.appendChild(H),f.appendChild(M);let I=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=o,I.rows=3,I.setAttribute("aria-label","Additional comments"),j.appendChild(I),f.appendChild(j)}let N=document.createElement("div");N.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=i,O.addEventListener("click",()=>{n==null||n(),m.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(g===null){H.classList.add("persona-feedback-shake"),setTimeout(()=>H.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let j=(I==null?void 0:I.value.trim())||void 0;await t(g,j),m.remove()}catch(j){L.disabled=!1,L.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),N.appendChild(O),N.appendChild(L),f.appendChild(N),m.appendChild(f),m}var Xs="persona-chat-history",Wb=30*1e3,Hb={"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 Bb(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=Hb[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function yl(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 Db(e){var t,n,r,s,o,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Nb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ac=e=>!e||typeof e!="object"?{}:{...e},af=e=>e.map(t=>({...t,streaming:!1})),lf=(e,t,n)=>{let r=e!=null&&e.markdown?Yo(e.markdown):null,s=Is(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,p,m;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(m=i!=null?i:o.text)!=null?m:""}):r?d=r(a):d=Fr(a),s?s(d):d}};function cf(e){var i,d,c,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ve(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let m=y("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var bl=(e,t,n)=>{var ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Sd,Ad,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Qd,Xd,Yd,Zd,ep,tp;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=Ni(t),s=qa.getForInstance(r.plugins);r.components&&so.registerAll(r.components);let o=tf(),i=r.persistState===!1?null:(ad=r.storageAdapter)!=null?ad:dl(),d={},c=null,p=!1,m=l=>{if(r.onStateLoaded)try{let u=r.onStateLoaded(l);if(u&&typeof u=="object"&&"state"in u){let{state:h,open:b}=u;return b&&(p=!0),h}return u}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(u=>{let h=u!=null?u:{messages:[],metadata:{}};return m(h)});else{let u=l!=null?l:{messages:[],metadata:{}},h=m(u);h.metadata&&(d=Ac(h.metadata)),(id=h.messages)!=null&&id.length&&(r={...r,initialMessages:h.messages}),(ld=h.artifacts)!=null&&ld.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(cd=h.selectedArtifactId)!=null?cd:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=m({messages:[],metadata:{}});(dd=l.messages)!=null&&dd.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>d,f=l=>{var h;d=(h=l({...d}))!=null?h:{},vs()},x=r.actionParsers&&r.actionParsers.length?r.actionParsers:[za],v=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ps.message,ps.messageAndClick],A=Va({parsers:x,handlers:v,getSessionMetadata:g,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let M=(ud=(pd=r.launcher)==null?void 0:pd.enabled)!=null?ud:!0,B=(gd=(md=r.launcher)==null?void 0:md.autoExpand)!=null?gd:!1,D=(fd=r.autoFocusInput)!=null?fd:!1,k=B,H=M,S=(yd=(hd=r.layout)==null?void 0:hd.header)==null?void 0:yd.layout,I=!1,N=()=>Ho(r),O=()=>M||N(),L=N()?!1:M?B:!0,j=!1,z=null,oe=()=>{j=!0,z&&clearTimeout(z),z=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},ke=lf(r,A,oe),Ke=(xd=(bd=r.features)==null?void 0:bd.showReasoning)!=null?xd:!0,Ce=(wd=(vd=r.features)==null?void 0:vd.showToolCalls)!=null?wd:!0,We=(Sd=(Cd=r.features)==null?void 0:Cd.showEventStreamToggle)!=null?Sd:!1,Ne=(Td=(Ad=r.features)==null?void 0:Ad.scrollToBottom)!=null?Td:{},be=(Md=(Ed=r.features)==null?void 0:Ed.scrollBehavior)!=null?Md:{},ue=`${(Ld=typeof r.persistState=="object"?(kd=r.persistState)==null?void 0:kd.keyPrefix:void 0)!=null?Ld:"persona-"}event-stream`,Q=We?new ja(ue):null,ne=(Rd=(Id=(Pd=r.features)==null?void 0:Pd.eventStream)==null?void 0:Id.maxEvents)!=null?Rd:2e3,pe=We?new $a(ne,Q):null,me=We?new Ua:null,K=null,ae=!1,He=null,Y=0;Q==null||Q.open().then(()=>pe==null?void 0:pe.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ee={onCopy:l=>{var u,h;o.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(u=r.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;o.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(u=r.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},ie=(Wd=r.statusIndicator)!=null?Wd:{},Se=l=>{var u,h,b,T;return l==="idle"?(u=ie.idleText)!=null?u:Mn.idle:l==="connecting"?(h=ie.connectingText)!=null?h:Mn.connecting:l==="connected"?(b=ie.connectedText)!=null?b:Mn.connected:l==="error"?(T=ie.errorText)!=null?T:Mn.error:Mn[l]};function tt(l,u,h,b){if(b==="idle"&&h.idleLink){l.textContent="";let T=document.createElement("a");T.href=h.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=u,T.style.color="inherit",T.style.textDecoration="none",l.appendChild(T)}else l.textContent=u}let Qe=Ig({config:r,showClose:O()}),{wrapper:Oe,panel:fe,pillRoot:nt}=Qe.shell,te=Qe.panelElements,{container:ge,body:Me,messagesWrapper:Ze,suggestions:Je,textarea:Pe,sendButton:Ge,sendButtonWrapper:wn,composerForm:Wt,statusText:mn,introTitle:Ar,introSubtitle:U,closeButton:G,iconHolder:ye,headerTitle:Xe,headerSubtitle:rt,header:Ue,footer:$e,actionsRow:Pt,leftActions:Gt,rightActions:Yt}=te,Ln=te.setSendButtonMode,V=te.micButton,Ht=te.micButtonWrapper,le=te.attachmentButton,Ae=te.attachmentButtonWrapper,_e=te.attachmentInput,Tt=te.attachmentPreviewsContainer;ge.classList.add("persona-relative"),Me.classList.add("persona-relative");let sn=12,an=()=>{var l;return(l=Ne.label)!=null?l:""},Cn=()=>{var l;return(l=Ne.iconName)!=null?l:"arrow-down"},Nt=()=>Ne.enabled!==!1,at=()=>{var l;return(l=be.mode)!=null?l:"follow"},Dt=()=>{var l;return(l=be.anchorTopOffset)!=null?l:16},pt=y("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");pt.type="button",pt.style.display="none",pt.setAttribute("data-persona-scroll-to-bottom","true");let Zt=y("span","persona-flex persona-items-center"),or=y("span",""),Pn=y("span","");Pn.setAttribute("data-persona-scroll-to-bottom-count",""),Pn.style.display="none",pt.append(Zt,or,Pn),ge.appendChild(pt);let ln=y("div","persona-stream-anchor-spacer");ln.setAttribute("aria-hidden","true"),ln.setAttribute("data-persona-anchor-spacer",""),ln.style.flexShrink="0",ln.style.pointerEvents="none",ln.style.height="0px",Me.appendChild(ln);let Fn=()=>{let u=$e.style.display==="none"?0:$e.offsetHeight;pt.style.bottom=`${u+sn}px`};Fn();let Tr=()=>{let l=!!an();pt.setAttribute("aria-label",an()||"Jump to latest"),pt.title=an(),pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Zt.innerHTML="";let u=ve(Cn(),"14px","currentColor",2);u?(Zt.appendChild(u),Zt.style.display=""):Zt.style.display="none",or.textContent=an(),or.style.display=l?"":"none"};Tr();let vt=null,qn=null,Er=s.find(l=>l.renderHeader);if(Er!=null&&Er.renderHeader){let l=Er.renderHeader({config:r,defaultRenderer:()=>{let u=oo({config:r,showClose:O()});return ls(ge,u,r),u.header},onClose:()=>E(!1,"user")});if(l){let u=ge.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),Ue=l,Qe.header.element=l)}}let jr=()=>{var u,h,b,T;if(!pe)return;if(ae=!0,!K&&pe&&(K=zg({buffer:pe,getFullHistory:()=>pe.getAllFromStore(),onClose:()=>fr(),config:r,plugins:s,getThroughput:()=>{var W;return(W=me==null?void 0:me.getMetric())!=null?W:{status:"idle"}}})),K&&(Me.style.display="none",(u=$e.parentNode)==null||u.insertBefore(K.element,$e),K.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${On.actionIconColor}`;let W=(T=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;W&&W.split(/\s+/).forEach(q=>q&&bt.classList.add(q))}let l=()=>{if(!ae)return;let W=Date.now();W-Y>=200&&(K==null||K.update(),Y=W),He=requestAnimationFrame(l)};Y=0,He=requestAnimationFrame(l),jn(),o.emit("eventStream:opened",{timestamp:Date.now()})},fr=()=>{var l,u,h;if(ae){if(ae=!1,K&&K.element.remove(),Me.style.display="",bt){bt.style.boxShadow="";let b=(h=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&bt.classList.remove(T))}He!==null&&(cancelAnimationFrame(He),He=null),jn(),o.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(We){let l=(Bd=(Hd=r.features)==null?void 0:Hd.eventStream)==null?void 0:Bd.classNames,u="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:"");bt=y("button",u),bt.style.width="28px",bt.style.height="28px",bt.style.color=On.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let h=ve("activity","18px","currentColor",1.5);h&&bt.appendChild(h);let b=te.clearChatButtonWrapper,T=te.closeButtonWrapper,W=b||T;W&&W.parentNode===Ue?Ue.insertBefore(bt,W):Ue.appendChild(bt),bt.addEventListener("click",()=>{ae?fr():jr()})}let No=l=>{var T,W,q,F,R;let u=r.attachments;if(!(u!=null&&u.enabled))return;let h=(T=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?T:l.querySelector(".persona-attachment-previews");if(!h){h=y("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 ce=l.querySelector("[data-persona-composer-form]");ce!=null&&ce.parentNode?ce.parentNode.insertBefore(h,ce):l.insertBefore(h,l.firstChild)}if(!((W=l.querySelector("[data-persona-composer-attachment-input]"))!=null?W:l.querySelector('input[type="file"]'))){let ce=y("input");ce.type="file",ce.setAttribute("data-persona-composer-attachment-input",""),ce.accept=((q=u.allowedTypes)!=null?q:no).join(","),ce.multiple=((F=u.maxFiles)!=null?F:4)>1,ce.style.display="none",ce.setAttribute("aria-label",(R=u.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(ce)}},Mr=s.find(l=>l.renderComposer);if(Mr!=null&&Mr.renderComposer){let l=r.composer,u=Mr.renderComposer({config:r,defaultRenderer:()=>zs({config:r}).footer,onSubmit:h=>{var q;if(!_||_.isStreaming())return;let b=h.trim(),T=(q=vt==null?void 0:vt.hasAttachments())!=null?q:!1;if(!b&&!T)return;ot();let W;T&&(W=[],W.push(...vt.getContentParts()),b&&W.push(Ea(b))),_.sendMessage(b,{contentParts:W}),T&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{_e==null||_e.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Dd=r.voiceRecognition)==null?void 0:Dd.enabled)===!0?()=>{qn==null||qn()}:void 0});u&&(Qe.replaceComposer(u),$e=Qe.composer.footer)}let Oo=l=>{let u=(...de)=>{for(let Z of de){let we=l.querySelector(Z);if(we)return we}return null},h=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),T=l.querySelector("[data-persona-composer-submit]"),W=l.querySelector("[data-persona-composer-mic]"),q=l.querySelector("[data-persona-composer-status]");h&&(Wt=h),b&&(Pe=b),T&&(Ge=T),W&&(V=W,Ht=W.parentElement),q&&(mn=q);let F=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Je=F);let R=u("[data-persona-composer-attachment-button]",".persona-attachment-button");R&&(le=R,Ae=R.parentElement),_e=u("[data-persona-composer-attachment-input]",'input[type="file"]'),Tt=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ce=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ce&&(Pt=ce)};No($e),Oo($e);let _n=($d=(Nd=r.layout)==null?void 0:Nd.contentMaxWidth)!=null?$d:N()?(_d=(Fd=(Od=r.launcher)==null?void 0:Od.composerBar)==null?void 0:Fd.contentMaxWidth)!=null?_d:"720px":void 0;if(_n&&(Ze.style.maxWidth=_n,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%"),_n&&Wt&&!N()&&(Wt.style.maxWidth=_n,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),_n&&Je&&!N()&&(Je.style.maxWidth=_n,Je.style.marginLeft="auto",Je.style.marginRight="auto"),_n&&Tt&&!N()&&(Tt.style.maxWidth=_n,Tt.style.marginLeft="auto",Tt.style.marginRight="auto"),(jd=r.attachments)!=null&&jd.enabled&&_e&&Tt){vt=as.fromConfig(r.attachments),vt.setPreviewsContainer(Tt),_e.addEventListener("change",h=>{let b=h.target;vt==null||vt.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,u=cf(l);ge.appendChild(u)}(()=>{var b,T;let l=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},u=W=>{switch(W){case"body-top":return ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ze;case"footer-top":return Je;case"composer":return Wt;case"footer-bottom":return mn;default:return null}},h=(W,q)=>{var F;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")Ue.insertBefore(q,Ue.firstChild);else if(W==="header-right")Ue.appendChild(q);else{let R=Ue.querySelector(".persona-flex-col");R?(F=R.parentNode)==null||F.insertBefore(q,R.nextSibling):Ue.appendChild(q)}break;case"body-top":{let R=Me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(q):Me.insertBefore(q,Me.firstChild);break}case"body-bottom":Me.appendChild(q);break;case"footer-top":Je.replaceWith(q);break;case"footer-bottom":mn.replaceWith(q);break;default:break}};for(let[W,q]of Object.entries(l))if(q)try{let F=q({config:r,defaultContent:()=>u(W)});F&&h(W,F)}catch(F){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,F)}})();let io=l=>{var q,F;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let W=h.getAttribute("data-bubble-type");if(W==="reasoning")Ks.has(T)?Ks.delete(T):Ks.add(T),Bg(T,b);else if(W==="tool")Gs.has(T)?Gs.delete(T):Gs.add(T),Dg(T,b,r);else if(W==="approval"){let R=r.approval!==!1?r.approval:void 0,ce=((q=R==null?void 0:R.detailsDisplay)!=null?q:"collapsed")==="expanded",de=(F=sl.get(T))!=null?F:ce;sl.set(T,!de),_g(T,b,r)}Rr.delete(T)};Ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),io(l))}),Ze.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),io(l))});let Ur=new Map,lo=null,co="idle",Fo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},_o=(l,u)=>{let{icon:h,label:b}=Fo[u];l.setAttribute("aria-label",b),l.title=b,l.setAttribute("aria-pressed",u==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",u!=="idle"),l.classList.toggle("persona-message-action-loading",u==="loading");let T=ve(h,14,"currentColor",2);T&&(l.innerHTML="",l.appendChild(T))},po=()=>{Ze.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{var W;let h=u.closest("[data-actions-for]"),b=(W=h==null?void 0:h.getAttribute("data-actions-for"))!=null?W:null;_o(u,b&&b===lo?co:"idle")})};Ze.addEventListener("click",l=>{var q;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let W=h.getAttribute("data-action");if(W==="copy"){let R=_.getMessages().find(ce=>ce.id===T);if(R&&ee.onCopy){let ce=R.content||"";navigator.clipboard.writeText(ce).then(()=>{h.classList.add("persona-message-action-success");let de=ve("check",14,"currentColor",2);de&&(h.innerHTML="",h.appendChild(de)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=ve("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(de=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",de)}),ee.onCopy(R)}}else if(W==="read-aloud")_.toggleReadAloud(T);else if(W==="upvote"||W==="downvote"){let R=((q=Ur.get(T))!=null?q:null)===W,ce=W==="upvote"?"thumbs-up":"thumbs-down";if(R){Ur.delete(T),h.classList.remove("persona-message-action-active");let de=ve(ce,14,"currentColor",2);de&&(h.innerHTML="",h.appendChild(de))}else{let de=W==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${de}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ze=ve(de==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Z.innerHTML="",Z.appendChild(ze))}Ur.set(T,W),h.classList.add("persona-message-action-active");let we=ve(ce,14,"currentColor",2);we&&(we.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(we)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Te=_.getMessages().find(it=>it.id===T);Te&&ee.onFeedback&&ee.onFeedback({type:W,messageId:Te.id,message:Te})}}}),Ze.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let W=h.getAttribute("data-approval-action");if(!W)return;let q=W==="approve"?"approved":"denied",R=_.getMessages().find(de=>de.id===T);if(!(R!=null&&R.approval))return;let ce=b.querySelector("[data-approval-buttons]");ce&&ce.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),R.approval.toolType==="webmcp"?_.resolveWebMcpApproval(T,q):_.resolveApproval(R.approval,q)});let Ct=null,zn=null,Vn={artifacts:[],selectedId:null},In=!1,Et={current:null};Ze.addEventListener("click",l=>{var Z,we,Fe,Te,it;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Fe=(we=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Fe.call(we,{type:"download",artifactId:b}))===!0)return;let W=_.getArtifactById(b),q=W==null?void 0:W.markdown,F=(W==null?void 0:W.title)||"artifact";if(!q){let ze=h.closest("[data-open-artifact]"),ft=ze==null?void 0:ze.closest("[data-message-id]"),ct=ft==null?void 0:ft.getAttribute("data-message-id");if(ct){let Le=_.getMessages().find(Ve=>Ve.id===ct);if(Le!=null&&Le.rawContent)try{let Ve=JSON.parse(Le.rawContent);q=(Te=Ve==null?void 0:Ve.props)==null?void 0:Te.markdown,F=((it=Ve==null?void 0:Ve.props)==null?void 0:it.title)||F}catch{}}}if(!q)return;let R=new Blob([q],{type:"text/markdown"}),ce=URL.createObjectURL(R),de=document.createElement("a");de.href=ce,de.download=`${F}.md`,de.click(),URL.revokeObjectURL(ce)}),Ze.addEventListener("click",l=>{var W,q,F;let h=l.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((F=(q=(W=r.features)==null?void 0:W.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:F.call(q,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),In=!1,_.selectArtifact(b),Jn())}),Ze.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let sr=te.composerOverlay,ar=(l,u,h)=>{var F,R,ce,de;let b=u.trim();if(!b||!Et.current)return;let T=(F=l.getAttribute("data-tool-call-id"))!=null?F:"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:h.structured,values:(R=h.values)!=null?R:h.source==="multi"?b.split(", "):[b],isFreeText:W,source:h.source},bubbles:!0,composed:!0})),Mo(sr,T);let q=Et.current.getMessages().find(Z=>{var we;return((we=Z.toolCall)==null?void 0:we.id)===T});(ce=q==null?void 0:q.agentMetadata)!=null&&ce.awaitingLocalTool?Et.current.resolveAskUserQuestion(q,(de=h.structured)!=null?de:b):Et.current.sendMessage(b)},Kn=l=>{var T;let u=Et.current;if(!u)return;let h=(T=l.getAttribute("data-tool-call-id"))!=null?T:"",b=u.getMessages().find(W=>{var q;return((q=W.toolCall)==null?void 0:q.id)===h});b&&u.persistAskUserQuestionProgress(b,{answers:hi(l,b),currentIndex:mr(l)})},uo=l=>Object.entries(l).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),qr=l=>{var T,W,q;if(((W=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let u=mr(l),h=Hs(l);if(u>=h-1)return;let b=(q=Et.current)==null?void 0:q.getMessages().find(F=>{var R;return((R=F.toolCall)==null?void 0:R.id)===l.getAttribute("data-tool-call-id")});b&&(yi(l,b,r,u+1),Kn(l))};sr.addEventListener("click",l=>{var W,q,F,R,ce,de,Z,we,Fe,Te,it,ze,ft,ct;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),T==="dismiss"){let Ie=(W=b.getAttribute("data-tool-call-id"))!=null?W:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Mo(sr,Ie);let Le=(q=Et.current)==null?void 0:q.getMessages().find(Ve=>{var Ye;return((Ye=Ve.toolCall)==null?void 0:Ye.id)===Ie});(F=Le==null?void 0:Le.agentMetadata)!=null&&F.awaitingLocalTool&&((R=Et.current)==null||R.markAskUserQuestionResolved(Le),(ce=Et.current)==null||ce.resolveAskUserQuestion(Le,"(dismissed)"));return}if(T==="pick"){let Ie=h.getAttribute("data-option-label");if(!Ie)return;let Le=b.getAttribute("data-multi-select")==="true",Ve=Eo(b);if(Ve&&Le){let Ye=es(b)[mr(b)],xt=new Set(Array.isArray(Ye)?Ye:[]);xt.has(Ie)?xt.delete(Ie):xt.add(Ie),ko(b,Array.from(xt)),Kn(b);return}if(Ve){ko(b,Ie),Kn(b),qr(b);return}if(Le){let Ye=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ye?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ye);let xt=b.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=_l(b).length===0);return}ar(b,Ie,{source:"pick",values:[Ie]});return}if(T==="submit-multi"){let Ie=_l(b);if(Ie.length===0)return;ar(b,Ie.join(", "),{source:"multi",values:Ie});return}if(T==="open-free-text"){let Ie=b.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Le=Ie.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(T==="focus-free-text"){let Ie=b.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(T==="submit-free-text"){let Ie=b.querySelector('[data-ask-free-text-input="true"]'),Le=(de=Ie==null?void 0:Ie.value)!=null?de:"";if(!Le.trim())return;if(Eo(b)){ko(b,Le.trim()),Kn(b),qr(b);return}ar(b,Le,{source:"free-text"});return}if(T==="next"||T==="back"){if(!Et.current)return;let Ie=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",Le=Et.current.getMessages().find(De=>{var Re;return((Re=De.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let Ve=b.querySelector('[data-ask-free-text-input="true"]'),Ye=(Fe=(we=Ve==null?void 0:Ve.value)==null?void 0:we.trim())!=null?Fe:"";if(Ye){let De=es(b)[mr(b)];(typeof De!="string"||De!==Ye)&&ko(b,Ye)}let xt=T==="next"?1:-1,P=mr(b)+xt;yi(b,Le,r,P),Kn(b);return}if(T==="submit-all"){if(!Et.current)return;let Ie=(Te=b.getAttribute("data-tool-call-id"))!=null?Te:"",Le=Et.current.getMessages().find(De=>{var Re;return((Re=De.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let Ve=b.querySelector('[data-ask-free-text-input="true"]'),Ye=(ze=(it=Ve==null?void 0:Ve.value)==null?void 0:it.trim())!=null?ze:"";Ye&&ko(b,Ye);let xt=hi(b,Le);Et.current.persistAskUserQuestionProgress(Le,{answers:xt,currentIndex:mr(b)});let P=uo(xt);ar(b,P||"(submitted)",{source:"submit-all",structured:xt});return}if(T==="skip"){if(!Et.current)return;let Ie=(ft=b.getAttribute("data-tool-call-id"))!=null?ft:"",Le=Et.current.getMessages().find(Re=>{var he;return((he=Re.toolCall)==null?void 0:he.id)===Ie});if(!Le)return;let Ve=Eo(b),Ye=mr(b),xt=Hs(b),P=Ye>=xt-1;if(!Ve){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Mo(sr,Ie),(ct=Le.agentMetadata)!=null&&ct.awaitingLocalTool&&(Et.current.markAskUserQuestionResolved(Le),Et.current.resolveAskUserQuestion(Le,"(dismissed)"));return}ko(b,"");let De=b.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),P){let Re=hi(b,Le),he=uo(Re);ar(b,he||"(skipped)",{source:"submit-all",structured:Re});return}yi(b,Le,r,Ye+1),Kn(b);return}}),sr.addEventListener("keydown",l=>{var W;if(l.key!=="Enter")return;let h=l.target;if(!((W=h.matches)!=null&&W.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let T=h.value;if(T.trim()){if(Eo(b)){ko(b,T.trim()),Kn(b),qr(b);return}ar(b,T,{source:"free-text"})}});let mo=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let u=l.target;if((u==null?void 0:u.tagName)==="INPUT"||(u==null?void 0:u.tagName)==="TEXTAREA"||u!=null&&u.isContentEditable)return;let h=sr.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(l.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];W&&(l.preventDefault(),W.click())};document.addEventListener("keydown",mo);let Gn=null,Ot=null,Rn=null,ir=null,go=()=>{};function zr(){ir==null||ir(),ir=null}let fo=()=>{var q;if(!Gn||!Ot)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((q=e.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Ot.style.removeProperty("position"),Ot.style.removeProperty("left"),Ot.style.removeProperty("top"),Ot.style.removeProperty("bottom"),Ot.style.removeProperty("width"),Ot.style.removeProperty("z-index");return}let b=Gn.firstElementChild;if(!b||b===Ot)return;let T=10;Ot.style.position="absolute",Ot.style.top="0",Ot.style.bottom="0",Ot.style.width=`${T}px`,Ot.style.zIndex="5";let W=b.offsetWidth-T/2;Ot.style.left=`${Math.max(0,W)}px`},kr=()=>{},Jn=()=>{var h,b,T,W,q;if(!Ct||!gr(r))return;ll(e,r),cl(e,r),kr();let l=(W=(T=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?W:520,u=fe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),Ct.update(Vn),In?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),(q=Ct.backdrop)==null||q.classList.add("persona-hidden")):Vn.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),go()};if(gr(r)){fe.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ge),Ct=Gg(r,{onSelect:h=>{var b;return(b=Et.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{In=!0,Jn()}}),Ct.element.classList.add("persona-hidden"),Gn=u,u.appendChild(l),u.appendChild(Ct.element),Ct.backdrop&&fe.appendChild(Ct.backdrop),fe.appendChild(u),go=()=>{var b,T,W,q;if(!Gn||!Ct)return;if(!(((W=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:W.resizable)===!0)){Rn==null||Rn(),Rn=null,zr(),Ot&&(Ot.remove(),Ot=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Ot){let F=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");F.setAttribute("role","separator"),F.setAttribute("aria-orientation","vertical"),F.setAttribute("aria-label","Resize artifacts panel"),F.tabIndex=0;let R=e.ownerDocument,ce=(q=R.defaultView)!=null?q:window,de=Z=>{var ft,ct;if(!Ct||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||ce.innerWidth<=640)return;Z.preventDefault(),zr();let we=Z.clientX,Fe=Ct.element.getBoundingClientRect().width,Te=(ct=(ft=r.features)==null?void 0:ft.artifacts)==null?void 0:ct.layout,it=Ie=>{let Le=Gn.getBoundingClientRect().width,Ve=e.classList.contains("persona-artifact-appearance-seamless"),Ye=Ve?0:Yg(Gn,ce),xt=Ve?0:F.getBoundingClientRect().width||6,P=Fe-(Ie.clientX-we),De=Zg(P,Le,Ye,xt,Te==null?void 0:Te.resizableMinWidth,Te==null?void 0:Te.resizableMaxWidth);Ct.element.style.width=`${De}px`,Ct.element.style.maxWidth="none",fo()},ze=()=>{R.removeEventListener("pointermove",it),R.removeEventListener("pointerup",ze),R.removeEventListener("pointercancel",ze),ir=null;try{F.releasePointerCapture(Z.pointerId)}catch{}};ir=ze,R.addEventListener("pointermove",it),R.addEventListener("pointerup",ze),R.addEventListener("pointercancel",ze);try{F.setPointerCapture(Z.pointerId)}catch{}};F.addEventListener("pointerdown",de),Ot=F,Gn.insertBefore(F,Ct.element),Rn=()=>{F.removeEventListener("pointerdown",de)}}if(Ot){let F=Vn.artifacts.length>0&&!In;Ot.classList.toggle("persona-hidden",!F),fo()}},kr=()=>{var ce,de,Z,we,Fe,Te,it,ze,ft,ct,Ie,Le,Ve,Ye;if(!M||!Ct||((de=(ce=r.launcher)==null?void 0:ce.sidebarMode)!=null?de:!1)||un(r)&&nr(r).reveal==="emerge")return;let b=(Z=e.ownerDocument.defaultView)!=null?Z:window,T=(Fe=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Fe:!0,W=(it=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?it:640;if(T&&b.innerWidth<=W||!Xg(r,M))return;let q=(ct=(ft=(ze=r.launcher)==null?void 0:ze.width)!=null?ft:r.launcherWidth)!=null?ct:tr,F=(Ye=(Ve=(Le=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:Le.layout)==null?void 0:Ve.expandedPanelWidth)!=null?Ye:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!In?(fe.style.width=F,fe.style.maxWidth=F):(fe.style.width=q,fe.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(zn=new ResizeObserver(()=>{Jn()}),zn.observe(fe))}else fe.appendChild(ge),N()&&nt&&(te.peekBanner&&nt.appendChild(te.peekBanner),nt.appendChild($e));e.appendChild(Oe),nt&&e.appendChild(nt);let xe=()=>{var De,Re,he,$t,Ft,Jt,wt,zt,Yn,on,et,It,pn,ur,Zn,zo,Vo,Es,Ms,Qt,Ko,So,Ao,Xr,Go,xr,st,hn;if(N()){fe.style.width="100%",fe.style.maxWidth="100%";let Ut=(Re=(De=r.launcher)==null?void 0:De.composerBar)!=null?Re:{},jt=Oe.dataset.state==="expanded",ht=(he=Ut.expandedSize)!=null?he:"anchored";if(!(jt&&ht!=="fullscreen")){ge.style.background="",ge.style.border="",ge.style.borderRadius="",ge.style.overflow="",ge.style.boxShadow="";return}let At=(Ft=($t=r.theme)==null?void 0:$t.components)==null?void 0:Ft.panel,Tn=Us(r),Hn=(Dn,Jo)=>{var ma;return Dn==null||Dn===""?Jo:(ma=$s(Tn,Dn))!=null?ma:Dn},Or="1px solid var(--persona-border)",vn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Bn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ge.style.background="var(--persona-surface, #ffffff)",ge.style.border=Hn(At==null?void 0:At.border,Or),ge.style.borderRadius=Hn(At==null?void 0:At.borderRadius,Bn),ge.style.boxShadow=Hn(At==null?void 0:At.shadow,vn),ge.style.overflow="hidden";return}let l=un(r),u=(wt=(Jt=r.launcher)==null?void 0:Jt.sidebarMode)!=null?wt:!1,h=l||u||((Yn=(zt=r.launcher)==null?void 0:zt.fullHeight)!=null?Yn:!1),b=((on=r.launcher)==null?void 0:on.enabled)===!1,T=(It=(et=r.theme)==null?void 0:et.components)==null?void 0:It.panel,W=Us(r),q=(Ut,jt)=>{var ht;return Ut==null||Ut===""?jt:(ht=$s(W,Ut))!=null?ht:Ut},F=(pn=e.ownerDocument.defaultView)!=null?pn:window,R=(Zn=(ur=r.launcher)==null?void 0:ur.mobileFullscreen)!=null?Zn:!0,ce=(Vo=(zo=r.launcher)==null?void 0:zo.mobileBreakpoint)!=null?Vo:640,de=F.innerWidth<=ce,Z=R&&de&&M,we=(Ms=(Es=r.launcher)==null?void 0:Es.position)!=null?Ms:"bottom-left",Fe=we==="bottom-left"||we==="top-left",Te=(Ko=(Qt=r.launcher)==null?void 0:Qt.zIndex)!=null?Ko:kn,it=u||Z?"none":"1px solid var(--persona-border)",ze=Z?"none":u?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&(ze="none",it="none");let ft=u||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ct=q(T==null?void 0:T.border,it),Ie=q(T==null?void 0:T.shadow,ze),Le=q(T==null?void 0:T.borderRadius,ft),Ve=Me.scrollTop;e.style.cssText="",Oe.style.cssText="",fe.style.cssText="",ge.style.cssText="",Me.style.cssText="",$e.style.cssText="";let Ye=()=>{var jt;if(Ve<=0)return;((jt=Me.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(Me.scrollTop===Ve)return;let ht=Me.scrollHeight-Me.clientHeight;ht<=0||(Me.scrollTop=Math.min(Ve,ht))})};if(Z){Oe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Oe.style.cssText=`
32
+ `,I.addEventListener("click",()=>{m=S,M.forEach((N,O)=>{let L=O<S;N.classList.toggle("selected",L),N.setAttribute("aria-checked",O===S-1?"true":"false")})}),M.push(I),A.appendChild(I)}g.appendChild(A);let B=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=o,B.rows=3,B.setAttribute("aria-label","Additional comments"),S.appendChild(B),g.appendChild(S)}let D=document.createElement("div");D.className="persona-feedback-actions";let k=document.createElement("button");k.type="button",k.className="persona-feedback-btn persona-feedback-btn-skip",k.textContent=i,k.addEventListener("click",()=>{n==null||n(),p.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(m===null){A.classList.add("persona-feedback-shake"),setTimeout(()=>A.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let S=(B==null?void 0:B.value.trim())||void 0;await t(m,S),p.remove()}catch(S){H.disabled=!1,H.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),D.appendChild(k),D.appendChild(H),g.appendChild(D),p.appendChild(g),p}function hl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,x.appendChild(v);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,x.appendChild(A),f.appendChild(x);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-nps",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Likelihood rating from 0 to 10");let B=document.createElement("div");B.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=c;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=p,B.appendChild(D),B.appendChild(k);let H=document.createElement("div");H.className="persona-feedback-numbers";let S=[];for(let j=0;j<=10;j++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${j} out of 10`),z.textContent=String(j),z.dataset.rating=String(j),j<=6?z.classList.add("persona-feedback-detractor"):j<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{g=j,S.forEach((oe,ke)=>{oe.classList.toggle("selected",ke===j),oe.setAttribute("aria-checked",ke===j?"true":"false")})}),S.push(z),H.appendChild(z)}M.appendChild(B),M.appendChild(H),f.appendChild(M);let I=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=o,I.rows=3,I.setAttribute("aria-label","Additional comments"),j.appendChild(I),f.appendChild(j)}let N=document.createElement("div");N.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=i,O.addEventListener("click",()=>{n==null||n(),m.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(g===null){H.classList.add("persona-feedback-shake"),setTimeout(()=>H.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let j=(I==null?void 0:I.value.trim())||void 0;await t(g,j),m.remove()}catch(j){L.disabled=!1,L.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),N.appendChild(O),N.appendChild(L),f.appendChild(N),m.appendChild(f),m}var Xs="persona-chat-history",Hb=30*1e3,Bb={"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 Db(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=Bb[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function yl(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 Nb(e){var t,n,r,s,o,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Ob(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ac=e=>!e||typeof e!="object"?{}:{...e},lf=e=>e.map(t=>({...t,streaming:!1})),cf=(e,t,n)=>{let r=e!=null&&e.markdown?Zo(e.markdown):null,s=Is(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,p,m;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(m=i!=null?i:o.text)!=null?m:""}):r?d=r(a):d=_r(a),s?s(d):d}};function df(e){var i,d,c,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ve(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let m=y("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var bl=(e,t,n)=>{var ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Sd,Ad,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Qd,Xd,Yd,Zd,ep,tp;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=Ni(t),s=qa.getForInstance(r.plugins);r.components&&ao.registerAll(r.components);let o=nf(),i=r.persistState===!1?null:(ad=r.storageAdapter)!=null?ad:dl(),d={},c=null,p=!1,m=l=>{if(r.onStateLoaded)try{let u=r.onStateLoaded(l);if(u&&typeof u=="object"&&"state"in u){let{state:h,open:b}=u;return b&&(p=!0),h}return u}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(u=>{let h=u!=null?u:{messages:[],metadata:{}};return m(h)});else{let u=l!=null?l:{messages:[],metadata:{}},h=m(u);h.metadata&&(d=Ac(h.metadata)),(id=h.messages)!=null&&id.length&&(r={...r,initialMessages:h.messages}),(ld=h.artifacts)!=null&&ld.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(cd=h.selectedArtifactId)!=null?cd:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=m({messages:[],metadata:{}});(dd=l.messages)!=null&&dd.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>d,f=l=>{var h;d=(h=l({...d}))!=null?h:{},vs()},x=r.actionParsers&&r.actionParsers.length?r.actionParsers:[za],v=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[us.message,us.messageAndClick],A=Va({parsers:x,handlers:v,getSessionMetadata:g,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let M=(ud=(pd=r.launcher)==null?void 0:pd.enabled)!=null?ud:!0,B=(gd=(md=r.launcher)==null?void 0:md.autoExpand)!=null?gd:!1,D=(fd=r.autoFocusInput)!=null?fd:!1,k=B,H=M,S=(yd=(hd=r.layout)==null?void 0:hd.header)==null?void 0:yd.layout,I=!1,N=()=>Bo(r),O=()=>M||N(),L=N()?!1:M?B:!0,j=!1,z=null,oe=()=>{j=!0,z&&clearTimeout(z),z=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},ke=cf(r,A,oe),Ke=(xd=(bd=r.features)==null?void 0:bd.showReasoning)!=null?xd:!0,Ce=(wd=(vd=r.features)==null?void 0:vd.showToolCalls)!=null?wd:!0,We=(Sd=(Cd=r.features)==null?void 0:Cd.showEventStreamToggle)!=null?Sd:!1,Ne=(Td=(Ad=r.features)==null?void 0:Ad.scrollToBottom)!=null?Td:{},be=(Md=(Ed=r.features)==null?void 0:Ed.scrollBehavior)!=null?Md:{},ue=`${(Ld=typeof r.persistState=="object"?(kd=r.persistState)==null?void 0:kd.keyPrefix:void 0)!=null?Ld:"persona-"}event-stream`,Q=We?new ja(ue):null,ne=(Rd=(Id=(Pd=r.features)==null?void 0:Pd.eventStream)==null?void 0:Id.maxEvents)!=null?Rd:2e3,pe=We?new $a(ne,Q):null,me=We?new Ua:null,K=null,ae=!1,He=null,Y=0;Q==null||Q.open().then(()=>pe==null?void 0:pe.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ee={onCopy:l=>{var u,h;o.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(u=r.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;o.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(u=r.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},ie=(Wd=r.statusIndicator)!=null?Wd:{},Se=l=>{var u,h,b,T;return l==="idle"?(u=ie.idleText)!=null?u:Mn.idle:l==="connecting"?(h=ie.connectingText)!=null?h:Mn.connecting:l==="connected"?(b=ie.connectedText)!=null?b:Mn.connected:l==="error"?(T=ie.errorText)!=null?T:Mn.error:Mn[l]};function tt(l,u,h,b){if(b==="idle"&&h.idleLink){l.textContent="";let T=document.createElement("a");T.href=h.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=u,T.style.color="inherit",T.style.textDecoration="none",l.appendChild(T)}else l.textContent=u}let Qe=Rg({config:r,showClose:O()}),{wrapper:Oe,panel:fe,pillRoot:nt}=Qe.shell,te=Qe.panelElements,{container:ge,body:Me,messagesWrapper:Ze,suggestions:Je,textarea:Pe,sendButton:Ge,sendButtonWrapper:wn,composerForm:Wt,statusText:mn,introTitle:Tr,introSubtitle:U,closeButton:G,iconHolder:ye,headerTitle:Xe,headerSubtitle:rt,header:Ue,footer:$e,actionsRow:Pt,leftActions:Gt,rightActions:Yt}=te,Ln=te.setSendButtonMode,V=te.micButton,Ht=te.micButtonWrapper,le=te.attachmentButton,Ae=te.attachmentButtonWrapper,_e=te.attachmentInput,Tt=te.attachmentPreviewsContainer;ge.classList.add("persona-relative"),Me.classList.add("persona-relative");let sn=12,an=()=>{var l;return(l=Ne.label)!=null?l:""},Cn=()=>{var l;return(l=Ne.iconName)!=null?l:"arrow-down"},Nt=()=>Ne.enabled!==!1,at=()=>{var l;return(l=be.mode)!=null?l:"follow"},Dt=()=>{var l;return(l=be.anchorTopOffset)!=null?l:16},pt=y("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");pt.type="button",pt.style.display="none",pt.setAttribute("data-persona-scroll-to-bottom","true");let Zt=y("span","persona-flex persona-items-center"),or=y("span",""),Pn=y("span","");Pn.setAttribute("data-persona-scroll-to-bottom-count",""),Pn.style.display="none",pt.append(Zt,or,Pn),ge.appendChild(pt);let ln=y("div","persona-stream-anchor-spacer");ln.setAttribute("aria-hidden","true"),ln.setAttribute("data-persona-anchor-spacer",""),ln.style.flexShrink="0",ln.style.pointerEvents="none",ln.style.height="0px",Me.appendChild(ln);let Fn=()=>{let u=$e.style.display==="none"?0:$e.offsetHeight;pt.style.bottom=`${u+sn}px`};Fn();let Er=()=>{let l=!!an();pt.setAttribute("aria-label",an()||"Jump to latest"),pt.title=an(),pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Zt.innerHTML="";let u=ve(Cn(),"14px","currentColor",2);u?(Zt.appendChild(u),Zt.style.display=""):Zt.style.display="none",or.textContent=an(),or.style.display=l?"":"none"};Er();let vt=null,qn=null,Mr=s.find(l=>l.renderHeader);if(Mr!=null&&Mr.renderHeader){let l=Mr.renderHeader({config:r,defaultRenderer:()=>{let u=so({config:r,showClose:O()});return cs(ge,u,r),u.header},onClose:()=>E(!1,"user")});if(l){let u=ge.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),Ue=l,Qe.header.element=l)}}let Ur=()=>{var u,h,b,T;if(!pe)return;if(ae=!0,!K&&pe&&(K=Vg({buffer:pe,getFullHistory:()=>pe.getAllFromStore(),onClose:()=>hr(),config:r,plugins:s,getThroughput:()=>{var W;return(W=me==null?void 0:me.getMetric())!=null?W:{status:"idle"}}})),K&&(Me.style.display="none",(u=$e.parentNode)==null||u.insertBefore(K.element,$e),K.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${On.actionIconColor}`;let W=(T=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;W&&W.split(/\s+/).forEach(q=>q&&bt.classList.add(q))}let l=()=>{if(!ae)return;let W=Date.now();W-Y>=200&&(K==null||K.update(),Y=W),He=requestAnimationFrame(l)};Y=0,He=requestAnimationFrame(l),jn(),o.emit("eventStream:opened",{timestamp:Date.now()})},hr=()=>{var l,u,h;if(ae){if(ae=!1,K&&K.element.remove(),Me.style.display="",bt){bt.style.boxShadow="";let b=(h=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&bt.classList.remove(T))}He!==null&&(cancelAnimationFrame(He),He=null),jn(),o.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(We){let l=(Bd=(Hd=r.features)==null?void 0:Hd.eventStream)==null?void 0:Bd.classNames,u="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:"");bt=y("button",u),bt.style.width="28px",bt.style.height="28px",bt.style.color=On.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let h=ve("activity","18px","currentColor",1.5);h&&bt.appendChild(h);let b=te.clearChatButtonWrapper,T=te.closeButtonWrapper,W=b||T;W&&W.parentNode===Ue?Ue.insertBefore(bt,W):Ue.appendChild(bt),bt.addEventListener("click",()=>{ae?hr():Ur()})}let Oo=l=>{var T,W,q,F,R;let u=r.attachments;if(!(u!=null&&u.enabled))return;let h=(T=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?T:l.querySelector(".persona-attachment-previews");if(!h){h=y("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 ce=l.querySelector("[data-persona-composer-form]");ce!=null&&ce.parentNode?ce.parentNode.insertBefore(h,ce):l.insertBefore(h,l.firstChild)}if(!((W=l.querySelector("[data-persona-composer-attachment-input]"))!=null?W:l.querySelector('input[type="file"]'))){let ce=y("input");ce.type="file",ce.setAttribute("data-persona-composer-attachment-input",""),ce.accept=((q=u.allowedTypes)!=null?q:ro).join(","),ce.multiple=((F=u.maxFiles)!=null?F:4)>1,ce.style.display="none",ce.setAttribute("aria-label",(R=u.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(ce)}},kr=s.find(l=>l.renderComposer);if(kr!=null&&kr.renderComposer){let l=r.composer,u=kr.renderComposer({config:r,defaultRenderer:()=>zs({config:r}).footer,onSubmit:h=>{var q;if(!_||_.isStreaming())return;let b=h.trim(),T=(q=vt==null?void 0:vt.hasAttachments())!=null?q:!1;if(!b&&!T)return;ot();let W;T&&(W=[],W.push(...vt.getContentParts()),b&&W.push(Ea(b))),_.sendMessage(b,{contentParts:W}),T&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{_e==null||_e.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Dd=r.voiceRecognition)==null?void 0:Dd.enabled)===!0?()=>{qn==null||qn()}:void 0});u&&(Qe.replaceComposer(u),$e=Qe.composer.footer)}let Fo=l=>{let u=(...de)=>{for(let Z of de){let we=l.querySelector(Z);if(we)return we}return null},h=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),T=l.querySelector("[data-persona-composer-submit]"),W=l.querySelector("[data-persona-composer-mic]"),q=l.querySelector("[data-persona-composer-status]");h&&(Wt=h),b&&(Pe=b),T&&(Ge=T),W&&(V=W,Ht=W.parentElement),q&&(mn=q);let F=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Je=F);let R=u("[data-persona-composer-attachment-button]",".persona-attachment-button");R&&(le=R,Ae=R.parentElement),_e=u("[data-persona-composer-attachment-input]",'input[type="file"]'),Tt=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ce=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ce&&(Pt=ce)};Oo($e),Fo($e);let _n=($d=(Nd=r.layout)==null?void 0:Nd.contentMaxWidth)!=null?$d:N()?(_d=(Fd=(Od=r.launcher)==null?void 0:Od.composerBar)==null?void 0:Fd.contentMaxWidth)!=null?_d:"720px":void 0;if(_n&&(Ze.style.maxWidth=_n,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%"),_n&&Wt&&!N()&&(Wt.style.maxWidth=_n,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),_n&&Je&&!N()&&(Je.style.maxWidth=_n,Je.style.marginLeft="auto",Je.style.marginRight="auto"),_n&&Tt&&!N()&&(Tt.style.maxWidth=_n,Tt.style.marginLeft="auto",Tt.style.marginRight="auto"),(jd=r.attachments)!=null&&jd.enabled&&_e&&Tt){vt=is.fromConfig(r.attachments),vt.setPreviewsContainer(Tt),_e.addEventListener("change",h=>{let b=h.target;vt==null||vt.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,u=df(l);ge.appendChild(u)}(()=>{var b,T;let l=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},u=W=>{switch(W){case"body-top":return ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ze;case"footer-top":return Je;case"composer":return Wt;case"footer-bottom":return mn;default:return null}},h=(W,q)=>{var F;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")Ue.insertBefore(q,Ue.firstChild);else if(W==="header-right")Ue.appendChild(q);else{let R=Ue.querySelector(".persona-flex-col");R?(F=R.parentNode)==null||F.insertBefore(q,R.nextSibling):Ue.appendChild(q)}break;case"body-top":{let R=Me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(q):Me.insertBefore(q,Me.firstChild);break}case"body-bottom":Me.appendChild(q);break;case"footer-top":Je.replaceWith(q);break;case"footer-bottom":mn.replaceWith(q);break;default:break}};for(let[W,q]of Object.entries(l))if(q)try{let F=q({config:r,defaultContent:()=>u(W)});F&&h(W,F)}catch(F){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,F)}})();let lo=l=>{var q,F;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let W=h.getAttribute("data-bubble-type");if(W==="reasoning")Ks.has(T)?Ks.delete(T):Ks.add(T),Dg(T,b);else if(W==="tool")Gs.has(T)?Gs.delete(T):Gs.add(T),Ng(T,b,r);else if(W==="approval"){let R=r.approval!==!1?r.approval:void 0,ce=((q=R==null?void 0:R.detailsDisplay)!=null?q:"collapsed")==="expanded",de=(F=sl.get(T))!=null?F:ce;sl.set(T,!de),$g(T,b,r)}Wr.delete(T)};Ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),lo(l))}),Ze.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),lo(l))});let qr=new Map,co=null,po="idle",_o={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},$o=(l,u)=>{let{icon:h,label:b}=_o[u];l.setAttribute("aria-label",b),l.title=b,l.setAttribute("aria-pressed",u==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",u!=="idle"),l.classList.toggle("persona-message-action-loading",u==="loading");let T=ve(h,14,"currentColor",2);T&&(l.innerHTML="",l.appendChild(T))},uo=()=>{Ze.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{var W;let h=u.closest("[data-actions-for]"),b=(W=h==null?void 0:h.getAttribute("data-actions-for"))!=null?W:null;$o(u,b&&b===co?po:"idle")})};Ze.addEventListener("click",l=>{var q;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let W=h.getAttribute("data-action");if(W==="copy"){let R=_.getMessages().find(ce=>ce.id===T);if(R&&ee.onCopy){let ce=R.content||"";navigator.clipboard.writeText(ce).then(()=>{h.classList.add("persona-message-action-success");let de=ve("check",14,"currentColor",2);de&&(h.innerHTML="",h.appendChild(de)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=ve("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(de=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",de)}),ee.onCopy(R)}}else if(W==="read-aloud")_.toggleReadAloud(T);else if(W==="upvote"||W==="downvote"){let R=((q=qr.get(T))!=null?q:null)===W,ce=W==="upvote"?"thumbs-up":"thumbs-down";if(R){qr.delete(T),h.classList.remove("persona-message-action-active");let de=ve(ce,14,"currentColor",2);de&&(h.innerHTML="",h.appendChild(de))}else{let de=W==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${de}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ze=ve(de==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Z.innerHTML="",Z.appendChild(ze))}qr.set(T,W),h.classList.add("persona-message-action-active");let we=ve(ce,14,"currentColor",2);we&&(we.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(we)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Te=_.getMessages().find(it=>it.id===T);Te&&ee.onFeedback&&ee.onFeedback({type:W,messageId:Te.id,message:Te})}}}),Ze.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let W=h.getAttribute("data-approval-action");if(!W)return;let q=W==="approve"?"approved":"denied",R=_.getMessages().find(de=>de.id===T);if(!(R!=null&&R.approval))return;let ce=b.querySelector("[data-approval-buttons]");ce&&ce.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),R.approval.toolType==="webmcp"?_.resolveWebMcpApproval(T,q):_.resolveApproval(R.approval,q)});let Ct=null,zn=null,Vn={artifacts:[],selectedId:null},In=!1,Et={current:null};Ze.addEventListener("click",l=>{var Z,we,Fe,Te,it;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Fe=(we=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Fe.call(we,{type:"download",artifactId:b}))===!0)return;let W=_.getArtifactById(b),q=W==null?void 0:W.markdown,F=(W==null?void 0:W.title)||"artifact";if(!q){let ze=h.closest("[data-open-artifact]"),ft=ze==null?void 0:ze.closest("[data-message-id]"),ct=ft==null?void 0:ft.getAttribute("data-message-id");if(ct){let Le=_.getMessages().find(Ve=>Ve.id===ct);if(Le!=null&&Le.rawContent)try{let Ve=JSON.parse(Le.rawContent);q=(Te=Ve==null?void 0:Ve.props)==null?void 0:Te.markdown,F=((it=Ve==null?void 0:Ve.props)==null?void 0:it.title)||F}catch{}}}if(!q)return;let R=new Blob([q],{type:"text/markdown"}),ce=URL.createObjectURL(R),de=document.createElement("a");de.href=ce,de.download=`${F}.md`,de.click(),URL.revokeObjectURL(ce)}),Ze.addEventListener("click",l=>{var W,q,F;let h=l.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((F=(q=(W=r.features)==null?void 0:W.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:F.call(q,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),In=!1,_.selectArtifact(b),Jn())}),Ze.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let sr=te.composerOverlay,ar=(l,u,h)=>{var F,R,ce,de;let b=u.trim();if(!b||!Et.current)return;let T=(F=l.getAttribute("data-tool-call-id"))!=null?F:"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:h.structured,values:(R=h.values)!=null?R:h.source==="multi"?b.split(", "):[b],isFreeText:W,source:h.source},bubbles:!0,composed:!0})),ko(sr,T);let q=Et.current.getMessages().find(Z=>{var we;return((we=Z.toolCall)==null?void 0:we.id)===T});(ce=q==null?void 0:q.agentMetadata)!=null&&ce.awaitingLocalTool?Et.current.resolveAskUserQuestion(q,(de=h.structured)!=null?de:b):Et.current.sendMessage(b)},Kn=l=>{var T;let u=Et.current;if(!u)return;let h=(T=l.getAttribute("data-tool-call-id"))!=null?T:"",b=u.getMessages().find(W=>{var q;return((q=W.toolCall)==null?void 0:q.id)===h});b&&u.persistAskUserQuestionProgress(b,{answers:hi(l,b),currentIndex:mr(l)})},mo=l=>Object.entries(l).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),zr=l=>{var T,W,q;if(((W=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let u=mr(l),h=Hs(l);if(u>=h-1)return;let b=(q=Et.current)==null?void 0:q.getMessages().find(F=>{var R;return((R=F.toolCall)==null?void 0:R.id)===l.getAttribute("data-tool-call-id")});b&&(yi(l,b,r,u+1),Kn(l))};sr.addEventListener("click",l=>{var W,q,F,R,ce,de,Z,we,Fe,Te,it,ze,ft,ct;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),T==="dismiss"){let Ie=(W=b.getAttribute("data-tool-call-id"))!=null?W:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),ko(sr,Ie);let Le=(q=Et.current)==null?void 0:q.getMessages().find(Ve=>{var Ye;return((Ye=Ve.toolCall)==null?void 0:Ye.id)===Ie});(F=Le==null?void 0:Le.agentMetadata)!=null&&F.awaitingLocalTool&&((R=Et.current)==null||R.markAskUserQuestionResolved(Le),(ce=Et.current)==null||ce.resolveAskUserQuestion(Le,"(dismissed)"));return}if(T==="pick"){let Ie=h.getAttribute("data-option-label");if(!Ie)return;let Le=b.getAttribute("data-multi-select")==="true",Ve=Mo(b);if(Ve&&Le){let Ye=ts(b)[mr(b)],xt=new Set(Array.isArray(Ye)?Ye:[]);xt.has(Ie)?xt.delete(Ie):xt.add(Ie),Lo(b,Array.from(xt)),Kn(b);return}if(Ve){Lo(b,Ie),Kn(b),zr(b);return}if(Le){let Ye=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ye?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ye);let xt=b.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=_l(b).length===0);return}ar(b,Ie,{source:"pick",values:[Ie]});return}if(T==="submit-multi"){let Ie=_l(b);if(Ie.length===0)return;ar(b,Ie.join(", "),{source:"multi",values:Ie});return}if(T==="open-free-text"){let Ie=b.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Le=Ie.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(T==="focus-free-text"){let Ie=b.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(T==="submit-free-text"){let Ie=b.querySelector('[data-ask-free-text-input="true"]'),Le=(de=Ie==null?void 0:Ie.value)!=null?de:"";if(!Le.trim())return;if(Mo(b)){Lo(b,Le.trim()),Kn(b),zr(b);return}ar(b,Le,{source:"free-text"});return}if(T==="next"||T==="back"){if(!Et.current)return;let Ie=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",Le=Et.current.getMessages().find(De=>{var Re;return((Re=De.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let Ve=b.querySelector('[data-ask-free-text-input="true"]'),Ye=(Fe=(we=Ve==null?void 0:Ve.value)==null?void 0:we.trim())!=null?Fe:"";if(Ye){let De=ts(b)[mr(b)];(typeof De!="string"||De!==Ye)&&Lo(b,Ye)}let xt=T==="next"?1:-1,P=mr(b)+xt;yi(b,Le,r,P),Kn(b);return}if(T==="submit-all"){if(!Et.current)return;let Ie=(Te=b.getAttribute("data-tool-call-id"))!=null?Te:"",Le=Et.current.getMessages().find(De=>{var Re;return((Re=De.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let Ve=b.querySelector('[data-ask-free-text-input="true"]'),Ye=(ze=(it=Ve==null?void 0:Ve.value)==null?void 0:it.trim())!=null?ze:"";Ye&&Lo(b,Ye);let xt=hi(b,Le);Et.current.persistAskUserQuestionProgress(Le,{answers:xt,currentIndex:mr(b)});let P=mo(xt);ar(b,P||"(submitted)",{source:"submit-all",structured:xt});return}if(T==="skip"){if(!Et.current)return;let Ie=(ft=b.getAttribute("data-tool-call-id"))!=null?ft:"",Le=Et.current.getMessages().find(Re=>{var he;return((he=Re.toolCall)==null?void 0:he.id)===Ie});if(!Le)return;let Ve=Mo(b),Ye=mr(b),xt=Hs(b),P=Ye>=xt-1;if(!Ve){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),ko(sr,Ie),(ct=Le.agentMetadata)!=null&&ct.awaitingLocalTool&&(Et.current.markAskUserQuestionResolved(Le),Et.current.resolveAskUserQuestion(Le,"(dismissed)"));return}Lo(b,"");let De=b.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),P){let Re=hi(b,Le),he=mo(Re);ar(b,he||"(skipped)",{source:"submit-all",structured:Re});return}yi(b,Le,r,Ye+1),Kn(b);return}}),sr.addEventListener("keydown",l=>{var W;if(l.key!=="Enter")return;let h=l.target;if(!((W=h.matches)!=null&&W.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let T=h.value;if(T.trim()){if(Mo(b)){Lo(b,T.trim()),Kn(b),zr(b);return}ar(b,T,{source:"free-text"})}});let go=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let u=l.target;if((u==null?void 0:u.tagName)==="INPUT"||(u==null?void 0:u.tagName)==="TEXTAREA"||u!=null&&u.isContentEditable)return;let h=sr.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(l.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];W&&(l.preventDefault(),W.click())};document.addEventListener("keydown",go);let Gn=null,Ot=null,Rn=null,ir=null,fo=()=>{};function Vr(){ir==null||ir(),ir=null}let ho=()=>{var q;if(!Gn||!Ot)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((q=e.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Ot.style.removeProperty("position"),Ot.style.removeProperty("left"),Ot.style.removeProperty("top"),Ot.style.removeProperty("bottom"),Ot.style.removeProperty("width"),Ot.style.removeProperty("z-index");return}let b=Gn.firstElementChild;if(!b||b===Ot)return;let T=10;Ot.style.position="absolute",Ot.style.top="0",Ot.style.bottom="0",Ot.style.width=`${T}px`,Ot.style.zIndex="5";let W=b.offsetWidth-T/2;Ot.style.left=`${Math.max(0,W)}px`},Lr=()=>{},Jn=()=>{var h,b,T,W,q;if(!Ct||!fr(r))return;ll(e,r),cl(e,r),Lr();let l=(W=(T=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?W:520,u=fe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),Ct.update(Vn),In?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),(q=Ct.backdrop)==null||q.classList.add("persona-hidden")):Vn.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),fo()};if(fr(r)){fe.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ge),Ct=Jg(r,{onSelect:h=>{var b;return(b=Et.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{In=!0,Jn()}}),Ct.element.classList.add("persona-hidden"),Gn=u,u.appendChild(l),u.appendChild(Ct.element),Ct.backdrop&&fe.appendChild(Ct.backdrop),fe.appendChild(u),fo=()=>{var b,T,W,q;if(!Gn||!Ct)return;if(!(((W=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:W.resizable)===!0)){Rn==null||Rn(),Rn=null,Vr(),Ot&&(Ot.remove(),Ot=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Ot){let F=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");F.setAttribute("role","separator"),F.setAttribute("aria-orientation","vertical"),F.setAttribute("aria-label","Resize artifacts panel"),F.tabIndex=0;let R=e.ownerDocument,ce=(q=R.defaultView)!=null?q:window,de=Z=>{var ft,ct;if(!Ct||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||ce.innerWidth<=640)return;Z.preventDefault(),Vr();let we=Z.clientX,Fe=Ct.element.getBoundingClientRect().width,Te=(ct=(ft=r.features)==null?void 0:ft.artifacts)==null?void 0:ct.layout,it=Ie=>{let Le=Gn.getBoundingClientRect().width,Ve=e.classList.contains("persona-artifact-appearance-seamless"),Ye=Ve?0:Zg(Gn,ce),xt=Ve?0:F.getBoundingClientRect().width||6,P=Fe-(Ie.clientX-we),De=ef(P,Le,Ye,xt,Te==null?void 0:Te.resizableMinWidth,Te==null?void 0:Te.resizableMaxWidth);Ct.element.style.width=`${De}px`,Ct.element.style.maxWidth="none",ho()},ze=()=>{R.removeEventListener("pointermove",it),R.removeEventListener("pointerup",ze),R.removeEventListener("pointercancel",ze),ir=null;try{F.releasePointerCapture(Z.pointerId)}catch{}};ir=ze,R.addEventListener("pointermove",it),R.addEventListener("pointerup",ze),R.addEventListener("pointercancel",ze);try{F.setPointerCapture(Z.pointerId)}catch{}};F.addEventListener("pointerdown",de),Ot=F,Gn.insertBefore(F,Ct.element),Rn=()=>{F.removeEventListener("pointerdown",de)}}if(Ot){let F=Vn.artifacts.length>0&&!In;Ot.classList.toggle("persona-hidden",!F),ho()}},Lr=()=>{var ce,de,Z,we,Fe,Te,it,ze,ft,ct,Ie,Le,Ve,Ye;if(!M||!Ct||((de=(ce=r.launcher)==null?void 0:ce.sidebarMode)!=null?de:!1)||un(r)&&nr(r).reveal==="emerge")return;let b=(Z=e.ownerDocument.defaultView)!=null?Z:window,T=(Fe=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Fe:!0,W=(it=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?it:640;if(T&&b.innerWidth<=W||!Yg(r,M))return;let q=(ct=(ft=(ze=r.launcher)==null?void 0:ze.width)!=null?ft:r.launcherWidth)!=null?ct:tr,F=(Ye=(Ve=(Le=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:Le.layout)==null?void 0:Ve.expandedPanelWidth)!=null?Ye:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!In?(fe.style.width=F,fe.style.maxWidth=F):(fe.style.width=q,fe.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(zn=new ResizeObserver(()=>{Jn()}),zn.observe(fe))}else fe.appendChild(ge),N()&&nt&&(te.peekBanner&&nt.appendChild(te.peekBanner),nt.appendChild($e));e.appendChild(Oe),nt&&e.appendChild(nt);let xe=()=>{var De,Re,he,$t,Ft,Jt,wt,zt,Yn,on,et,It,pn,ur,Zn,Vo,Ko,Es,Ms,Qt,Go,Ao,To,Yr,Jo,vr,st,hn;if(N()){fe.style.width="100%",fe.style.maxWidth="100%";let Ut=(Re=(De=r.launcher)==null?void 0:De.composerBar)!=null?Re:{},jt=Oe.dataset.state==="expanded",ht=(he=Ut.expandedSize)!=null?he:"anchored";if(!(jt&&ht!=="fullscreen")){ge.style.background="",ge.style.border="",ge.style.borderRadius="",ge.style.overflow="",ge.style.boxShadow="";return}let At=(Ft=($t=r.theme)==null?void 0:$t.components)==null?void 0:Ft.panel,Tn=Us(r),Hn=(Dn,Qo)=>{var ma;return Dn==null||Dn===""?Qo:(ma=$s(Tn,Dn))!=null?ma:Dn},Fr="1px solid var(--persona-border)",vn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Bn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ge.style.background="var(--persona-surface, #ffffff)",ge.style.border=Hn(At==null?void 0:At.border,Fr),ge.style.borderRadius=Hn(At==null?void 0:At.borderRadius,Bn),ge.style.boxShadow=Hn(At==null?void 0:At.shadow,vn),ge.style.overflow="hidden";return}let l=un(r),u=(wt=(Jt=r.launcher)==null?void 0:Jt.sidebarMode)!=null?wt:!1,h=l||u||((Yn=(zt=r.launcher)==null?void 0:zt.fullHeight)!=null?Yn:!1),b=((on=r.launcher)==null?void 0:on.enabled)===!1,T=(It=(et=r.theme)==null?void 0:et.components)==null?void 0:It.panel,W=Us(r),q=(Ut,jt)=>{var ht;return Ut==null||Ut===""?jt:(ht=$s(W,Ut))!=null?ht:Ut},F=(pn=e.ownerDocument.defaultView)!=null?pn:window,R=(Zn=(ur=r.launcher)==null?void 0:ur.mobileFullscreen)!=null?Zn:!0,ce=(Ko=(Vo=r.launcher)==null?void 0:Vo.mobileBreakpoint)!=null?Ko:640,de=F.innerWidth<=ce,Z=R&&de&&M,we=(Ms=(Es=r.launcher)==null?void 0:Es.position)!=null?Ms:"bottom-left",Fe=we==="bottom-left"||we==="top-left",Te=(Go=(Qt=r.launcher)==null?void 0:Qt.zIndex)!=null?Go:kn,it=u||Z?"none":"1px solid var(--persona-border)",ze=Z?"none":u?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&(ze="none",it="none");let ft=u||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ct=q(T==null?void 0:T.border,it),Ie=q(T==null?void 0:T.shadow,ze),Le=q(T==null?void 0:T.borderRadius,ft),Ve=Me.scrollTop;e.style.cssText="",Oe.style.cssText="",fe.style.cssText="",ge.style.cssText="",Me.style.cssText="",$e.style.cssText="";let Ye=()=>{var jt;if(Ve<=0)return;((jt=Me.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(Me.scrollTop===Ve)return;let ht=Me.scrollHeight-Me.clientHeight;ht<=0||(Me.scrollTop=Math.min(Ve,ht))})};if(Z){Oe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Oe.style.cssText=`
33
33
  position: fixed !important;
34
34
  inset: 0 !important;
35
35
  width: 100% !important;
@@ -65,7 +65,7 @@ _Details: ${n.message}_`:r}var La=e=>({isError:!0,content:[{type:"text",text:e}]
65
65
  overflow: hidden !important;
66
66
  border-radius: 0 !important;
67
67
  border: none !important;
68
- `,Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",$e.style.flexShrink="0",I=!0,Ye();return}let xt=(Ao=(So=r==null?void 0:r.launcher)==null?void 0:So.width)!=null?Ao:r==null?void 0:r.launcherWidth,P=xt!=null?xt:tr;if(!u&&!l)b&&h?(fe.style.width="100%",fe.style.maxWidth="100%"):(fe.style.width=P,fe.style.maxWidth=P);else if(l)if(nr(r).reveal==="emerge"){let jt=nr(r).width;fe.style.width=jt,fe.style.maxWidth=jt}else fe.style.width="100%",fe.style.maxWidth="100%";if(kr(),fe.style.boxShadow=Ie,fe.style.borderRadius=Le,ge.style.border=ct,ge.style.borderRadius=Le,l&&!Z&&(T==null?void 0:T.border)===void 0&&(ge.style.border="none",nr(r).side==="right"?ge.style.borderLeft="1px solid var(--persona-border)":ge.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),Oe.style.display="flex",Oe.style.flexDirection="column",Oe.style.flex="1 1 0%",Oe.style.minHeight="0",Oe.style.maxHeight="100%",Oe.style.height="100%",b&&(Oe.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",fe.style.overflow="hidden",ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.overflow="hidden",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",$e.style.flexShrink="0"),Oe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!u&&!b&&!l&&((Xr=Sr[we])!=null?Xr:Sr["bottom-right"]).split(" ").forEach(jt=>Oe.classList.add(jt)),u){let Ut=(xr=(Go=r.launcher)==null?void 0:Go.sidebarWidth)!=null?xr:"420px";Oe.style.cssText=`
68
+ `,Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",$e.style.flexShrink="0",I=!0,Ye();return}let xt=(To=(Ao=r==null?void 0:r.launcher)==null?void 0:Ao.width)!=null?To:r==null?void 0:r.launcherWidth,P=xt!=null?xt:tr;if(!u&&!l)b&&h?(fe.style.width="100%",fe.style.maxWidth="100%"):(fe.style.width=P,fe.style.maxWidth=P);else if(l)if(nr(r).reveal==="emerge"){let jt=nr(r).width;fe.style.width=jt,fe.style.maxWidth=jt}else fe.style.width="100%",fe.style.maxWidth="100%";if(Lr(),fe.style.boxShadow=Ie,fe.style.borderRadius=Le,ge.style.border=ct,ge.style.borderRadius=Le,l&&!Z&&(T==null?void 0:T.border)===void 0&&(ge.style.border="none",nr(r).side==="right"?ge.style.borderLeft="1px solid var(--persona-border)":ge.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),Oe.style.display="flex",Oe.style.flexDirection="column",Oe.style.flex="1 1 0%",Oe.style.minHeight="0",Oe.style.maxHeight="100%",Oe.style.height="100%",b&&(Oe.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",fe.style.overflow="hidden",ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.overflow="hidden",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",$e.style.flexShrink="0"),Oe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!u&&!b&&!l&&((Yr=Ar[we])!=null?Yr:Ar["bottom-right"]).split(" ").forEach(jt=>Oe.classList.add(jt)),u){let Ut=(vr=(Jo=r.launcher)==null?void 0:Jo.sidebarWidth)!=null?vr:"420px";Oe.style.cssText=`
69
69
  position: fixed !important;
70
70
  top: 0 !important;
71
71
  bottom: 0 !important;
@@ -106,9 +106,9 @@ _Details: ${n.message}_`:r}var La=e=>({isError:!0,content:[{type:"text",text:e}]
106
106
  flex-shrink: 0 !important;
107
107
  border-top: none !important;
108
108
  padding: 8px 16px 12px 16px !important;
109
- `}if(!b&&!l){let Ut="max-height: -moz-available !important; max-height: stretch !important;",jt=u?"":"padding-top: 1.25em !important;",ht=u?"":`z-index: ${(hn=(st=r.launcher)==null?void 0:st.zIndex)!=null?hn:kn} !important;`;Oe.style.cssText+=Ut+jt+ht}Ye()};xe(),Io(e,r),ll(e,r),cl(e,r);let ut=[];ut.push(()=>{document.removeEventListener("keydown",mo)});let nn=null,gn=null;ut.push(()=>{nn==null||nn(),nn=null,gn==null||gn(),gn=null}),zn&&ut.push(()=>{zn==null||zn.disconnect(),zn=null}),ut.push(()=>{Rn==null||Rn(),Rn=null,zr(),Ot&&(Ot.remove(),Ot=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),We&&ut.push(()=>{He!==null&&(cancelAnimationFrame(He),He=null),K==null||K.destroy(),K=null,pe==null||pe.destroy(),pe=null,Q=null});let Lr=null,Ys=()=>{Lr&&(Lr(),Lr=null),r.colorScheme==="auto"&&(Lr=_i(()=>{Io(e,r)}))};Ys(),ut.push(()=>{Lr&&(Lr(),Lr=null)});let Vr=(Ud=r.features)==null?void 0:Ud.streamAnimation;if(Vr!=null&&Vr.type&&Vr.type!=="none"){let l=Ha(Vr.type,Vr.plugins);l&&(oc(l,e),ut.push(()=>Eg(e)))}let $o=$g(Je),Pr=null,_,gs=l=>{var b,T;if(!_)return;let u=l!=null?l:_.getMessages(),h=((T=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:T.enabled)!==!1?xi(u):null;h?$o.render(h,_,Pe,u,r.suggestionChipsConfig,{agentPushed:!0}):u.some(W=>W.role==="user")?$o.render([],_,Pe,u):$o.render(r.suggestionChips,_,Pe,u,r.suggestionChipsConfig)},Ir=!1,Rr=gg(),Kr=new Map,Wr=new Map,hr=new Map,fs=0,Ja=Ps()!==null,Qn=Ui(),Xn=0,yr=null,br=!1,jo=!1,Gr=0,An=null,Hr=null,hs=!1,Uo=!1,ys=null,Qa=4,bs=24,Xa=80,xs=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Zs=(zd=(qd=r.voiceRecognition)==null?void 0:qd.autoResume)!=null?zd:!1,lr=l=>{o.emit("voice:state",{active:yt.active,source:l,timestamp:Date.now()})},$n=()=>{f(l=>({...l,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Ya=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=Ac(d.voiceState),u=!!l.active,h=Number((T=l.timestamp)!=null?T:0);yt.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Wb&&setTimeout(()=>{var W,q;yt.active||(yt.manuallyDeactivated=!1,((q=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:q.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("restore"),_.isVoiceActive()&&As()}):li("restore"))},1e3)},Za=()=>_?af(_.getMessages()).filter(l=>!l.__skipPersist):[];function vs(l){if(!(i!=null&&i.save))return;let h={messages:l?af(l):_?Za():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let b=i.save(h);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Jr=null,ea=()=>Oe.querySelector("#persona-scroll-container")||Me,ho=()=>{Jr!==null&&(cancelAnimationFrame(Jr),Jr=null),br=!1},ta=()=>{yr!==null&&(cancelAnimationFrame(yr),yr=null),jo=!1,ho()},na=()=>{Gr>0?(Pn.textContent=String(Gr),Pn.style.display="",pt.setAttribute("aria-label",`${an()||"Jump to latest"} (${Gr} new)`)):(Pn.textContent="",Pn.style.display="none",pt.setAttribute("aria-label",an()||"Jump to latest"))},ra=()=>{Gr!==0&&(Gr=0,na())},oa=()=>at()==="follow"?!Qn.isFollowing():!is(Me,bs),jn=()=>{if(!Nt()||ae){pt.parentNode&&pt.remove(),pt.style.display="none";return}pt.parentNode!==ge&&ge.appendChild(pt),Fn();let u=ro(Me)>0&&oa();u||ra(),pt.style.display=u?"":"none"},ws=()=>{Qn.pause()&&(ta(),jn())},Br=()=>{Qn.resume(),ra(),jn()},Dr=(l=!1)=>{at()==="follow"&&Qn.isFollowing()&&(!l&&!Ir||(yr!==null&&(cancelAnimationFrame(yr),yr=null),jo=!0,yr=requestAnimationFrame(()=>{yr=null,jo=!1,Qn.isFollowing()&&ei(ea(),l?220:140)})))},sa=(l,u,h,b=()=>!0)=>{let T=l.scrollTop,W=u(),q=W-T;ho();let F=performance.now();br=!0;let R=de=>1-Math.pow(1-de,3),ce=de=>{if(!b()){ho();return}let Z=u();Z!==W&&(W=Z,q=W-T);let we=de-F,Fe=Math.min(we/h,1),Te=R(Fe),it=T+q*Te;l.scrollTop=it,Xn=l.scrollTop,Fe<1?Jr=requestAnimationFrame(ce):(l.scrollTop=W,Xn=l.scrollTop,Jr=null,br=!1)};Jr=requestAnimationFrame(ce)},ei=(l,u=500)=>{let h=ro(l)-l.scrollTop;if(Math.abs(h)<1){Xn=l.scrollTop;return}if(Math.abs(h)>=Xa){ho(),br=!0,l.scrollTop=ro(l),Xn=l.scrollTop,br=!1;return}sa(l,()=>ro(l),u,()=>Qn.isFollowing())},aa=()=>{let l=ea();br=!0,l.scrollTop=ro(l),Xn=l.scrollTop,br=!1,jn()},ia=l=>{ln.style.height=`${Math.max(0,Math.round(l))}px`,An&&(An.spacerHeight=Math.max(0,l))},qo=()=>{Hr!==null&&(cancelAnimationFrame(Hr),Hr=null),ho(),An=null,ln.style.height="0px"},ti=l=>{Hr!==null&&cancelAnimationFrame(Hr),Hr=requestAnimationFrame(()=>{var ce;Hr=null;let u=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Me.querySelector(`[data-message-id="${u}"]`);if(!h)return;let b=0,T=h;for(;T&&T!==Me;)b+=T.offsetTop,T=T.offsetParent;let W=(ce=An==null?void 0:An.spacerHeight)!=null?ce:0,q=Me.scrollHeight-W,{targetScrollTop:F,spacerHeight:R}=xg({anchorOffsetTop:b,topOffset:Dt(),viewportHeight:Me.clientHeight,contentHeight:q});An={initialSpacerHeight:R,contentHeightAtAnchor:q,spacerHeight:R},ia(R),sa(Me,()=>F,220)})},ni=()=>{if(at()==="follow"){if(!Qn.isFollowing()||is(Me,1))return;Dr(!Ir);return}if(An&&An.initialSpacerHeight>0){let l=Me.scrollHeight-An.spacerHeight,u=vg({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:l});u!==An.spacerHeight&&ia(u)}jn()},ri=l=>{let u=at();u==="follow"?(Br(),Dr(!0)):u==="anchor-top"&&ti(l)},oi=l=>{let u=new Map;l.forEach(h=>{let b=xs.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(o.emit("assistant:message",h),!Uo&&at()!=="anchor-top"&&oa()&&(Gr+=1,na(),jn())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&o.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&o.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):o.emit("approval:requested",{approval:h.approval,message:h}))}),xs.clear(),u.forEach((h,b)=>{xs.set(b,h)})},si=(l,u,h)=>{var ct,Ie,Le,Ve,Ye,xt;let b=document.createElement("div"),W=(()=>{var De;let P=s.find(Re=>Re.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),q=(P,De)=>De==null?!1:typeof De=="string"?(P.textContent=De,!0):(P.appendChild(De),!0),F=new Set,R=new Set,ce=s.some(P=>P.renderAskUserQuestion),de=[],Z=[],we=r.enableComponentStreaming!==!1,Fe=s.some(P=>P.renderApproval)&&r.approval!==!1,Te=[];if(u.forEach(P=>{var et,It,pn,ur,Zn,zo,Vo,Es,Ms,Qt,Ko,So,Ao,Xr,Go,xr;F.add(P.id);let De=ce&&Zr(P),Re=Fe&&P.variant==="approval"&&!!P.approval,he=!De&&P.role==="assistant"&&!P.variant&&we&&ml(P);if(!Re&&hr.has(P.id)){let st=l.querySelector(`#wrapper-${P.id}`);st==null||st.removeAttribute("data-preserve-runtime"),hr.delete(P.id)}if(!he&&Wr.has(P.id)){let st=l.querySelector(`#wrapper-${P.id}`);st==null||st.removeAttribute("data-preserve-runtime"),Wr.delete(P.id)}let $t=Zr(P)?`:${(et=P.agentMetadata)!=null&&et.askUserQuestionAnswered?"a":"u"}:${(It=P.agentMetadata)!=null&&It.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ft=mg(P,fs)+$t,Jt=De||Re||he?null:fg(Rr,P.id,Ft);if(Jt){b.appendChild(Jt.cloneNode(!0)),Zr(P)&&((pn=P.toolCall)!=null&&pn.id)&&((ur=P.agentMetadata)==null?void 0:ur.awaitingLocalTool)===!0&&!((Zn=P.agentMetadata)!=null&&Zn.askUserQuestionAnswered)&&(R.add(P.toolCall.id),Bs(P,r,te.composerOverlay));return}let wt=null,zt=s.find(st=>!!(P.variant==="reasoning"&&st.renderReasoning||P.variant==="tool"&&st.renderToolCall||!P.variant&&st.renderMessage)),Yn=(zo=r.layout)==null?void 0:zo.messages;if(Zr(P)&&((Vo=P.agentMetadata)==null?void 0:Vo.askUserQuestionAnswered)===!0){Kr.delete(P.id);let st=l.querySelector(`#wrapper-${P.id}`);st==null||st.removeAttribute("data-preserve-runtime");return}if(Ca(P)&&((Ms=(Es=r.features)==null?void 0:Es.suggestReplies)==null?void 0:Ms.enabled)!==!1)return;if(Zr(P)&&((Ko=(Qt=r.features)==null?void 0:Qt.askUserQuestion)==null?void 0:Ko.enabled)!==!1){let st=s.find(hn=>typeof hn.renderAskUserQuestion=="function");if(st&&Et.current){let hn=Kr.get(P.id),Ut=hn!==Ft,jt=null;if(Ut){let{payload:At,complete:Tn}=eo(P),Hn=P.id,Or=()=>{var vn;return(vn=Et.current)==null?void 0:vn.getMessages().find(Bn=>Bn.id===Hn)};jt=st.renderAskUserQuestion({message:P,payload:At,complete:Tn,resolve:vn=>{var Dn;let Bn=Or();Bn&&((Dn=Et.current)==null||Dn.resolveAskUserQuestion(Bn,vn))},dismiss:()=>{var Bn,Dn,Jo;let vn=Or();(Bn=vn==null?void 0:vn.agentMetadata)!=null&&Bn.awaitingLocalTool&&((Dn=Et.current)==null||Dn.markAskUserQuestionResolved(vn),(Jo=Et.current)==null||Jo.resolveAskUserQuestion(vn,"(dismissed)"))},config:r})}let ht=hn!=null;if(Ut&&jt===null&&!ht){((So=P.agentMetadata)==null?void 0:So.awaitingLocalTool)===!0&&!((Ao=P.agentMetadata)!=null&&Ao.askUserQuestionAnswered)&&(R.add(P.toolCall.id),Bs(P,r,te.composerOverlay));return}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${P.id}`,Xt.setAttribute("data-wrapper-id",P.id),Xt.setAttribute("data-ask-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),b.appendChild(Xt),de.push({messageId:P.id,fingerprint:Ft,bubble:jt});return}else{((Xr=P.agentMetadata)==null?void 0:Xr.awaitingLocalTool)===!0&&!((Go=P.agentMetadata)!=null&&Go.askUserQuestionAnswered)&&(R.add(P.toolCall.id),Bs(P,r,te.composerOverlay));return}}else if(Re){let st=s.find(ht=>typeof ht.renderApproval=="function"),Ut=hr.get(P.id)!==Ft,jt=null;if(Ut&&(st!=null&&st.renderApproval)){let ht=P.id,Xt=(At,Tn)=>{var Or,vn,Bn;let Hn=(Or=Et.current)==null?void 0:Or.getMessages().find(Dn=>Dn.id===ht);Hn!=null&&Hn.approval&&(Hn.approval.toolType==="webmcp"?(vn=Et.current)==null||vn.resolveWebMcpApproval(Hn.id,At):(Bn=Et.current)==null||Bn.resolveApproval(Hn.approval,At,Tn))};jt=st.renderApproval({message:P,defaultRenderer:()=>al(P,r),config:r,approve:At=>Xt("approved",At),deny:At=>Xt("denied",At)})}if(Ut&&jt===null){let ht=l.querySelector(`#wrapper-${P.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),hr.delete(P.id),wt=al(P,r)}else{let ht=document.createElement("div");ht.className="persona-flex",ht.id=`wrapper-${P.id}`,ht.setAttribute("data-wrapper-id",P.id),ht.setAttribute("data-approval-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),b.appendChild(ht),Te.push({messageId:P.id,fingerprint:Ft,bubble:jt});return}}else if(zt)if(P.variant==="reasoning"&&P.reasoning&&zt.renderReasoning){if(!Ke)return;wt=zt.renderReasoning({message:P,defaultRenderer:()=>hc(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&zt.renderToolCall){if(!Ce)return;wt=zt.renderToolCall({message:P,defaultRenderer:()=>yc(P,r),config:r})}else zt.renderMessage&&(wt=zt.renderMessage({message:P,defaultRenderer:()=>{let st=Vs(P,h,Yn,r.messageActions,ee,{loadingIndicatorRenderer:W,widgetConfig:r});return P.role!=="user"&&wc(st,P,r,_),st},config:r}));if(!wt&&he){let st=gl(P);if(st){let hn=Wr.get(P.id),Ut=hn!==Ft,jt=r.wrapComponentDirectiveInBubble!==!1,ht=null;if(Ut){let Xt=ul(st,{config:r,message:P,transform:h});if(Xt)if(jt){let At=document.createElement("div");if(At.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(" "),At.id=`bubble-${P.id}`,At.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let Tn=document.createElement("div");Tn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Tn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),At.appendChild(Tn)}At.appendChild(Xt),ht=At}else{let At=document.createElement("div");if(At.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",At.id=`bubble-${P.id}`,At.setAttribute("data-message-id",P.id),At.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let Tn=document.createElement("div");Tn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Tn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),At.appendChild(Tn)}At.appendChild(Xt),ht=At}}if(ht||hn!=null){let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${P.id}`,Xt.setAttribute("data-wrapper-id",P.id),Xt.setAttribute("data-component-directive-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),jt||Xt.classList.add("persona-w-full"),b.appendChild(Xt),Z.push({messageId:P.id,fingerprint:Ft,bubble:ht});return}}}if(!wt)if(P.variant==="reasoning"&&P.reasoning){if(!Ke)return;wt=hc(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!Ce)return;wt=yc(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;wt=al(P,r)}else{let st=(xr=r.layout)==null?void 0:xr.messages;st!=null&&st.renderUserMessage&&P.role==="user"?wt=st.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):st!=null&&st.renderAssistantMessage&&P.role==="assistant"?wt=st.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):wt=Vs(P,h,st,r.messageActions,ee,{loadingIndicatorRenderer:W,widgetConfig:r}),P.role!=="user"&&wt&&wc(wt,P,r,_)}let on=document.createElement("div");on.className="persona-flex",on.id=`wrapper-${P.id}`,on.setAttribute("data-wrapper-id",P.id),P.role==="user"&&on.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&on.classList.add("persona-w-full"),on.appendChild(wt),hg(Rr,P.id,Ft,on),b.appendChild(on)}),te.composerOverlay&&te.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let Re=De.getAttribute("data-persona-ask-sheet-for");Re&&!R.has(Re)&&Mo(te.composerOverlay,Re)}),(Ie=(ct=r.features)==null?void 0:ct.toolCallDisplay)!=null&&Ie.grouped){let P=[],De=[];u.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&Ce){De.push(Re);return}De.length>1&&P.push(De),De=[]}),De.length>1&&P.push(De),P.forEach((Re,he)=>{var et,It;let $t=Re.map(pn=>Array.from(b.children).find(ur=>ur instanceof HTMLElement&&ur.getAttribute("data-wrapper-id")===pn.id)).filter(pn=>!!pn);if($t.length<2)return;let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id=`wrapper-tool-group-${he}-${Re[0].id}`,Ft.setAttribute("data-wrapper-id",`tool-group-${he}-${Re[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Re.length} tools`,Yn=(It=(et=r.toolCall)==null?void 0:et.renderGroupedSummary)==null?void 0:It.call(et,{messages:Re,toolCalls:Re.map(pn=>pn.toolCall).filter(pn=>!!pn),defaultSummary:zt,config:r});q(wt,Yn)||(wt.textContent=zt);let on=document.createElement("div");on.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(wt,on),Ft.appendChild(Jt),$t[0].before(Ft),$t.forEach((pn,ur)=>{let Zn=document.createElement("div");Zn.className="persona-tool-group-item persona-relative",Zn.setAttribute("data-persona-tool-group-item","true"),ur<$t.length-1&&Zn.setAttribute("data-persona-tool-group-connector","true"),Zn.appendChild(pn),on.appendChild(Zn)})})}yg(Rr,F);let it=u.some(P=>P.role==="assistant"&&P.streaming),ze=u[u.length-1],ft=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(Ir&&u.some(P=>P.role==="user")&&!it&&!ft){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:cs},De=s.find(he=>he.renderLoadingIndicator),Re=null;if(De!=null&&De.renderLoadingIndicator&&(Re=De.renderLoadingIndicator(P)),Re===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(Re=r.loadingIndicator.render(P)),Re===null&&(Re=cs()),Re){let he=document.createElement("div"),$t=((Ve=r.loadingIndicator)==null?void 0:Ve.showBubble)!==!1;he.className=$t?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),he.setAttribute("data-typing-indicator","true"),he.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",he.appendChild(Re);let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id="wrapper-typing-indicator",Ft.setAttribute("data-wrapper-id","typing-indicator"),Ft.appendChild(he),b.appendChild(Ft)}}if(!Ir&&u.length>0){let P=u[u.length-1],De={config:r,lastMessage:P,messageCount:u.length},Re=s.find($t=>$t.renderIdleIndicator),he=null;if(Re!=null&&Re.renderIdleIndicator&&(he=Re.renderIdleIndicator(De)),he===null&&((Ye=r.loadingIndicator)!=null&&Ye.renderIdle)&&(he=r.loadingIndicator.renderIdle(De)),he){let $t=document.createElement("div"),Ft=((xt=r.loadingIndicator)==null?void 0:xt.showBubble)!==!1;$t.className=Ft?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),$t.setAttribute("data-idle-indicator","true"),$t.appendChild(he);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild($t),b.appendChild(Jt)}}if($i(l,b),de.length>0)for(let{messageId:P,fingerprint:De,bubble:Re}of de){let he=l.querySelector(`#wrapper-${P}`);he&&Re!==null&&(he.replaceChildren(Re),he.setAttribute("data-bubble-fp",De),Kr.set(P,De))}if(Kr.size>0)for(let P of Kr.keys())F.has(P)||Kr.delete(P);if(Z.length>0)for(let{messageId:P,fingerprint:De,bubble:Re}of Z){let he=l.querySelector(`#wrapper-${P}`);he&&Re!==null&&(he.replaceChildren(Re),he.setAttribute("data-bubble-fp",De),Wr.set(P,De))}if(Wr.size>0)for(let P of Wr.keys())F.has(P)||Wr.delete(P);if(Te.length>0)for(let{messageId:P,fingerprint:De,bubble:Re}of Te){let he=l.querySelector(`#wrapper-${P}`);he&&Re!==null&&(he.replaceChildren(Re),he.setAttribute("data-bubble-fp",De),hr.set(P,De))}if(hr.size>0)for(let P of hr.keys())F.has(P)||hr.delete(P)},yo=(l,u,h)=>{si(l,u,h),po()},bo=null,ai=()=>{var h;if(bo)return;let l=b=>{let T=b.composedPath();T.includes(Oe)||nt&&T.includes(nt)||E(!1,"user")};bo=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},la=()=>{var u;if(!bo)return;((u=e.ownerDocument)!=null?u:document).removeEventListener("pointerdown",bo,!0),bo=null};ut.push(()=>la());let xo=null,ii=()=>{var h;if(xo)return;let l=b=>{b.key==="Escape"&&(b.isComposing||E(!1,"user"))};xo=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},ca=()=>{var u;if(!xo)return;((u=e.ownerDocument)!=null?u:document).removeEventListener("keydown",xo,!0),xo=null};ut.push(()=>ca());let vo=!1,da=new Set,Cs=()=>{var u,h,b,T;let l=(b=(h=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return l||((T=r.features)==null?void 0:T.streamAnimation)},qe=()=>{var ft,ct,Ie,Le;if(!N())return;let l=te.peekBanner,u=te.peekTextNode;if(!l||!u)return;if(L){l.classList.remove("persona-pill-peek--visible");return}let h=(ft=_==null?void 0:_.getMessages())!=null?ft:[],b;for(let Ve=h.length-1;Ve>=0;Ve--){let Ye=h[Ve];if(Ye.role==="assistant"&&Ye.content){b=Ye;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let T=b.content,W=!!b.streaming,q=Cs(),F=Vi(q),R=F.type!=="none"?Ha(F.type,q==null?void 0:q.plugins):null,ce=((ct=R==null?void 0:R.isAnimating)==null?void 0:ct.call(R,b))===!0,de=R!==null&&(W||ce);de&&R&&!da.has(R.name)&&(oc(R,e),da.add(R.name));let Z=de&&(R!=null&&R.containerClass)?R.containerClass:null,we=(Ie=u.dataset.personaPeekStreamClass)!=null?Ie:null;we&&we!==Z&&(u.classList.remove(we),delete u.dataset.personaPeekStreamClass),Z&&we!==Z&&(u.classList.add(Z),u.dataset.personaPeekStreamClass=Z),de?(u.style.setProperty("--persona-stream-step",`${F.speed}ms`),u.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Fe=de?Ki(T,F.buffer,R,b,W):T;if(de&&F.placeholder==="skeleton"&&W&&(!Fe||!Fe.trim())){let Ve=document.createElement("div"),Ye=Da();Ye.classList.add("persona-pill-peek__skeleton"),Ve.appendChild(Ye),$i(u,Ve)}else{let Ve=Math.max(0,Fe.length-100),Ye=Fe.length>100?Fe.slice(-100):Fe,xt=Fr(Ye);if(!de||!R){let P=Fe.length>100?`\u2026${Ye}`:Ye;u.textContent!==P&&(u.textContent=P)}else{let P=xt;(R.wrap==="char"||R.wrap==="word")&&(P=Ba(xt,R.wrap,`peek-${b.id}`,{skipTags:R.skipTags,startIndex:Ve}));let De=document.createElement("div");if(De.innerHTML=P,R.useCaret&&Ye.length>0){let Re=Gi(),he=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),$t=he[he.length-1];$t!=null&&$t.parentNode?$t.parentNode.insertBefore(Re,$t.nextSibling):De.appendChild(Re)}$i(u,De),(Le=R.onAfterRender)==null||Le.call(R,{container:u,bubble:l,messageId:b.id,message:b,speed:F.speed,duration:F.duration})}}let ze=Ir||vo;l.classList.toggle("persona-pill-peek--visible",ze)};if(N()){let l=te.peekBanner;if(l){let b=T=>{T.preventDefault(),T.stopPropagation(),E(!0,"user")};l.addEventListener("pointerdown",b),ut.push(()=>{l.removeEventListener("pointerdown",b)})}let u=()=>{vo||(vo=!0,qe())},h=()=>{vo&&(vo=!1,qe())};fe.addEventListener("pointerenter",u),fe.addEventListener("pointerleave",h),ut.push(()=>{fe.removeEventListener("pointerenter",u),fe.removeEventListener("pointerleave",h)}),nt&&(nt.addEventListener("pointerenter",u),nt.addEventListener("pointerleave",h),ut.push(()=>{nt.removeEventListener("pointerenter",u),nt.removeEventListener("pointerleave",h)}))}let C=l=>{var we,Fe,Te,it,ze,ft,ct,Ie;let u=(Fe=(we=r.launcher)==null?void 0:we.composerBar)!=null?Fe:{},h=(Te=u.expandedSize)!=null?Te:"anchored",b=(it=u.bottomOffset)!=null?it:"16px",T=u.collapsedMaxWidth,W=(ze=u.expandedMaxWidth)!=null?ze:"880px",q=(ft=u.expandedTopOffset)!=null?ft:"5vh",F=(ct=u.modalMaxWidth)!=null?ct:"880px",R=(Ie=u.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",ce="calc(100vw - 32px)",de="var(--persona-pill-area-height, 80px)",Z=Oe.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",nt){let Le=nt.style;Le.bottom=b,Le.width=T!=null?T:""}if(l&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=F,Z.maxWidth=ce,Z.maxHeight=R,Z.height=R;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${b} + ${de})`,Z.top=q,Z.width=W,Z.maxWidth=ce}},$=()=>{var R,ce,de,Z,we,Fe,Te,it;if(!O())return;if(N()){let ft=(de=((ce=(R=r.launcher)==null?void 0:R.composerBar)!=null?ce:{}).expandedSize)!=null?de:"anchored",ct=L?"expanded":"collapsed";Oe.dataset.state=ct,Oe.dataset.expandedSize=ft,nt&&(nt.dataset.state=ct,nt.dataset.expandedSize=ft),Oe.style.removeProperty("display"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),C(L),ge.style.display=L?"flex":"none",xe(),L?(ai(),ii()):(la(),ca()),qe();return}let l=un(r),u=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Fe=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Fe:640,b=(it=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?it:!0,T=u.innerWidth<=h,W=b&&T&&M,q=nr(r).reveal;L?(Oe.style.removeProperty("display"),Oe.style.display=l?"flex":"",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0"),fe.classList.add("persona-scale-100","persona-opacity-100"),rn?rn.element.style.display="none":fn&&(fn.style.display="none")):(l?l&&(q==="overlay"||q==="push")&&!W?(Oe.style.removeProperty("display"),Oe.style.display="flex",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.setProperty("display","none","important"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.display="",Oe.classList.add("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100"),fe.classList.add("persona-scale-95","persona-opacity-0")),rn?rn.element.style.display=l?"none":"":fn&&(fn.style.display=l?"none":""))},E=(l,u="user")=>{var W,q;if(!O()||L===l)return;let h=L;L=l,$();let b=(()=>{var Te,it,ze,ft,ct,Ie,Le,Ve,Ye,xt;let F=(it=(Te=r.launcher)==null?void 0:Te.sidebarMode)!=null?it:!1,R=(ze=e.ownerDocument.defaultView)!=null?ze:window,ce=(ct=(ft=r.launcher)==null?void 0:ft.mobileFullscreen)!=null?ct:!0,de=(Le=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Le:640,Z=R.innerWidth<=de,we=un(r)&&ce&&Z,Fe=N()&&((xt=(Ye=(Ve=r.launcher)==null?void 0:Ve.composerBar)==null?void 0:Ye.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return F||ce&&Z&&M||we||Fe})();if(L&&b){if(!nn){let F=e.getRootNode(),R=F instanceof ShadowRoot?F.host:e.closest(".persona-host");R&&(nn=sc(R,(q=(W=r.launcher)==null?void 0:W.zIndex)!=null?q:kn))}gn||(gn=ac(e.ownerDocument))}else L||(nn==null||nn(),nn=null,gn==null||gn(),gn=null);L&&(pa(),at()==="follow"?Dr(!0):aa());let T={open:L,source:u,timestamp:Date.now()};L&&!h?o.emit("widget:opened",T):!L&&h&&o.emit("widget:closed",T),o.emit("widget:state",{open:L,launcherEnabled:M,voiceActive:yt.active,streaming:_.isStreaming()})},X=l=>{Ln(l?"stop":"send"),V&&(V.disabled=l),$o.buttons.forEach(u=>{u.disabled=l}),$e.dataset.personaComposerStreaming=l?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},se=()=>{yt.active||Pe&&Pe.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>se(),200)});let J=()=>{var h,b,T,W,q,F,R,ce,de,Z,we;Ar.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",U.textContent=(W=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",Pe.placeholder=(F=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?F:"How can I help...";let l=Me.querySelector("[data-persona-intro-card]");if(l){let Fe=((R=r.copy)==null?void 0:R.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(Me.classList.remove("persona-gap-3"),Me.classList.add("persona-gap-6")):(Me.classList.remove("persona-gap-6"),Me.classList.add("persona-gap-3"))}!((de=(ce=r.sendButton)==null?void 0:ce.useIcon)!=null&&de)&&!(_!=null&&_.isStreaming())&&(Ge.textContent=(we=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?we:"Send"),Pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(u=>({...u,sessionId:l}))}});let Ee=null,je=()=>{Ee==null&&(Ee=setInterval(()=>{let l=Ze.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Ee),Ee=null;return}let u=Date.now();l.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=wi(u-b))})},100))};_=new _s(r,{onMessagesChanged(l){var b;yo(Ze,l,ke),je(),gs(l),Dr(!Ir),oi(l);let u=[...l].reverse().find(T=>T.role==="user");l.length===0&&qo(),!hs||Uo?(hs=!0,ys=(b=u==null?void 0:u.id)!=null?b:null):u&&u.id!==ys&&(ys=u.id,ri(u.id));let h=yt.lastUserMessageId;u&&u.id!==h&&(yt.lastUserMessageId=u.id,o.emit("user:message",u)),yt.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),vs(l),qe()},onStatusChanged(l){var b;let u=(b=r.statusIndicator)!=null?b:{};tt(mn,(T=>{var W,q,F,R;return T==="idle"?(W=u.idleText)!=null?W:Mn.idle:T==="connecting"?(q=u.connectingText)!=null?q:Mn.connecting:T==="connected"?(F=u.connectedText)!=null?F:Mn.connected:T==="error"?(R=u.errorText)!=null?R:Mn.error:Mn[T]})(l),u,l)},onStreamingChanged(l){Ir=l,X(l),_&&yo(Ze,_.getMessages(),ke),l||Dr(!0),qe()},onVoiceStatusChanged(l){var u,h;if(o.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Qr(),As();break;case"processing":Qr(),Xf();break;case"speaking":Qr(),Yf();break;default:l==="idle"&&_.isBargeInActive()?(Qr(),As(),V==null||V.setAttribute("aria-label","End voice session")):(yt.active=!1,Qr(),lr("system"),$n());break}},onArtifactsState(l){Vn=l,Jn(),vs()}}),Et.current=_;let lt=null;if(_.onReadAloudChange((l,u)=>{var T;lo=l,co=u,po();let h=l!=null?l:lt;l&&(lt=l);let b=h&&(T=_.getMessages().find(W=>W.id===h))!=null?T:null;o.emit("message:read-aloud",{messageId:h,message:b,state:u,timestamp:Date.now()}),u==="idle"&&(lt=null)}),hs=!0,((Kd=(Vd=r.voiceRecognition)==null?void 0:Vd.provider)==null?void 0:Kd.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&_.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(pe||r.onSSEEvent)&&_.setSSEEventCallback((l,u)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,u),me==null||me.processEvent(l,u),pe==null||pe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),c&&c.then(l=>{var u,h,b;if(l){if(l.metadata&&(d=Ac(l.metadata),A.syncFromMetadata()),(u=l.messages)!=null&&u.length){Uo=!0;try{_.hydrateMessages(l.messages)}finally{Uo=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let ot=()=>{var u,h,b;!N()||L||!((b=(h=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||E(!0,"auto")},Bt=l=>{var T;if(l.preventDefault(),_.isStreaming()){_.cancel(),me==null||me.reset(),K==null||K.update();return}let u=Pe.value.trim(),h=(T=vt==null?void 0:vt.hasAttachments())!=null?T:!1;if(!u&&!h)return;ot();let b;h&&(b=[],b.push(...vt.getContentParts()),u&&b.push(Ea(u))),Pe.value="",Pe.style.height="auto",Mt(),_.sendMessage(u,{contentParts:b}),h&&vt.clearAttachments()},qt=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},cn={...ji},St=!1,Mt=()=>{cn={...ji}},xn=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var u;return(u=l.content)!=null?u:""}).filter(l=>l.length>0),Wn=l=>{if(!Pe)return;St=!0,Pe.value=l,Pe.dispatchEvent(new Event("input",{bubbles:!0})),St=!1;let u=Pe.value.length;Pe.setSelectionRange(u,u)},Sn=()=>{St||Mt()},en=l=>{if(Pe){if(qt()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let u=Pe.selectionStart===0&&Pe.selectionEnd===0,h=ug({direction:l.key==="ArrowUp"?"up":"down",history:xn(),currentValue:Pe.value,atStart:u,state:cn});if(cn=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Wn(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Mt(),l.preventDefault(),Ge.click()}}},cr=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(ge)&&(_.cancel(),me==null||me.reset(),K==null||K.update(),Mt(),l.preventDefault(),l.stopImmediatePropagation())},jc=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!vt)return;let u=Bb(l.clipboardData);u.length!==0&&(l.preventDefault(),await vt.handleFiles(u))},dr=null,Nr=!1,Ss=null,gt=null,Uc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,li=(l="user")=>{var W,q,F,R,ce,de,Z;if(Nr||_.isStreaming())return;let u=Uc();if(!u)return;dr=new u;let b=(q=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?q:2e3;dr.continuous=!0,dr.interimResults=!0,dr.lang="en-US";let T=Pe.value;dr.onresult=we=>{let Fe="",Te="";for(let ze=0;ze<we.results.length;ze++){let ft=we.results[ze],ct=ft[0].transcript;ft.isFinal?Fe+=ct+" ":Te=ct}let it=T+Fe+Te;Pe.value=it,Ss&&clearTimeout(Ss),(Fe||Te)&&(Ss=window.setTimeout(()=>{let ze=Pe.value.trim();ze&&dr&&Nr&&(wo(),Pe.value="",Pe.style.height="auto",_.sendMessage(ze,{viaVoice:!0}))},b))},dr.onerror=we=>{we.error!=="no-speech"&&wo()},dr.onend=()=>{if(Nr){let we=Pe.value.trim();we&&we!==T.trim()&&(Pe.value="",Pe.style.height="auto",_.sendMessage(we,{viaVoice:!0})),wo()}};try{if(dr.start(),Nr=!0,yt.active=!0,l!=="system"&&(yt.manuallyDeactivated=!1),lr(l),$n(),V){let we=(F=r.voiceRecognition)!=null?F:{};gt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(R=we.iconName)!=null?R:"mic",iconSize:parseFloat((Z=(de=we.iconSize)!=null?de:(ce=r.sendButton)==null?void 0:ce.size)!=null?Z:"40")||24};let Fe=we.recordingBackgroundColor,Te=we.recordingIconColor,it=we.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let ze=V.querySelector("svg");ze&&ze.setAttribute("stroke",Te)}it&&(V.style.borderColor=it),V.setAttribute("aria-label","Stop voice recognition")}}catch{wo("system")}},wo=(l="user")=>{if(Nr){if(Nr=!1,Ss&&(clearTimeout(Ss),Ss=null),dr){try{dr.stop()}catch{}dr=null}if(yt.active=!1,lr(l),$n(),V){if(V.classList.remove("persona-voice-recording"),gt){V.style.backgroundColor=gt.backgroundColor,V.style.color=gt.color,V.style.borderColor=gt.borderColor;let u=V.querySelector("svg");u&&u.setAttribute("stroke",gt.color||"currentColor"),gt=null}V.setAttribute("aria-label","Start voice recognition")}}},Qf=(l,u)=>{var ct,Ie,Le,Ve,Ye,xt,P,De,Re;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((ct=l==null?void 0:l.provider)==null?void 0:ct.type)==="runtype",T=((Ie=l==null?void 0:l.provider)==null?void 0:Ie.type)==="custom";if(!(h||b||T))return null;let q=y("div","persona-send-button-wrapper"),F=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let R=(Le=l==null?void 0:l.iconName)!=null?Le:"mic",ce=(Ve=u==null?void 0:u.size)!=null?Ve:"40px",de=(Ye=l==null?void 0:l.iconSize)!=null?Ye:ce,Z=parseFloat(de)||24,we=(xt=l==null?void 0:l.backgroundColor)!=null?xt:u==null?void 0:u.backgroundColor,Fe=(P=l==null?void 0:l.iconColor)!=null?P:u==null?void 0:u.textColor;F.style.width=de,F.style.height=de,F.style.minWidth=de,F.style.minHeight=de,F.style.fontSize="18px",F.style.lineHeight="1",Fe?F.style.color=Fe:F.style.color="var(--persona-text, #111827)";let it=ve(R,Z,Fe||"currentColor",1.5);it?F.appendChild(it):F.textContent="\u{1F3A4}",we?F.style.backgroundColor=we:F.style.backgroundColor="",l!=null&&l.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l!=null&&l.borderColor&&(F.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),q.appendChild(F);let ze=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((Re=l==null?void 0:l.showTooltip)!=null?Re:!1)&&ze){let he=y("div","persona-send-button-tooltip");he.textContent=ze,q.appendChild(he)}return{micButton:F,micButtonWrapper:q}},El=()=>{var u,h,b,T,W;if(!V||gt)return;let l=(u=r.voiceRecognition)!=null?u:{};gt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((W=(T=l.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?W:"40")||24}},Ml=(l,u)=>{var W,q,F,R,ce;if(!V)return;let h=V.querySelector("svg");h&&h.remove();let b=(ce=gt==null?void 0:gt.iconSize)!=null?ce:parseFloat((R=(F=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?F:(q=r.sendButton)==null?void 0:q.size)!=null?R:"40")||24,T=ve(l,b,u,1.5);T&&V.appendChild(T)},ci=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},As=()=>{var T;if(!V)return;El();let l=(T=r.voiceRecognition)!=null?T:{},u=l.recordingBackgroundColor,h=l.recordingIconColor,b=l.recordingBorderColor;if(ci(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=u!=null?u:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let W=V.querySelector("svg");W&&W.setAttribute("stroke",h)}b&&(V.style.borderColor=b),V.setAttribute("aria-label","Stop voice recognition")},Xf=()=>{var F,R,ce,de,Z,we,Fe,Te;if(!V)return;El();let l=(F=r.voiceRecognition)!=null?F:{},u=_.getVoiceInterruptionMode(),h=(R=l.processingIconName)!=null?R:"loader",b=(de=(ce=l.processingIconColor)!=null?ce:gt==null?void 0:gt.color)!=null?de:"",T=(we=(Z=l.processingBackgroundColor)!=null?Z:gt==null?void 0:gt.backgroundColor)!=null?we:"",W=(Te=(Fe=l.processingBorderColor)!=null?Fe:gt==null?void 0:gt.borderColor)!=null?Te:"";ci(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=T,V.style.borderColor=W;let q=b||"currentColor";V.style.color=q,Ml(h,q),V.setAttribute("aria-label","Processing voice input"),u==="none"&&(V.style.cursor="default")},Yf=()=>{var ce,de,Z,we,Fe,Te,it,ze,ft,ct,Ie,Le;if(!V)return;El();let l=(ce=r.voiceRecognition)!=null?ce:{},u=_.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",b=(de=l.speakingIconName)!=null?de:h,T=(Te=l.speakingIconColor)!=null?Te:u==="barge-in"?(we=(Z=l.recordingIconColor)!=null?Z:gt==null?void 0:gt.color)!=null?we:"":(Fe=gt==null?void 0:gt.color)!=null?Fe:"",W=(ft=l.speakingBackgroundColor)!=null?ft:u==="barge-in"?(it=l.recordingBackgroundColor)!=null?it:"var(--persona-voice-recording-bg, #ef4444)":(ze=gt==null?void 0:gt.backgroundColor)!=null?ze:"",q=(Le=l.speakingBorderColor)!=null?Le:u==="barge-in"?(ct=l.recordingBorderColor)!=null?ct:"":(Ie=gt==null?void 0:gt.borderColor)!=null?Ie:"";ci(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=W,V.style.borderColor=q;let F=T||"currentColor";V.style.color=F,Ml(b,F);let R=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",R),u==="none"&&(V.style.cursor="default"),u==="barge-in"&&V.classList.add("persona-voice-recording")},Qr=()=>{var l,u,h;V&&(ci(),gt&&(V.style.backgroundColor=(l=gt.backgroundColor)!=null?l:"",V.style.color=(u=gt.color)!=null?u:"",V.style.borderColor=(h=gt.borderColor)!=null?h:"",Ml(gt.iconName,gt.color||"currentColor"),gt=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},di=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=_.getVoiceStatus(),b=_.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),lr("user"),Qr()});return}_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),yt.manuallyDeactivated=!_.isVoiceActive(),$n(),lr("user"),_.isVoiceActive()?As():Qr()});return}if(Nr){let h=Pe.value.trim();yt.manuallyDeactivated=!0,$n(),wo("user"),h&&(Pe.value="",Pe.style.height="auto",_.sendMessage(h))}else yt.manuallyDeactivated=!1,$n(),li("user")};qn=di,V&&(V.addEventListener("click",di),ut.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Qr()):wo("system"),V&&V.removeEventListener("click",di)}));let Zf=o.on("assistant:complete",()=>{Zs&&(yt.active||yt.manuallyDeactivated||Zs==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!yt.active&&!yt.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("auto"),_.isVoiceActive()&&As()}):li("auto"))},600))});ut.push(Zf);let eh=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});ut.push(eh);let qc=()=>{E(!L,"user")},rn=null,fn=null;if(M&&!N()){let{instance:l,element:u}=pc({config:r,plugins:s,onToggle:qc});rn=l,l||(fn=u)}rn?e.appendChild(rn.element):fn&&e.appendChild(fn),$(),gs(),J(),X(_.isStreaming()),at()==="follow"?Dr(!0):aa(),Ya(),D&&(!M||N()?setTimeout(()=>se(),0):L&&setTimeout(()=>se(),200));let pa=()=>{var R,ce,de,Z,we,Fe,Te,it,ze,ft,ct,Ie,Le,Ve,Ye,xt,P,De,Re,he,$t,Ft;if(N()){Fn(),$();return}let l=un(r),u=(ce=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?ce:!1,h=l||u||((Z=(de=r.launcher)==null?void 0:de.fullHeight)!=null?Z:!1),b=(we=e.ownerDocument.defaultView)!=null?we:window,T=(Te=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Te:!0,W=(ze=(it=r.launcher)==null?void 0:it.mobileBreakpoint)!=null?ze:640,q=b.innerWidth<=W,F=T&&q&&M;try{if(F){xe(),Io(e,r);return}if(I&&(I=!1,xe(),Io(e,r)),!M&&!l){fe.style.height="",fe.style.width="";return}if(!u&&!l){let Jt=(ct=(ft=r==null?void 0:r.launcher)==null?void 0:ft.width)!=null?ct:r==null?void 0:r.launcherWidth,wt=Jt!=null?Jt:tr;fe.style.width=wt,fe.style.maxWidth=wt}if(kr(),!h){let Jt=b.innerHeight,wt=64,zt=(Le=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Le:0,Yn=Math.max(200,Jt-wt),on=Math.min(640,Yn),et=Math.max(200,on-zt);fe.style.height=`${et}px`}}finally{if(Fn(),$(),L&&M){let wt=((Ve=e.ownerDocument.defaultView)!=null?Ve:window).innerWidth<=((xt=(Ye=r.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?xt:640),zt=(De=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?De:!1,Yn=(he=(Re=r.launcher)==null?void 0:Re.mobileFullscreen)!=null?he:!0,on=un(r)&&Yn&&wt,et=zt||Yn&&wt&&M||on;if(et&&!gn){let It=e.getRootNode(),pn=It instanceof ShadowRoot?It.host:e.closest(".persona-host");pn&&!nn&&(nn=sc(pn,(Ft=($t=r.launcher)==null?void 0:$t.zIndex)!=null?Ft:kn)),gn=ac(e.ownerDocument)}else et||(nn==null||nn(),nn=null,gn==null||gn(),gn=null)}}};pa();let zc=(Gd=e.ownerDocument.defaultView)!=null?Gd:window;if(zc.addEventListener("resize",pa),ut.push(()=>zc.removeEventListener("resize",pa)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Fn()});l.observe($e),ut.push(()=>l.disconnect())}Xn=Me.scrollTop;let Vc=ro(Me),th=()=>{let l=Me.getRootNode(),u=typeof l.getSelection=="function"?l.getSelection():null;return u!=null?u:Me.ownerDocument.getSelection()},kl=()=>bg(th(),Me),Kc=()=>{let l=Me.scrollTop,u=ro(Me),h=u<Vc;if(Vc=u,at()!=="follow"){Xn=l,jn();return}let{action:b,nextLastScrollTop:T}=qi({following:Qn.isFollowing(),currentScrollTop:l,lastScrollTop:Xn,nearBottom:is(Me,bs),userScrollThreshold:Qa,isAutoScrolling:br||jo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Xn=T,b==="resume"){kl()||Br();return}b==="pause"&&ws()};if(Me.addEventListener("scroll",Kc,{passive:!0}),ut.push(()=>Me.removeEventListener("scroll",Kc)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{ni()});l.observe(Ze),l.observe(Me),ut.push(()=>l.disconnect())}let Gc=()=>{at()==="follow"&&Qn.isFollowing()&&kl()&&ws()},Jc=Me.ownerDocument;Jc.addEventListener("selectionchange",Gc),ut.push(()=>{Jc.removeEventListener("selectionchange",Gc)});let Qc=l=>{if(at()!=="follow")return;let u=zi({following:Qn.isFollowing(),deltaY:l.deltaY,nearBottom:is(Me,bs),resumeWhenNearBottom:!0});u==="pause"?ws():u==="resume"&&!kl()&&Br()};Me.addEventListener("wheel",Qc,{passive:!0}),ut.push(()=>Me.removeEventListener("wheel",Qc)),pt.addEventListener("click",()=>{qo(),Me.scrollTop=Me.scrollHeight,Xn=Me.scrollTop,Br(),Dr(!0),jn()}),ut.push(()=>pt.remove()),ut.push(()=>{ta(),qo()});let Xc=()=>{G&&(Pr&&(G.removeEventListener("click",Pr),Pr=null),O()?(G.style.display="",Pr=()=>{E(!1,"user")},G.addEventListener("click",Pr)):G.style.display="none")};Xc(),(()=>{let{clearChatButton:l}=te;l&&l.addEventListener("click",()=>{_.clearMessages(),Rr.clear(),Br(),Mo(te.composerOverlay);try{localStorage.removeItem(Xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Xs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},A.syncFromMetadata(),pe==null||pe.clear(),me==null||me.reset(),K==null||K.update()})})(),Wt&&Wt.addEventListener("submit",Bt),Pe==null||Pe.addEventListener("keydown",en),Pe==null||Pe.addEventListener("input",Sn),Pe==null||Pe.addEventListener("paste",jc);let Yc=(Jd=e.ownerDocument)!=null?Jd:document;Yc.addEventListener("keydown",cr,!0);let Zc="persona-attachment-drop-active",ua=0,Ll=()=>{ua=0,ge.classList.remove(Zc)},Ts=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&vt!==null},ed=l=>{!yl(l.dataTransfer)||!Ts()||(ua++,ua===1&&ge.classList.add(Zc))},td=l=>{!yl(l.dataTransfer)||!Ts()||(ua--,ua<=0&&Ll())},nd=l=>{!yl(l.dataTransfer)||!Ts()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},rd=l=>{var h;if(!yl(l.dataTransfer)||!Ts())return;l.preventDefault(),l.stopPropagation(),Ll();let u=Array.from((h=l.dataTransfer.files)!=null?h:[]);u.length!==0&&vt.handleFiles(u)},Co=!0;ge.addEventListener("dragenter",ed,Co),ge.addEventListener("dragleave",td,Co),e.addEventListener("dragover",nd,Co),e.addEventListener("drop",rd,Co);let pi=e.ownerDocument,od=l=>{Ts()&&l.preventDefault()},sd=l=>{Ts()&&l.preventDefault()};pi.addEventListener("dragover",od),pi.addEventListener("drop",sd),ut.push(()=>{Wt&&Wt.removeEventListener("submit",Bt),Pe==null||Pe.removeEventListener("keydown",en),Pe==null||Pe.removeEventListener("input",Sn),Pe==null||Pe.removeEventListener("paste",jc),Yc.removeEventListener("keydown",cr,!0)}),ut.push(()=>{ge.removeEventListener("dragenter",ed,Co),ge.removeEventListener("dragleave",td,Co),e.removeEventListener("dragover",nd,Co),e.removeEventListener("drop",rd,Co),pi.removeEventListener("dragover",od),pi.removeEventListener("drop",sd),Ll()}),ut.push(()=>{_.cancel()}),rn?ut.push(()=>{rn==null||rn.destroy()}):fn&&ut.push(()=>{fn==null||fn.remove()});let dn={update(l){var Tn,Hn,Or,vn,Bn,Dn,Jo,ma,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Sp,Ap,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Qp,Xp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Su,Au,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Nu,Ou,Fu,_u,$u,ju,Uu,qu,zu,Vu,Ku,Gu,Ju,Qu,Xu,Yu,Zu,em;let u=r.toolCall,h=r.messageActions,b=(Tn=r.layout)==null?void 0:Tn.messages,T=r.colorScheme,W=r.loadingIndicator,q=r.iterationDisplay,F=(Hn=r.features)==null?void 0:Hn.showReasoning,R=(Or=r.features)==null?void 0:Or.showToolCalls,ce=(vn=r.features)==null?void 0:vn.toolCallDisplay,de=(Bn=r.features)==null?void 0:Bn.reasoningDisplay;r={...r,...l},xe(),Io(e,r),ll(e,r),cl(e,r),Jn(),r.colorScheme!==T&&Ys();let Z=qa.getForInstance(r.plugins);s.length=0,s.push(...Z),M=(Jo=(Dn=r.launcher)==null?void 0:Dn.enabled)!=null?Jo:!0,B=(np=(ma=r.launcher)==null?void 0:ma.autoExpand)!=null?np:!1,Ke=(op=(rp=r.features)==null?void 0:rp.showReasoning)!=null?op:!0,Ce=(ap=(sp=r.features)==null?void 0:sp.showToolCalls)!=null?ap:!0,Ne=(lp=(ip=r.features)==null?void 0:ip.scrollToBottom)!=null?lp:{};let we=at();be=(dp=(cp=r.features)==null?void 0:cp.scrollBehavior)!=null?dp:{},we!==at()&&(qo(),Br()),Tr(),jn();let Fe=We;if(We=(up=(pp=r.features)==null?void 0:pp.showEventStreamToggle)!=null?up:!1,We&&!Fe){if(pe||(Q=new ja(ue),pe=new $a(ne,Q),me=me!=null?me:new Ua,Q.open().then(()=>pe==null?void 0:pe.restore()).catch(()=>{}),_.setSSEEventCallback((re,kt)=>{var Vt;(Vt=r.onSSEEvent)==null||Vt.call(r,re,kt),me==null||me.processEvent(re,kt),pe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(kt)})})),!bt&&Ue){let re=(gp=(mp=r.features)==null?void 0:mp.eventStream)==null?void 0:gp.classNames,kt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(re!=null&&re.toggleButton?" "+re.toggleButton:"");bt=y("button",kt),bt.style.width="28px",bt.style.height="28px",bt.style.color=On.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let Vt=ve("activity","18px","currentColor",1.5);Vt&&bt.appendChild(Vt);let dt=te.clearChatButtonWrapper,Rt=te.closeButtonWrapper,yn=dt||Rt;yn&&yn.parentNode===Ue?Ue.insertBefore(bt,yn):Ue.appendChild(bt),bt.addEventListener("click",()=>{ae?fr():jr()})}}else!We&&Fe&&(fr(),bt&&(bt.remove(),bt=null),pe==null||pe.clear(),Q==null||Q.destroy(),pe=null,Q=null,me==null||me.reset(),me=null);if(((fp=r.launcher)==null?void 0:fp.enabled)===!1&&rn&&(rn.destroy(),rn=null),((hp=r.launcher)==null?void 0:hp.enabled)===!1&&fn&&(fn.remove(),fn=null),((yp=r.launcher)==null?void 0:yp.enabled)!==!1&&!rn&&!fn){let{instance:re,element:kt}=pc({config:r,plugins:s,onToggle:qc});rn=re,re||(fn=kt),e.appendChild(kt)}rn&&rn.update(r),Xe&&((bp=r.launcher)==null?void 0:bp.title)!==void 0&&(Xe.textContent=r.launcher.title),rt&&((xp=r.launcher)==null?void 0:xp.subtitle)!==void 0&&(rt.textContent=r.launcher.subtitle);let Te=(vp=r.layout)==null?void 0:vp.header;if((Te==null?void 0:Te.layout)!==S&&Ue){let re=Te?qs(r,Te,{showClose:O(),onClose:()=>E(!1,"user")}):oo({config:r,showClose:O(),onClose:()=>E(!1,"user")});Qe.replaceHeader(re),Ue=Qe.header.element,ye=Qe.header.iconHolder,Xe=Qe.header.headerTitle,rt=Qe.header.headerSubtitle,G=Qe.header.closeButton,S=Te==null?void 0:Te.layout}else if(Te&&(ye&&(ye.style.display=Te.showIcon===!1?"none":""),Xe&&(Xe.style.display=Te.showTitle===!1?"none":""),rt&&(rt.style.display=Te.showSubtitle===!1?"none":""),G&&(G.style.display=Te.showCloseButton===!1?"none":""),te.clearChatButtonWrapper)){let re=Te.showClearChat;if(re!==void 0){te.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:kt}=te;kt&&!kt.classList.contains("persona-absolute")&&(re?kt.classList.remove("persona-ml-auto"):kt.classList.add("persona-ml-auto"))}}let ze=((wp=r.layout)==null?void 0:wp.showHeader)!==!1;Ue&&(Ue.style.display=ze?"":"none");let ft=((Cp=r.layout)==null?void 0:Cp.showFooter)!==!1;$e&&($e.style.display=ft?"":"none"),Fn(),jn(),M!==H?M?E(B,"auto"):(L=!0,$()):B!==k&&E(B,"auto"),k=B,H=M,pa(),Xc();let Le=JSON.stringify(l.toolCall)!==JSON.stringify(u),Ve=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ye=JSON.stringify((Sp=r.layout)==null?void 0:Sp.messages)!==JSON.stringify(b),xt=((Ap=r.loadingIndicator)==null?void 0:Ap.render)!==(W==null?void 0:W.render)||((Tp=r.loadingIndicator)==null?void 0:Tp.renderIdle)!==(W==null?void 0:W.renderIdle)||((Ep=r.loadingIndicator)==null?void 0:Ep.showBubble)!==(W==null?void 0:W.showBubble),P=r.iterationDisplay!==q,De=((kp=(Mp=r.features)==null?void 0:Mp.showReasoning)!=null?kp:!0)!==(F!=null?F:!0)||((Pp=(Lp=r.features)==null?void 0:Lp.showToolCalls)!=null?Pp:!0)!==(R!=null?R:!0)||JSON.stringify((Ip=r.features)==null?void 0:Ip.toolCallDisplay)!==JSON.stringify(ce)||JSON.stringify((Rp=r.features)==null?void 0:Rp.reasoningDisplay)!==JSON.stringify(de);(Le||Ve||Ye||xt||P||De)&&_&&(fs++,yo(Ze,_.getMessages(),ke));let he=(Wp=r.launcher)!=null?Wp:{},$t=(Hp=he.headerIconHidden)!=null?Hp:!1,Ft=(Dp=(Bp=r.layout)==null?void 0:Bp.header)==null?void 0:Dp.showIcon,Jt=$t||Ft===!1,wt=he.headerIconName,zt=(Np=he.headerIconSize)!=null?Np:"48px";if(ye){let re=ge.querySelector(".persona-border-b-persona-divider"),kt=re==null?void 0:re.querySelector(".persona-flex-col");if(Jt)ye.style.display="none",re&&kt&&!re.contains(kt)&&re.insertBefore(kt,re.firstChild);else{if(ye.style.display="",ye.style.height=zt,ye.style.width=zt,re&&kt&&(re.contains(ye)?ye.nextSibling!==kt&&(ye.remove(),re.insertBefore(ye,kt)):re.insertBefore(ye,kt)),wt){let dt=parseFloat(zt)||24,Rt=ve(wt,dt*.6,"currentColor",1);Rt?ye.replaceChildren(Rt):ye.textContent=(Op=he.agentIconText)!=null?Op:"\u{1F4AC}"}else if(he.iconUrl){let dt=ye.querySelector("img");if(dt)dt.src=he.iconUrl,dt.style.height=zt,dt.style.width=zt;else{let Rt=document.createElement("img");Rt.src=he.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=zt,Rt.style.width=zt,ye.replaceChildren(Rt)}}else{let dt=ye.querySelector("svg"),Rt=ye.querySelector("img");(dt||Rt)&&ye.replaceChildren(),ye.textContent=(Fp=he.agentIconText)!=null?Fp:"\u{1F4AC}"}let Vt=ye.querySelector("img");Vt&&(Vt.style.height=zt,Vt.style.width=zt)}}let Yn=($p=(_p=r.layout)==null?void 0:_p.header)==null?void 0:$p.showTitle,on=(Up=(jp=r.layout)==null?void 0:jp.header)==null?void 0:Up.showSubtitle;if(Xe&&(Xe.style.display=Yn===!1?"none":""),rt&&(rt.style.display=on===!1?"none":""),G){((zp=(qp=r.layout)==null?void 0:qp.header)==null?void 0:zp.showCloseButton)===!1?G.style.display="none":G.style.display="";let kt=(Vp=he.closeButtonSize)!=null?Vp:"32px",Vt=(Kp=he.closeButtonPlacement)!=null?Kp:"inline";G.style.height=kt,G.style.width=kt;let{closeButtonWrapper:dt}=te,Rt=Vt==="top-right",yn=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Rt!==yn)if(dt.remove(),Rt)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ge.style.position="relative",ge.appendChild(dt);else{let mt=(Jp=(Gp=he.clearChat)==null?void 0:Gp.placement)!=null?Jp:"inline",bn=(Xp=(Qp=he.clearChat)==null?void 0:Qp.enabled)!=null?Xp:!0;dt.className=bn&&mt==="inline"?"":"persona-ml-auto";let Un=ge.querySelector(".persona-border-b-persona-divider");Un&&Un.appendChild(dt)}if(G.style.color=he.closeButtonColor||On.actionIconColor,he.closeButtonBackgroundColor?(G.style.backgroundColor=he.closeButtonBackgroundColor,G.classList.remove("hover:persona-bg-gray-100")):(G.style.backgroundColor="",G.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let mt=he.closeButtonBorderWidth||"0px",bn=he.closeButtonBorderColor||"transparent";G.style.border=`${mt} solid ${bn}`,G.classList.remove("persona-border-none")}else G.style.border="",G.classList.add("persona-border-none");he.closeButtonBorderRadius?(G.style.borderRadius=he.closeButtonBorderRadius,G.classList.remove("persona-rounded-full")):(G.style.borderRadius="",G.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(G.style.paddingLeft=he.closeButtonPaddingX,G.style.paddingRight=he.closeButtonPaddingX):(G.style.paddingLeft="",G.style.paddingRight=""),he.closeButtonPaddingY?(G.style.paddingTop=he.closeButtonPaddingY,G.style.paddingBottom=he.closeButtonPaddingY):(G.style.paddingTop="",G.style.paddingBottom="");let En=(Yp=he.closeButtonIconName)!=null?Yp:"x",vr=(Zp=he.closeButtonIconText)!=null?Zp:"\xD7";G.innerHTML="";let Nn=ve(En,"28px","currentColor",1);Nn?G.appendChild(Nn):G.textContent=vr;let tn=(eu=he.closeButtonTooltipText)!=null?eu:"Close chat",er=(tu=he.closeButtonShowTooltip)!=null?tu:!0;if(G.setAttribute("aria-label",tn),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),er&&tn)){let mt=null,bn=()=>{if(mt||!G)return;let Qo=G.ownerDocument,ga=Qo.body;if(!ga)return;mt=_r(Qo,"div","persona-clear-chat-tooltip"),mt.textContent=tn;let fa=_r(Qo,"div");fa.className="persona-clear-chat-tooltip-arrow",mt.appendChild(fa);let Xo=G.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(Ro),mt.style.left=`${Xo.left+Xo.width/2}px`,mt.style.top=`${Xo.top-8}px`,mt.style.transform="translate(-50%, -100%)",ga.appendChild(mt)},Un=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};dt.addEventListener("mouseenter",bn),dt.addEventListener("mouseleave",Un),G.addEventListener("focus",bn),G.addEventListener("blur",Un),dt._cleanupTooltip=()=>{Un(),dt&&(dt.removeEventListener("mouseenter",bn),dt.removeEventListener("mouseleave",Un)),G&&(G.removeEventListener("focus",bn),G.removeEventListener("blur",Un))}}}let{clearChatButton:et,clearChatButtonWrapper:It}=te;if(et){let re=(nu=he.clearChat)!=null?nu:{},kt=(ru=re.enabled)!=null?ru:!0,Vt=(su=(ou=r.layout)==null?void 0:ou.header)==null?void 0:su.showClearChat,dt=Vt!==void 0?Vt:kt,Rt=(au=re.placement)!=null?au:"inline";if(It){It.style.display=dt?"":"none";let{closeButtonWrapper:yn}=te;!N()&&yn&&!yn.classList.contains("persona-absolute")&&(dt?yn.classList.remove("persona-ml-auto"):yn.classList.add("persona-ml-auto"));let En=Rt==="top-right",vr=It.classList.contains("persona-absolute");if(!N()&&En!==vr&&dt){if(It.remove(),En)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",ge.style.position="relative",ge.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let tn=ge.querySelector(".persona-border-b-persona-divider"),er=te.closeButtonWrapper;tn&&er&&er.parentElement===tn?tn.insertBefore(It,er):tn&&tn.appendChild(It)}let Nn=te.closeButtonWrapper;Nn&&!Nn.classList.contains("persona-absolute")&&(En?Nn.classList.add("persona-ml-auto"):Nn.classList.remove("persona-ml-auto"))}}if(dt){if(!N()){let mt=(iu=re.size)!=null?iu:"32px";et.style.height=mt,et.style.width=mt}let yn=(lu=re.iconName)!=null?lu:"refresh-cw",En=(cu=re.iconColor)!=null?cu:"";et.style.color=En||On.actionIconColor,et.innerHTML="";let vr=N()?"14px":"20px",Nn=ve(yn,vr,"currentColor",2);if(Nn&&et.appendChild(Nn),re.backgroundColor?(et.style.backgroundColor=re.backgroundColor,et.classList.remove("hover:persona-bg-gray-100")):(et.style.backgroundColor="",et.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let mt=re.borderWidth||"0px",bn=re.borderColor||"transparent";et.style.border=`${mt} solid ${bn}`,et.classList.remove("persona-border-none")}else et.style.border="",et.classList.add("persona-border-none");re.borderRadius?(et.style.borderRadius=re.borderRadius,et.classList.remove("persona-rounded-full")):(et.style.borderRadius="",et.classList.add("persona-rounded-full")),re.paddingX?(et.style.paddingLeft=re.paddingX,et.style.paddingRight=re.paddingX):(et.style.paddingLeft="",et.style.paddingRight=""),re.paddingY?(et.style.paddingTop=re.paddingY,et.style.paddingBottom=re.paddingY):(et.style.paddingTop="",et.style.paddingBottom="");let tn=(du=re.tooltipText)!=null?du:"Clear chat",er=(pu=re.showTooltip)!=null?pu:!0;if(et.setAttribute("aria-label",tn),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),er&&tn)){let mt=null,bn=()=>{if(mt||!et)return;let Qo=et.ownerDocument,ga=Qo.body;if(!ga)return;mt=_r(Qo,"div","persona-clear-chat-tooltip"),mt.textContent=tn;let fa=_r(Qo,"div");fa.className="persona-clear-chat-tooltip-arrow",mt.appendChild(fa);let Xo=et.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(Ro),mt.style.left=`${Xo.left+Xo.width/2}px`,mt.style.top=`${Xo.top-8}px`,mt.style.transform="translate(-50%, -100%)",ga.appendChild(mt)},Un=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};It.addEventListener("mouseenter",bn),It.addEventListener("mouseleave",Un),et.addEventListener("focus",bn),et.addEventListener("blur",Un),It._cleanupTooltip=()=>{Un(),It&&(It.removeEventListener("mouseenter",bn),It.removeEventListener("mouseleave",Un)),et&&(et.removeEventListener("focus",bn),et.removeEventListener("blur",Un))}}}}let pn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[za],ur=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ps.message,ps.messageAndClick];A=Va({parsers:pn,handlers:ur,getSessionMetadata:g,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),ke=lf(r,A,oe),_.updateConfig(r),yo(Ze,_.getMessages(),ke),gs(),J(),X(_.isStreaming());let Zn=((uu=r.voiceRecognition)==null?void 0:uu.enabled)===!0,zo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Vo=((gu=(mu=r.voiceRecognition)==null?void 0:mu.provider)==null?void 0:gu.type)==="runtype";if(Zn&&(zo||Vo))if(!V||!Ht){let re=Qf(r.voiceRecognition,r.sendButton);re&&(V=re.micButton,Ht=re.micButtonWrapper,Yt.insertBefore(Ht,wn),V.addEventListener("click",di),V.disabled=_.isStreaming())}else{let re=(fu=r.voiceRecognition)!=null?fu:{},kt=(hu=r.sendButton)!=null?hu:{},Vt=(yu=re.iconName)!=null?yu:"mic",dt=(bu=kt.size)!=null?bu:"40px",Rt=(xu=re.iconSize)!=null?xu:dt,yn=parseFloat(Rt)||24;V.style.width=Rt,V.style.height=Rt,V.style.minWidth=Rt,V.style.minHeight=Rt;let En=(wu=(vu=re.iconColor)!=null?vu:kt.textColor)!=null?wu:"currentColor";V.innerHTML="";let vr=ve(Vt,yn,En,2);vr?V.appendChild(vr):V.textContent="\u{1F3A4}";let Nn=(Cu=re.backgroundColor)!=null?Cu:kt.backgroundColor;Nn?V.style.backgroundColor=Nn:V.style.backgroundColor="",En?V.style.color=En:V.style.color="var(--persona-text, #111827)",re.borderWidth?(V.style.borderWidth=re.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),re.borderColor?V.style.borderColor=re.borderColor:V.style.borderColor="",re.paddingX?(V.style.paddingLeft=re.paddingX,V.style.paddingRight=re.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),re.paddingY?(V.style.paddingTop=re.paddingY,V.style.paddingBottom=re.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let tn=Ht==null?void 0:Ht.querySelector(".persona-send-button-tooltip"),er=(Su=re.tooltipText)!=null?Su:"Start voice recognition";if(((Au=re.showTooltip)!=null?Au:!1)&&er)if(tn)tn.textContent=er,tn.style.display="";else{let bn=document.createElement("div");bn.className="persona-send-button-tooltip",bn.textContent=er,Ht==null||Ht.insertBefore(bn,V)}else tn&&(tn.style.display="none");Ht.style.display="",V.disabled=_.isStreaming()}else V&&Ht&&(Ht.style.display="none",((Eu=(Tu=r.voiceRecognition)==null?void 0:Tu.provider)==null?void 0:Eu.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Nr&&wo());if(((Mu=r.attachments)==null?void 0:Mu.enabled)===!0)if(!Ae||!le){let re=(ku=r.attachments)!=null?ku:{},Vt=(Pu=((Lu=r.sendButton)!=null?Lu:{}).size)!=null?Pu:"40px";Tt||(Tt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Tt.style.display="none",Wt.insertBefore(Tt,Pe)),_e||(_e=document.createElement("input"),_e.type="file",_e.accept=((Iu=re.allowedTypes)!=null?Iu:no).join(","),_e.multiple=((Ru=re.maxFiles)!=null?Ru:4)>1,_e.style.display="none",_e.setAttribute("aria-label","Attach files"),Wt.insertBefore(_e,Pe)),Ae=y("div","persona-send-button-wrapper"),le=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",(Wu=re.buttonTooltipText)!=null?Wu:"Attach file");let dt=(Hu=re.buttonIconName)!=null?Hu:"paperclip",Rt=Vt,yn=parseFloat(Rt)||40,En=Math.round(yn*.6);le.style.width=Rt,le.style.height=Rt,le.style.minWidth=Rt,le.style.minHeight=Rt,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let vr=ve(dt,En,"currentColor",1.5);vr?le.appendChild(vr):le.textContent="\u{1F4CE}",le.addEventListener("click",er=>{er.preventDefault(),_e==null||_e.click()}),Ae.appendChild(le);let Nn=(Bu=re.buttonTooltipText)!=null?Bu:"Attach file",tn=y("div","persona-send-button-tooltip");tn.textContent=Nn,Ae.appendChild(tn),Gt.append(Ae),!vt&&_e&&Tt&&(vt=as.fromConfig(re),vt.setPreviewsContainer(Tt),_e.addEventListener("change",async()=>{vt&&(_e!=null&&_e.files)&&(await vt.handleFileSelect(_e.files),_e.value="")})),ge.querySelector(".persona-attachment-drop-overlay")||ge.appendChild(cf(re.dropOverlay))}else{Ae.style.display="";let re=(Du=r.attachments)!=null?Du:{};_e&&(_e.accept=((Nu=re.allowedTypes)!=null?Nu:no).join(","),_e.multiple=((Ou=re.maxFiles)!=null?Ou:4)>1),vt&&vt.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}else Ae&&(Ae.style.display="none"),vt&&vt.clearAttachments(),(Fu=ge.querySelector(".persona-attachment-drop-overlay"))==null||Fu.remove();let Qt=(_u=r.sendButton)!=null?_u:{},Ko=($u=Qt.useIcon)!=null?$u:!1,So=(ju=Qt.iconText)!=null?ju:"\u2191",Ao=Qt.iconName,Xr=(Uu=Qt.tooltipText)!=null?Uu:"Send message",Go=(qu=Qt.showTooltip)!=null?qu:!1,xr=(zu=Qt.size)!=null?zu:"40px",st=Qt.backgroundColor,hn=Qt.textColor;if(Ko){if(Ge.style.width=xr,Ge.style.height=xr,Ge.style.minWidth=xr,Ge.style.minHeight=xr,Ge.style.fontSize="18px",Ge.style.lineHeight="1",Ge.innerHTML="",hn?Ge.style.color=hn:Ge.style.color="var(--persona-button-primary-fg, #ffffff)",Ao){let re=parseFloat(xr)||24,kt=(hn==null?void 0:hn.trim())||"currentColor",Vt=ve(Ao,re,kt,2);Vt?Ge.appendChild(Vt):Ge.textContent=So}else Ge.textContent=So;Ge.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",st?(Ge.style.backgroundColor=st,Ge.classList.remove("persona-bg-persona-primary")):(Ge.style.backgroundColor="",Ge.classList.add("persona-bg-persona-primary"))}else Ge.textContent=(Ku=(Vu=r.copy)==null?void 0:Vu.sendButtonLabel)!=null?Ku:"Send",Ge.style.width="",Ge.style.height="",Ge.style.minWidth="",Ge.style.minHeight="",Ge.style.fontSize="",Ge.style.lineHeight="",Ge.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",st?(Ge.style.backgroundColor=st,Ge.classList.remove("persona-bg-persona-accent")):Ge.classList.add("persona-bg-persona-accent"),hn?Ge.style.color=hn:Ge.classList.add("persona-text-white");Qt.borderWidth?(Ge.style.borderWidth=Qt.borderWidth,Ge.style.borderStyle="solid"):(Ge.style.borderWidth="",Ge.style.borderStyle=""),Qt.borderColor?Ge.style.borderColor=Qt.borderColor:Ge.style.borderColor="",Qt.paddingX?(Ge.style.paddingLeft=Qt.paddingX,Ge.style.paddingRight=Qt.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),Qt.paddingY?(Ge.style.paddingTop=Qt.paddingY,Ge.style.paddingBottom=Qt.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Ut=wn==null?void 0:wn.querySelector(".persona-send-button-tooltip");if(Go&&Xr)if(Ut)Ut.textContent=Xr,Ut.style.display="";else{let re=document.createElement("div");re.className="persona-send-button-tooltip",re.textContent=Xr,wn==null||wn.insertBefore(re,Ge)}else Ut&&(Ut.style.display="none");let jt=(Yu=(Gu=r.layout)==null?void 0:Gu.contentMaxWidth)!=null?Yu:N()?(Xu=(Qu=(Ju=r.launcher)==null?void 0:Ju.composerBar)==null?void 0:Qu.contentMaxWidth)!=null?Xu:"720px":void 0;jt?(Ze.style.maxWidth=jt,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%",Wt&&(Wt.style.maxWidth=jt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Je&&(Je.style.maxWidth=jt,Je.style.marginLeft="auto",Je.style.marginRight="auto")):(Ze.style.maxWidth="",Ze.style.marginLeft="",Ze.style.marginRight="",Ze.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Je&&(Je.style.maxWidth="",Je.style.marginLeft="",Je.style.marginRight=""));let ht=(Zu=r.statusIndicator)!=null?Zu:{},Xt=(em=ht.visible)!=null?em:!0;if(mn.style.display=Xt?"":"none",_){let re=_.getStatus();tt(mn,(Vt=>{var dt,Rt,yn,En;return Vt==="idle"?(dt=ht.idleText)!=null?dt:Mn.idle:Vt==="connecting"?(Rt=ht.connectingText)!=null?Rt:Mn.connecting:Vt==="connected"?(yn=ht.connectedText)!=null?yn:Mn.connected:Vt==="error"?(En=ht.errorText)!=null?En:Mn.error:Mn[Vt]})(re),ht,re)}mn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let At=ht.align==="left"?"persona-text-left":ht.align==="center"?"persona-text-center":"persona-text-right";mn.classList.add(At)},open(){O()&&E(!0,"api")},close(){O()&&E(!1,"api")},toggle(){O()&&E(!L,"api")},clearChat(){In=!1,_.clearMessages(),Rr.clear(),Br();try{localStorage.removeItem(Xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xs}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Xs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}d={},A.syncFromMetadata(),pe==null||pe.clear(),me==null||me.reset(),K==null||K.update()},setMessage(l){return!Pe||_.isStreaming()?!1:(!L&&O()&&E(!0,"system"),Pe.value=l,Pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let u=(l==null?void 0:l.trim())||Pe.value.trim();return u?(!L&&O()&&E(!0,"system"),Pe.value="",Pe.style.height="auto",_.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return _.isStreaming()?!1:((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!L&&O()&&E(!0,"system"),yt.manuallyDeactivated=!1,$n(),_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("user"),_.isVoiceActive()&&As()})),!0):Nr?!0:Uc()?(!L&&O()&&E(!0,"system"),yt.manuallyDeactivated=!1,$n(),li("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),lr("user"),Qr()}),!0):!1:Nr?(yt.manuallyDeactivated=!0,$n(),wo("user"),!0):!1},injectMessage(l){return!L&&O()&&E(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!L&&O()&&E(!0,"system");let u=_.injectAssistantMessage(l);return j&&(j=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),u},injectUserMessage(l){return!L&&O()&&E(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!L&&O()&&E(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!L&&O()&&E(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!L&&O()&&E(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!L&&O()&&E(!0,"system"),_.injectTestEvent(l)},async connectStream(l,u){return _.connectStream(l,u)},__pushEventStreamEvent(l){pe&&(me==null||me.processEvent(l.type,l.payload),pe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!We||!pe||jr()},hideEventStream(){ae&&fr()},isEventStreamVisible(){return ae},showArtifacts(){gr(r)&&(In=!1,Jn(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){gr(r)&&(In=!0,Jn())},upsertArtifact(l){return gr(r)?(In=!1,_.upsertArtifact(l)):null},selectArtifact(l){gr(r)&&_.selectArtifact(l)},clearArtifacts(){gr(r)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return M&&!L&&!N()||!Pe?!1:(Pe.focus(),!0)},async resolveApproval(l,u,h){let T=_.getMessages().find(W=>{var q;return W.variant==="approval"&&((q=W.approval)==null?void 0:q.id)===l});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${l}`);if(T.approval.toolType==="webmcp"){_.resolveWebMcpApproval(T.id,u);return}return _.resolveApproval(T.approval,u,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){f(l)},on(l,u){return o.on(l,u)},off(l,u){o.off(l,u)},isOpen(){return O()&&L},isVoiceActive(){return yt.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:O()&&L,launcherEnabled:M,voiceActive:yt.active,streaming:_.isStreaming()}},showCSATFeedback(l){!L&&O()&&E(!0,"system");let u=Ze.querySelector(".persona-feedback-container");u&&u.remove();let h=fl({onSubmit:async(b,T)=>{var W;_.isClientTokenMode()&&await _.submitCSATFeedback(b,T),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!L&&O()&&E(!0,"system");let u=Ze.querySelector(".persona-feedback-container");u&&u.remove();let h=hl({onSubmit:async(b,T)=>{var W;_.isClientTokenMode()&&await _.submitNPSFeedback(b,T),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return _.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return _.submitNPSFeedback(l,u)},destroy(){Ee!=null&&(clearInterval(Ee),Ee=null),ut.forEach(l=>l()),Oe.remove(),nt==null||nt.remove(),rn==null||rn.destroy(),fn==null||fn.remove(),Pr&&G.removeEventListener("click",Pr)}};if((((Qd=n==null?void 0:n.debugTools)!=null?Qd:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:dn,getMessages:dn.getMessages,getStatus:dn.getStatus,getMetadata:dn.getPersistentMetadata,updateMetadata:dn.updatePersistentMetadata,clearHistory:()=>dn.clearChat(),setVoiceActive:h=>h?dn.startVoiceRecognition():dn.stopVoiceRecognition()};window.AgentWidgetBrowser=u,ut.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&dn.focusInput()};if(window.addEventListener("persona:focusInput",u),ut.push(()=>{window.removeEventListener("persona:focusInput",u)}),We){let F=ce=>{let de=ce.detail;(!(de!=null&&de.instanceId)||de.instanceId===l)&&dn.showEventStream()},R=ce=>{let de=ce.detail;(!(de!=null&&de.instanceId)||de.instanceId===l)&&dn.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",R),ut.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",R)})}let h=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&dn.showArtifacts()},b=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&dn.hideArtifacts()},T=F=>{let R=F.detail;R!=null&&R.instanceId&&R.instanceId!==l||R!=null&&R.artifact&&dn.upsertArtifact(R.artifact)},W=F=>{let R=F.detail;R!=null&&R.instanceId&&R.instanceId!==l||typeof(R==null?void 0:R.id)=="string"&&dn.selectArtifact(R.id)},q=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&dn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",q),ut.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",q)})}let pr=Db(r.persistState);if(pr&&O()){let l=Nb(pr.storage),u=`${pr.keyPrefix}widget-open`,h=`${pr.keyPrefix}widget-voice`,b=`${pr.keyPrefix}widget-voice-mode`;if(l){let T=((Xd=pr.persist)==null?void 0:Xd.openState)&&l.getItem(u)==="true",W=((Yd=pr.persist)==null?void 0:Yd.voiceState)&&l.getItem(h)==="true",q=((Zd=pr.persist)==null?void 0:Zd.voiceState)&&l.getItem(b)==="true";if(T&&setTimeout(()=>{dn.open(),setTimeout(()=>{var F;if(W||q)dn.startVoiceRecognition();else if((F=pr.persist)!=null&&F.focusInput){let R=e.querySelector("textarea");R&&R.focus()}},100)},0),(ep=pr.persist)!=null&&ep.openState&&(o.on("widget:opened",()=>{l.setItem(u,"true")}),o.on("widget:closed",()=>{l.setItem(u,"false")})),(tp=pr.persist)!=null&&tp.voiceState&&(o.on("voice:state",F=>{l.setItem(h,F.active?"true":"false")}),o.on("user:message",F=>{l.setItem(b,F.viaVoice?"true":"false")})),pr.clearOnChatClear){let F=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(b)},R=()=>F();window.addEventListener("persona:clear-chat",R),ut.push(()=>{window.removeEventListener("persona:clear-chat",R)})}}}return p&&O()&&setTimeout(()=>{dn.open()},0),qe(),Ja||lm().then(()=>{_&&(fs++,Rr.clear(),yo(Ze,_.getMessages(),ke))}).catch(()=>{}),dn};var Ob=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Fb=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},_b=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},$b=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let s=r.offsetHeight>0;r.style.height="100%";let o=r.offsetHeight>0;r.remove(),!(!s||o)&&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.")},df=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},kc=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=""},pf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",kc(e)},Tc=e=>{e.style.transition=""},Ec=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=""},Mc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},xl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},jb=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Ub=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},uf=(e,t,n,r,s,o,a)=>{var x,v,A,M,B,D;let i=nr(o),d=i.reveal==="push";jb(e,t,n,r,d),Ub(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(v=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,m=(M=(A=o==null?void 0:o.launcher)==null?void 0:A.mobileBreakpoint)!=null?M:640,g=c!=null?c.innerWidth<=m:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ec(t),Tc(r),pf(r),Mc(n),xl(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((D=(B=o==null?void 0:o.launcher)==null?void 0:B.zIndex)!=null?D:kn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),pf(r),Fb(r,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",Ec(t),Tc(r),Mc(n),xl(s,r);let k=i.animate?"transform 180ms ease":"none",H=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":H;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=k,r.style.transform=S,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Tc(r),kc(r),xl(s,r);let k=Ob(i.width,e.clientWidth),H=Math.max(0,e.clientWidth),S=i.animate?"margin-left 180ms ease":"none",I=i.side==="right"?a?-k:0:a?0:-k;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=`${H+k}px`,t.style.transition=S,t.style.marginLeft=`${I}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${H}px`,n.style.maxWidth=`${H}px`,n.style.minWidth=`${H}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ec(t),kc(r),Mc(n),xl(s,r);let k=i.reveal==="emerge";k?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let H=a?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",I=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${H}`,r.style.width=H,r.style.maxWidth=H,r.style.minWidth=H,r.style.minHeight="0",_b(r,i.maxHeight),r.style.overflow=k||I?"hidden":"visible",r.style.transition=S,k&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},qb=(e,t)=>{let n=e.ownerDocument.createElement("div");return df(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){df(n,r)},destroy(){n.remove()}}},zb=(e,t)=>{var D,k,H,S;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),m=(k=(D=t==null?void 0:t.launcher)==null?void 0:D.enabled)==null||k?(S=(H=t==null?void 0:t.launcher)==null?void 0:H.autoExpand)!=null?S:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,f=()=>{g==null||g.disconnect(),g=null},x=()=>{f(),nr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{uf(a,i,d,c,p,t,m)}),g.observe(a))},v=!1,A=()=>{uf(a,i,d,c,p,t,m),x(),m&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,$b(a,nr(t)))},M=a.ownerDocument.defaultView,B=()=>{A()};return M==null||M.addEventListener("resize",B),nr(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),A(),{mode:"docked",host:p,shell:a,syncWidgetState(I){let N=I.launcherEnabled?I.open:!0;m!==N&&(m=N,A())},updateConfig(I){var N,O;t=I,((O=(N=t==null?void 0:t.launcher)==null?void 0:N.enabled)!=null?O:!0)===!1&&(m=!0),A()},destroy(){M==null||M.removeEventListener("resize",B),f(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},Ka=(e,t)=>un(t)?zb(e,t):qb(e,t);var Lc={},mf=!1,Vb=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},Kb=()=>{try{if(typeof Lc!="undefined"&&Lc.url)return new URL("../widget.css",Lc.url).href}catch{}return null},gf=(e,t)=>{let n=Kb(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},Pc=e=>{let t=Vb(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=Ka(t,s),a,i=[],d=(A,M)=>{var H,S;let D=!((S=(H=M==null?void 0:M.launcher)==null?void 0:H.enabled)!=null?S:!0)||un(M),k=r.createElement("div");if(k.setAttribute("data-persona-root","true"),D&&(k.style.height="100%",k.style.display="flex",k.style.flexDirection="column",k.style.flex="1",k.style.minHeight="0"),n){let I=A.attachShadow({mode:"open"});I.appendChild(k),gf(I,r)}else A.appendChild(k),gf(A,r);return t.id&&k.setAttribute("data-persona-instance",t.id),k},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},m=()=>{let A=d(o.host,s);a=bl(A,s,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(A=>A()),i=[],a.destroy()};m(),e.onChatReady?e.onChatReady():e.onReady&&(mf||(mf=!0,console.warn("[Persona] `onReady` is deprecated: use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let f=A=>{g(),o.destroy(),o=Ka(t,A),s=A,m()},x={update(A){var S,I,N,O,L,j;let M={...s,...A,launcher:{...(S=s==null?void 0:s.launcher)!=null?S:{},...(I=A==null?void 0:A.launcher)!=null?I:{},dock:{...(O=(N=s==null?void 0:s.launcher)==null?void 0:N.dock)!=null?O:{},...(j=(L=A==null?void 0:A.launcher)==null?void 0:L.dock)!=null?j:{}}}},B=un(s),D=un(M),k=Ho(s),H=Ho(M);if(B!==D||k!==H){f(M);return}s=M,o.updateConfig(s),a.update(A),c()},destroy(){g(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(x,{get(A,M,B){if(M==="host")return o.host;if(M in A)return Reflect.get(A,M,B);let D=a[M];return typeof D=="function"?D.bind(a):D}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var xf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Gb=new Set(["button","a","input","select","textarea","details","summary"]),Jb=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ic=/\b(product|card|item|listing|result)\b/i,Wc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Qb=3e3,Xb=100;function vf(e){let t=typeof e.className=="string"?e.className:"";if(Ic.test(t)||e.id&&Ic.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Ic.test(r.value))return!0}return!1}function wf(e){var t;return Wc.test(((t=e.textContent)!=null?t:"").trim())}function Cf(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Yb(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ff(e){let t=e.match(Wc);return t?t[0]:null}function hf(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Zb(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var ex="commerce-card",tx="result-card";function yf(e){return!vf(e)||!wf(e)||!Cf(e)&&!Yb(e)?0:5200}function bf(e){var r;return!vf(e)||wf(e)||!Cf(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Hc=[{id:ex,scoreElement(e){return yf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||Wc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(yf(e)===0)return null;let{title:n,href:r}=hf(e),s=(p=(c=ff(((d=e.textContent)!=null?d:"").trim()))!=null?c:ff(t.text))!=null?p:"",o=Zb(e);return[r&&n?`[${n}](${r})${s?`: ${s}`:""}`:n?`${n}${s?`: ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
110
- `)}},{id:tx,scoreElement(e){return bf(e)},formatSummary(e,t){if(bf(e)===0)return null;let{title:n,href:r}=hf(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
111
- `)}}];function nx(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function rx(e){var p,m,g,f,x,v,A,M,B,D,k,H,S;let t=(p=e.options)!=null?p:{},n=(g=(m=t.maxElements)!=null?m:e.maxElements)!=null?g:80,r=(x=(f=t.excludeSelector)!=null?f:e.excludeSelector)!=null?x:".persona-host",s=(A=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?A:200,o=(B=(M=t.visibleOnly)!=null?M:e.visibleOnly)!=null?B:!0,a=(D=t.root)!=null?D:e.root,i=(k=t.mode)!=null?k:"structured",d=(H=t.maxCandidates)!=null?H:Math.max(500,n*10),c=(S=e.rules)!=null?S:Hc;return i==="simple"&&e.rules&&e.rules.length>0?(nx(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function Rc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var ox=["data-testid","data-product","data-action","data-id","data-name","data-type"];function sx(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||Gb.has(t)||n&&Jb.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Sf(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 ax(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Bc(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${Rc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of ox){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${Rc(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>Rc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function ix(e){return e==="static"?Xb:Qb}function Af(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:Bc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:sx(e),attributes:ax(e)}}function lx(e,t,n,r){let s=ix(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function cx(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function dx(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(xf.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Sf(c)){i=a.nextNode();continue}let m=Af(c,e.maxTextLength),g=m.text.length>0,f=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(A=>A==="role");if(!g&&!f){i=a.nextNode();continue}if(r.has(m.selector)){i=a.nextNode();continue}r.add(m.selector);let{score:x,formattingRule:v}=lx(c,m,e.rules,n);s.push({el:c,domIndex:o,enriched:m,score:x,formattingRule:v}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let m=c.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;cx(d,c)||d.push(c)}return d.sort((c,p)=>{let m=c.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:m===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var g;let p;if((g=c.formattingRule)!=null&&g.formatSummary){let f=c.formattingRule.formatSummary(c.el,c.enriched,n);f&&(p=f)}let m={...c.enriched};return p&&(m.formattedSummary=p),m})}function px(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,c=d.tagName.toLowerCase();if(xf.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Sf(d)){o=s.nextNode();continue}let p=Af(d,e.maxTextLength),m=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(f=>f==="role");if(!m&&!g){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}o=s.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Tf(e={}){var r;let t=rx(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?px(t,n):dx(t,n):[]}var vl=100;function Ef(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
109
+ `}if(!b&&!l){let Ut="max-height: -moz-available !important; max-height: stretch !important;",jt=u?"":"padding-top: 1.25em !important;",ht=u?"":`z-index: ${(hn=(st=r.launcher)==null?void 0:st.zIndex)!=null?hn:kn} !important;`;Oe.style.cssText+=Ut+jt+ht}Ye()};xe(),Ro(e,r),ll(e,r),cl(e,r);let ut=[];ut.push(()=>{document.removeEventListener("keydown",go)});let nn=null,gn=null;ut.push(()=>{nn==null||nn(),nn=null,gn==null||gn(),gn=null}),zn&&ut.push(()=>{zn==null||zn.disconnect(),zn=null}),ut.push(()=>{Rn==null||Rn(),Rn=null,Vr(),Ot&&(Ot.remove(),Ot=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),We&&ut.push(()=>{He!==null&&(cancelAnimationFrame(He),He=null),K==null||K.destroy(),K=null,pe==null||pe.destroy(),pe=null,Q=null});let Pr=null,Ys=()=>{Pr&&(Pr(),Pr=null),r.colorScheme==="auto"&&(Pr=_i(()=>{Ro(e,r)}))};Ys(),ut.push(()=>{Pr&&(Pr(),Pr=null)});let Kr=(Ud=r.features)==null?void 0:Ud.streamAnimation;if(Kr!=null&&Kr.type&&Kr.type!=="none"){let l=Ha(Kr.type,Kr.plugins);l&&(oc(l,e),ut.push(()=>Mg(e)))}let jo=jg(Je),Ir=null,_,gs=l=>{var b,T;if(!_)return;let u=l!=null?l:_.getMessages(),h=((T=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:T.enabled)!==!1?xi(u):null;h?jo.render(h,_,Pe,u,r.suggestionChipsConfig,{agentPushed:!0}):u.some(W=>W.role==="user")?jo.render([],_,Pe,u):jo.render(r.suggestionChips,_,Pe,u,r.suggestionChipsConfig)},Rr=!1,Wr=fg(),Gr=new Map,Hr=new Map,yr=new Map,fs=0,Ja=Ps()!==null,Qn=Ui(),Xn=0,br=null,xr=!1,Uo=!1,Jr=0,An=null,Br=null,hs=!1,qo=!1,ys=null,Qa=4,bs=24,Xa=80,xs=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Zs=(zd=(qd=r.voiceRecognition)==null?void 0:qd.autoResume)!=null?zd:!1,lr=l=>{o.emit("voice:state",{active:yt.active,source:l,timestamp:Date.now()})},$n=()=>{f(l=>({...l,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Ya=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=Ac(d.voiceState),u=!!l.active,h=Number((T=l.timestamp)!=null?T:0);yt.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Hb&&setTimeout(()=>{var W,q;yt.active||(yt.manuallyDeactivated=!1,((q=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:q.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("restore"),_.isVoiceActive()&&As()}):li("restore"))},1e3)},Za=()=>_?lf(_.getMessages()).filter(l=>!l.__skipPersist):[];function vs(l){if(!(i!=null&&i.save))return;let h={messages:l?lf(l):_?Za():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let b=i.save(h);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Qr=null,ea=()=>Oe.querySelector("#persona-scroll-container")||Me,yo=()=>{Qr!==null&&(cancelAnimationFrame(Qr),Qr=null),xr=!1},ta=()=>{br!==null&&(cancelAnimationFrame(br),br=null),Uo=!1,yo()},na=()=>{Jr>0?(Pn.textContent=String(Jr),Pn.style.display="",pt.setAttribute("aria-label",`${an()||"Jump to latest"} (${Jr} new)`)):(Pn.textContent="",Pn.style.display="none",pt.setAttribute("aria-label",an()||"Jump to latest"))},ra=()=>{Jr!==0&&(Jr=0,na())},oa=()=>at()==="follow"?!Qn.isFollowing():!ls(Me,bs),jn=()=>{if(!Nt()||ae){pt.parentNode&&pt.remove(),pt.style.display="none";return}pt.parentNode!==ge&&ge.appendChild(pt),Fn();let u=oo(Me)>0&&oa();u||ra(),pt.style.display=u?"":"none"},ws=()=>{Qn.pause()&&(ta(),jn())},Dr=()=>{Qn.resume(),ra(),jn()},Nr=(l=!1)=>{at()==="follow"&&Qn.isFollowing()&&(!l&&!Rr||(br!==null&&(cancelAnimationFrame(br),br=null),Uo=!0,br=requestAnimationFrame(()=>{br=null,Uo=!1,Qn.isFollowing()&&ei(ea(),l?220:140)})))},sa=(l,u,h,b=()=>!0)=>{let T=l.scrollTop,W=u(),q=W-T;yo();let F=performance.now();xr=!0;let R=de=>1-Math.pow(1-de,3),ce=de=>{if(!b()){yo();return}let Z=u();Z!==W&&(W=Z,q=W-T);let we=de-F,Fe=Math.min(we/h,1),Te=R(Fe),it=T+q*Te;l.scrollTop=it,Xn=l.scrollTop,Fe<1?Qr=requestAnimationFrame(ce):(l.scrollTop=W,Xn=l.scrollTop,Qr=null,xr=!1)};Qr=requestAnimationFrame(ce)},ei=(l,u=500)=>{let h=oo(l)-l.scrollTop;if(Math.abs(h)<1){Xn=l.scrollTop;return}if(Math.abs(h)>=Xa){yo(),xr=!0,l.scrollTop=oo(l),Xn=l.scrollTop,xr=!1;return}sa(l,()=>oo(l),u,()=>Qn.isFollowing())},aa=()=>{let l=ea();xr=!0,l.scrollTop=oo(l),Xn=l.scrollTop,xr=!1,jn()},ia=l=>{ln.style.height=`${Math.max(0,Math.round(l))}px`,An&&(An.spacerHeight=Math.max(0,l))},zo=()=>{Br!==null&&(cancelAnimationFrame(Br),Br=null),yo(),An=null,ln.style.height="0px"},ti=l=>{Br!==null&&cancelAnimationFrame(Br),Br=requestAnimationFrame(()=>{var ce;Br=null;let u=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Me.querySelector(`[data-message-id="${u}"]`);if(!h)return;let b=0,T=h;for(;T&&T!==Me;)b+=T.offsetTop,T=T.offsetParent;let W=(ce=An==null?void 0:An.spacerHeight)!=null?ce:0,q=Me.scrollHeight-W,{targetScrollTop:F,spacerHeight:R}=vg({anchorOffsetTop:b,topOffset:Dt(),viewportHeight:Me.clientHeight,contentHeight:q});An={initialSpacerHeight:R,contentHeightAtAnchor:q,spacerHeight:R},ia(R),sa(Me,()=>F,220)})},ni=()=>{if(at()==="follow"){if(!Qn.isFollowing()||ls(Me,1))return;Nr(!Rr);return}if(An&&An.initialSpacerHeight>0){let l=Me.scrollHeight-An.spacerHeight,u=wg({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:l});u!==An.spacerHeight&&ia(u)}jn()},ri=l=>{let u=at();u==="follow"?(Dr(),Nr(!0)):u==="anchor-top"&&ti(l)},oi=l=>{let u=new Map;l.forEach(h=>{let b=xs.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(o.emit("assistant:message",h),!qo&&at()!=="anchor-top"&&oa()&&(Jr+=1,na(),jn())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&o.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&o.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):o.emit("approval:requested",{approval:h.approval,message:h}))}),xs.clear(),u.forEach((h,b)=>{xs.set(b,h)})},si=(l,u,h)=>{var ct,Ie,Le,Ve,Ye,xt;let b=document.createElement("div"),W=(()=>{var De;let P=s.find(Re=>Re.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),q=(P,De)=>De==null?!1:typeof De=="string"?(P.textContent=De,!0):(P.appendChild(De),!0),F=new Set,R=new Set,ce=s.some(P=>P.renderAskUserQuestion),de=[],Z=[],we=r.enableComponentStreaming!==!1,Fe=s.some(P=>P.renderApproval)&&r.approval!==!1,Te=[];if(u.forEach(P=>{var et,It,pn,ur,Zn,Vo,Ko,Es,Ms,Qt,Go,Ao,To,Yr,Jo,vr;F.add(P.id);let De=ce&&eo(P),Re=Fe&&P.variant==="approval"&&!!P.approval,he=!De&&P.role==="assistant"&&!P.variant&&we&&ml(P);if(!Re&&yr.has(P.id)){let st=l.querySelector(`#wrapper-${P.id}`);st==null||st.removeAttribute("data-preserve-runtime"),yr.delete(P.id)}if(!he&&Hr.has(P.id)){let st=l.querySelector(`#wrapper-${P.id}`);st==null||st.removeAttribute("data-preserve-runtime"),Hr.delete(P.id)}let $t=eo(P)?`:${(et=P.agentMetadata)!=null&&et.askUserQuestionAnswered?"a":"u"}:${(It=P.agentMetadata)!=null&&It.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ft=gg(P,fs)+$t,Jt=De||Re||he?null:hg(Wr,P.id,Ft);if(Jt){b.appendChild(Jt.cloneNode(!0)),eo(P)&&((pn=P.toolCall)!=null&&pn.id)&&((ur=P.agentMetadata)==null?void 0:ur.awaitingLocalTool)===!0&&!((Zn=P.agentMetadata)!=null&&Zn.askUserQuestionAnswered)&&(R.add(P.toolCall.id),Bs(P,r,te.composerOverlay));return}let wt=null,zt=s.find(st=>!!(P.variant==="reasoning"&&st.renderReasoning||P.variant==="tool"&&st.renderToolCall||!P.variant&&st.renderMessage)),Yn=(Vo=r.layout)==null?void 0:Vo.messages;if(eo(P)&&((Ko=P.agentMetadata)==null?void 0:Ko.askUserQuestionAnswered)===!0){Gr.delete(P.id);let st=l.querySelector(`#wrapper-${P.id}`);st==null||st.removeAttribute("data-preserve-runtime");return}if(Ca(P)&&((Ms=(Es=r.features)==null?void 0:Es.suggestReplies)==null?void 0:Ms.enabled)!==!1)return;if(eo(P)&&((Go=(Qt=r.features)==null?void 0:Qt.askUserQuestion)==null?void 0:Go.enabled)!==!1){let st=s.find(hn=>typeof hn.renderAskUserQuestion=="function");if(st&&Et.current){let hn=Gr.get(P.id),Ut=hn!==Ft,jt=null;if(Ut){let{payload:At,complete:Tn}=to(P),Hn=P.id,Fr=()=>{var vn;return(vn=Et.current)==null?void 0:vn.getMessages().find(Bn=>Bn.id===Hn)};jt=st.renderAskUserQuestion({message:P,payload:At,complete:Tn,resolve:vn=>{var Dn;let Bn=Fr();Bn&&((Dn=Et.current)==null||Dn.resolveAskUserQuestion(Bn,vn))},dismiss:()=>{var Bn,Dn,Qo;let vn=Fr();(Bn=vn==null?void 0:vn.agentMetadata)!=null&&Bn.awaitingLocalTool&&((Dn=Et.current)==null||Dn.markAskUserQuestionResolved(vn),(Qo=Et.current)==null||Qo.resolveAskUserQuestion(vn,"(dismissed)"))},config:r})}let ht=hn!=null;if(Ut&&jt===null&&!ht){((Ao=P.agentMetadata)==null?void 0:Ao.awaitingLocalTool)===!0&&!((To=P.agentMetadata)!=null&&To.askUserQuestionAnswered)&&(R.add(P.toolCall.id),Bs(P,r,te.composerOverlay));return}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${P.id}`,Xt.setAttribute("data-wrapper-id",P.id),Xt.setAttribute("data-ask-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),b.appendChild(Xt),de.push({messageId:P.id,fingerprint:Ft,bubble:jt});return}else{((Yr=P.agentMetadata)==null?void 0:Yr.awaitingLocalTool)===!0&&!((Jo=P.agentMetadata)!=null&&Jo.askUserQuestionAnswered)&&(R.add(P.toolCall.id),Bs(P,r,te.composerOverlay));return}}else if(Re){let st=s.find(ht=>typeof ht.renderApproval=="function"),Ut=yr.get(P.id)!==Ft,jt=null;if(Ut&&(st!=null&&st.renderApproval)){let ht=P.id,Xt=(At,Tn)=>{var Fr,vn,Bn;let Hn=(Fr=Et.current)==null?void 0:Fr.getMessages().find(Dn=>Dn.id===ht);Hn!=null&&Hn.approval&&(Hn.approval.toolType==="webmcp"?(vn=Et.current)==null||vn.resolveWebMcpApproval(Hn.id,At):(Bn=Et.current)==null||Bn.resolveApproval(Hn.approval,At,Tn))};jt=st.renderApproval({message:P,defaultRenderer:()=>al(P,r),config:r,approve:At=>Xt("approved",At),deny:At=>Xt("denied",At)})}if(Ut&&jt===null){let ht=l.querySelector(`#wrapper-${P.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),yr.delete(P.id),wt=al(P,r)}else{let ht=document.createElement("div");ht.className="persona-flex",ht.id=`wrapper-${P.id}`,ht.setAttribute("data-wrapper-id",P.id),ht.setAttribute("data-approval-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),b.appendChild(ht),Te.push({messageId:P.id,fingerprint:Ft,bubble:jt});return}}else if(zt)if(P.variant==="reasoning"&&P.reasoning&&zt.renderReasoning){if(!Ke)return;wt=zt.renderReasoning({message:P,defaultRenderer:()=>hc(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&zt.renderToolCall){if(!Ce)return;wt=zt.renderToolCall({message:P,defaultRenderer:()=>yc(P,r),config:r})}else zt.renderMessage&&(wt=zt.renderMessage({message:P,defaultRenderer:()=>{let st=Vs(P,h,Yn,r.messageActions,ee,{loadingIndicatorRenderer:W,widgetConfig:r});return P.role!=="user"&&wc(st,P,r,_),st},config:r}));if(!wt&&he){let st=gl(P);if(st){let hn=Hr.get(P.id),Ut=hn!==Ft,jt=r.wrapComponentDirectiveInBubble!==!1,ht=null;if(Ut){let Xt=ul(st,{config:r,message:P,transform:h});if(Xt)if(jt){let At=document.createElement("div");if(At.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(" "),At.id=`bubble-${P.id}`,At.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let Tn=document.createElement("div");Tn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Tn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),At.appendChild(Tn)}At.appendChild(Xt),ht=At}else{let At=document.createElement("div");if(At.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",At.id=`bubble-${P.id}`,At.setAttribute("data-message-id",P.id),At.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let Tn=document.createElement("div");Tn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Tn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),At.appendChild(Tn)}At.appendChild(Xt),ht=At}}if(ht||hn!=null){let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${P.id}`,Xt.setAttribute("data-wrapper-id",P.id),Xt.setAttribute("data-component-directive-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),jt||Xt.classList.add("persona-w-full"),b.appendChild(Xt),Z.push({messageId:P.id,fingerprint:Ft,bubble:ht});return}}}if(!wt)if(P.variant==="reasoning"&&P.reasoning){if(!Ke)return;wt=hc(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!Ce)return;wt=yc(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;wt=al(P,r)}else{let st=(vr=r.layout)==null?void 0:vr.messages;st!=null&&st.renderUserMessage&&P.role==="user"?wt=st.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):st!=null&&st.renderAssistantMessage&&P.role==="assistant"?wt=st.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):wt=Vs(P,h,st,r.messageActions,ee,{loadingIndicatorRenderer:W,widgetConfig:r}),P.role!=="user"&&wt&&wc(wt,P,r,_)}let on=document.createElement("div");on.className="persona-flex",on.id=`wrapper-${P.id}`,on.setAttribute("data-wrapper-id",P.id),P.role==="user"&&on.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&on.classList.add("persona-w-full"),on.appendChild(wt),yg(Wr,P.id,Ft,on),b.appendChild(on)}),te.composerOverlay&&te.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let Re=De.getAttribute("data-persona-ask-sheet-for");Re&&!R.has(Re)&&ko(te.composerOverlay,Re)}),(Ie=(ct=r.features)==null?void 0:ct.toolCallDisplay)!=null&&Ie.grouped){let P=[],De=[];u.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&Ce){De.push(Re);return}De.length>1&&P.push(De),De=[]}),De.length>1&&P.push(De),P.forEach((Re,he)=>{var et,It;let $t=Re.map(pn=>Array.from(b.children).find(ur=>ur instanceof HTMLElement&&ur.getAttribute("data-wrapper-id")===pn.id)).filter(pn=>!!pn);if($t.length<2)return;let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id=`wrapper-tool-group-${he}-${Re[0].id}`,Ft.setAttribute("data-wrapper-id",`tool-group-${he}-${Re[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Re.length} tools`,Yn=(It=(et=r.toolCall)==null?void 0:et.renderGroupedSummary)==null?void 0:It.call(et,{messages:Re,toolCalls:Re.map(pn=>pn.toolCall).filter(pn=>!!pn),defaultSummary:zt,config:r});q(wt,Yn)||(wt.textContent=zt);let on=document.createElement("div");on.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(wt,on),Ft.appendChild(Jt),$t[0].before(Ft),$t.forEach((pn,ur)=>{let Zn=document.createElement("div");Zn.className="persona-tool-group-item persona-relative",Zn.setAttribute("data-persona-tool-group-item","true"),ur<$t.length-1&&Zn.setAttribute("data-persona-tool-group-connector","true"),Zn.appendChild(pn),on.appendChild(Zn)})})}bg(Wr,F);let it=u.some(P=>P.role==="assistant"&&P.streaming),ze=u[u.length-1],ft=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(Rr&&u.some(P=>P.role==="user")&&!it&&!ft){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:ds},De=s.find(he=>he.renderLoadingIndicator),Re=null;if(De!=null&&De.renderLoadingIndicator&&(Re=De.renderLoadingIndicator(P)),Re===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(Re=r.loadingIndicator.render(P)),Re===null&&(Re=ds()),Re){let he=document.createElement("div"),$t=((Ve=r.loadingIndicator)==null?void 0:Ve.showBubble)!==!1;he.className=$t?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),he.setAttribute("data-typing-indicator","true"),he.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",he.appendChild(Re);let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id="wrapper-typing-indicator",Ft.setAttribute("data-wrapper-id","typing-indicator"),Ft.appendChild(he),b.appendChild(Ft)}}if(!Rr&&u.length>0){let P=u[u.length-1],De={config:r,lastMessage:P,messageCount:u.length},Re=s.find($t=>$t.renderIdleIndicator),he=null;if(Re!=null&&Re.renderIdleIndicator&&(he=Re.renderIdleIndicator(De)),he===null&&((Ye=r.loadingIndicator)!=null&&Ye.renderIdle)&&(he=r.loadingIndicator.renderIdle(De)),he){let $t=document.createElement("div"),Ft=((xt=r.loadingIndicator)==null?void 0:xt.showBubble)!==!1;$t.className=Ft?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),$t.setAttribute("data-idle-indicator","true"),$t.appendChild(he);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild($t),b.appendChild(Jt)}}if($i(l,b),de.length>0)for(let{messageId:P,fingerprint:De,bubble:Re}of de){let he=l.querySelector(`#wrapper-${P}`);he&&Re!==null&&(he.replaceChildren(Re),he.setAttribute("data-bubble-fp",De),Gr.set(P,De))}if(Gr.size>0)for(let P of Gr.keys())F.has(P)||Gr.delete(P);if(Z.length>0)for(let{messageId:P,fingerprint:De,bubble:Re}of Z){let he=l.querySelector(`#wrapper-${P}`);he&&Re!==null&&(he.replaceChildren(Re),he.setAttribute("data-bubble-fp",De),Hr.set(P,De))}if(Hr.size>0)for(let P of Hr.keys())F.has(P)||Hr.delete(P);if(Te.length>0)for(let{messageId:P,fingerprint:De,bubble:Re}of Te){let he=l.querySelector(`#wrapper-${P}`);he&&Re!==null&&(he.replaceChildren(Re),he.setAttribute("data-bubble-fp",De),yr.set(P,De))}if(yr.size>0)for(let P of yr.keys())F.has(P)||yr.delete(P)},bo=(l,u,h)=>{si(l,u,h),uo()},xo=null,ai=()=>{var h;if(xo)return;let l=b=>{let T=b.composedPath();T.includes(Oe)||nt&&T.includes(nt)||E(!1,"user")};xo=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},la=()=>{var u;if(!xo)return;((u=e.ownerDocument)!=null?u:document).removeEventListener("pointerdown",xo,!0),xo=null};ut.push(()=>la());let vo=null,ii=()=>{var h;if(vo)return;let l=b=>{b.key==="Escape"&&(b.isComposing||E(!1,"user"))};vo=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},ca=()=>{var u;if(!vo)return;((u=e.ownerDocument)!=null?u:document).removeEventListener("keydown",vo,!0),vo=null};ut.push(()=>ca());let wo=!1,da=new Set,Cs=()=>{var u,h,b,T;let l=(b=(h=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return l||((T=r.features)==null?void 0:T.streamAnimation)},qe=()=>{var ft,ct,Ie,Le;if(!N())return;let l=te.peekBanner,u=te.peekTextNode;if(!l||!u)return;if(L){l.classList.remove("persona-pill-peek--visible");return}let h=(ft=_==null?void 0:_.getMessages())!=null?ft:[],b;for(let Ve=h.length-1;Ve>=0;Ve--){let Ye=h[Ve];if(Ye.role==="assistant"&&Ye.content){b=Ye;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let T=b.content,W=!!b.streaming,q=Cs(),F=Vi(q),R=F.type!=="none"?Ha(F.type,q==null?void 0:q.plugins):null,ce=((ct=R==null?void 0:R.isAnimating)==null?void 0:ct.call(R,b))===!0,de=R!==null&&(W||ce);de&&R&&!da.has(R.name)&&(oc(R,e),da.add(R.name));let Z=de&&(R!=null&&R.containerClass)?R.containerClass:null,we=(Ie=u.dataset.personaPeekStreamClass)!=null?Ie:null;we&&we!==Z&&(u.classList.remove(we),delete u.dataset.personaPeekStreamClass),Z&&we!==Z&&(u.classList.add(Z),u.dataset.personaPeekStreamClass=Z),de?(u.style.setProperty("--persona-stream-step",`${F.speed}ms`),u.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Fe=de?Ki(T,F.buffer,R,b,W):T;if(de&&F.placeholder==="skeleton"&&W&&(!Fe||!Fe.trim())){let Ve=document.createElement("div"),Ye=Da();Ye.classList.add("persona-pill-peek__skeleton"),Ve.appendChild(Ye),$i(u,Ve)}else{let Ve=Math.max(0,Fe.length-100),Ye=Fe.length>100?Fe.slice(-100):Fe,xt=_r(Ye);if(!de||!R){let P=Fe.length>100?`\u2026${Ye}`:Ye;u.textContent!==P&&(u.textContent=P)}else{let P=xt;(R.wrap==="char"||R.wrap==="word")&&(P=Ba(xt,R.wrap,`peek-${b.id}`,{skipTags:R.skipTags,startIndex:Ve}));let De=document.createElement("div");if(De.innerHTML=P,R.useCaret&&Ye.length>0){let Re=Gi(),he=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),$t=he[he.length-1];$t!=null&&$t.parentNode?$t.parentNode.insertBefore(Re,$t.nextSibling):De.appendChild(Re)}$i(u,De),(Le=R.onAfterRender)==null||Le.call(R,{container:u,bubble:l,messageId:b.id,message:b,speed:F.speed,duration:F.duration})}}let ze=Rr||wo;l.classList.toggle("persona-pill-peek--visible",ze)};if(N()){let l=te.peekBanner;if(l){let b=T=>{T.preventDefault(),T.stopPropagation(),E(!0,"user")};l.addEventListener("pointerdown",b),ut.push(()=>{l.removeEventListener("pointerdown",b)})}let u=()=>{wo||(wo=!0,qe())},h=()=>{wo&&(wo=!1,qe())};fe.addEventListener("pointerenter",u),fe.addEventListener("pointerleave",h),ut.push(()=>{fe.removeEventListener("pointerenter",u),fe.removeEventListener("pointerleave",h)}),nt&&(nt.addEventListener("pointerenter",u),nt.addEventListener("pointerleave",h),ut.push(()=>{nt.removeEventListener("pointerenter",u),nt.removeEventListener("pointerleave",h)}))}let C=l=>{var we,Fe,Te,it,ze,ft,ct,Ie;let u=(Fe=(we=r.launcher)==null?void 0:we.composerBar)!=null?Fe:{},h=(Te=u.expandedSize)!=null?Te:"anchored",b=(it=u.bottomOffset)!=null?it:"16px",T=u.collapsedMaxWidth,W=(ze=u.expandedMaxWidth)!=null?ze:"880px",q=(ft=u.expandedTopOffset)!=null?ft:"5vh",F=(ct=u.modalMaxWidth)!=null?ct:"880px",R=(Ie=u.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",ce="calc(100vw - 32px)",de="var(--persona-pill-area-height, 80px)",Z=Oe.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",nt){let Le=nt.style;Le.bottom=b,Le.width=T!=null?T:""}if(l&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=F,Z.maxWidth=ce,Z.maxHeight=R,Z.height=R;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${b} + ${de})`,Z.top=q,Z.width=W,Z.maxWidth=ce}},$=()=>{var R,ce,de,Z,we,Fe,Te,it;if(!O())return;if(N()){let ft=(de=((ce=(R=r.launcher)==null?void 0:R.composerBar)!=null?ce:{}).expandedSize)!=null?de:"anchored",ct=L?"expanded":"collapsed";Oe.dataset.state=ct,Oe.dataset.expandedSize=ft,nt&&(nt.dataset.state=ct,nt.dataset.expandedSize=ft),Oe.style.removeProperty("display"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),C(L),ge.style.display=L?"flex":"none",xe(),L?(ai(),ii()):(la(),ca()),qe();return}let l=un(r),u=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Fe=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Fe:640,b=(it=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?it:!0,T=u.innerWidth<=h,W=b&&T&&M,q=nr(r).reveal;L?(Oe.style.removeProperty("display"),Oe.style.display=l?"flex":"",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0"),fe.classList.add("persona-scale-100","persona-opacity-100"),rn?rn.element.style.display="none":fn&&(fn.style.display="none")):(l?l&&(q==="overlay"||q==="push")&&!W?(Oe.style.removeProperty("display"),Oe.style.display="flex",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.setProperty("display","none","important"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.display="",Oe.classList.add("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100"),fe.classList.add("persona-scale-95","persona-opacity-0")),rn?rn.element.style.display=l?"none":"":fn&&(fn.style.display=l?"none":""))},E=(l,u="user")=>{var W,q;if(!O()||L===l)return;let h=L;L=l,$();let b=(()=>{var Te,it,ze,ft,ct,Ie,Le,Ve,Ye,xt;let F=(it=(Te=r.launcher)==null?void 0:Te.sidebarMode)!=null?it:!1,R=(ze=e.ownerDocument.defaultView)!=null?ze:window,ce=(ct=(ft=r.launcher)==null?void 0:ft.mobileFullscreen)!=null?ct:!0,de=(Le=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Le:640,Z=R.innerWidth<=de,we=un(r)&&ce&&Z,Fe=N()&&((xt=(Ye=(Ve=r.launcher)==null?void 0:Ve.composerBar)==null?void 0:Ye.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return F||ce&&Z&&M||we||Fe})();if(L&&b){if(!nn){let F=e.getRootNode(),R=F instanceof ShadowRoot?F.host:e.closest(".persona-host");R&&(nn=sc(R,(q=(W=r.launcher)==null?void 0:W.zIndex)!=null?q:kn))}gn||(gn=ac(e.ownerDocument))}else L||(nn==null||nn(),nn=null,gn==null||gn(),gn=null);L&&(pa(),at()==="follow"?Nr(!0):aa());let T={open:L,source:u,timestamp:Date.now()};L&&!h?o.emit("widget:opened",T):!L&&h&&o.emit("widget:closed",T),o.emit("widget:state",{open:L,launcherEnabled:M,voiceActive:yt.active,streaming:_.isStreaming()})},X=l=>{Ln(l?"stop":"send"),V&&(V.disabled=l),jo.buttons.forEach(u=>{u.disabled=l}),$e.dataset.personaComposerStreaming=l?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},se=()=>{yt.active||Pe&&Pe.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>se(),200)});let J=()=>{var h,b,T,W,q,F,R,ce,de,Z,we;Tr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",U.textContent=(W=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",Pe.placeholder=(F=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?F:"How can I help...";let l=Me.querySelector("[data-persona-intro-card]");if(l){let Fe=((R=r.copy)==null?void 0:R.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(Me.classList.remove("persona-gap-3"),Me.classList.add("persona-gap-6")):(Me.classList.remove("persona-gap-6"),Me.classList.add("persona-gap-3"))}!((de=(ce=r.sendButton)==null?void 0:ce.useIcon)!=null&&de)&&!(_!=null&&_.isStreaming())&&(Ge.textContent=(we=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?we:"Send"),Pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(u=>({...u,sessionId:l}))}});let Ee=null,je=()=>{Ee==null&&(Ee=setInterval(()=>{let l=Ze.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Ee),Ee=null;return}let u=Date.now();l.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=wi(u-b))})},100))};_=new _s(r,{onMessagesChanged(l){var b;bo(Ze,l,ke),je(),gs(l),Nr(!Rr),oi(l);let u=[...l].reverse().find(T=>T.role==="user");l.length===0&&zo(),!hs||qo?(hs=!0,ys=(b=u==null?void 0:u.id)!=null?b:null):u&&u.id!==ys&&(ys=u.id,ri(u.id));let h=yt.lastUserMessageId;u&&u.id!==h&&(yt.lastUserMessageId=u.id,o.emit("user:message",u)),yt.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),vs(l),qe()},onStatusChanged(l){var b;let u=(b=r.statusIndicator)!=null?b:{};tt(mn,(T=>{var W,q,F,R;return T==="idle"?(W=u.idleText)!=null?W:Mn.idle:T==="connecting"?(q=u.connectingText)!=null?q:Mn.connecting:T==="connected"?(F=u.connectedText)!=null?F:Mn.connected:T==="error"?(R=u.errorText)!=null?R:Mn.error:Mn[T]})(l),u,l)},onStreamingChanged(l){Rr=l,X(l),_&&bo(Ze,_.getMessages(),ke),l||Nr(!0),qe()},onVoiceStatusChanged(l){var u,h;if(o.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Xr(),As();break;case"processing":Xr(),Xf();break;case"speaking":Xr(),Yf();break;default:l==="idle"&&_.isBargeInActive()?(Xr(),As(),V==null||V.setAttribute("aria-label","End voice session")):(yt.active=!1,Xr(),lr("system"),$n());break}},onArtifactsState(l){Vn=l,Jn(),vs()}}),Et.current=_;let lt=null;if(_.onReadAloudChange((l,u)=>{var T;co=l,po=u,uo();let h=l!=null?l:lt;l&&(lt=l);let b=h&&(T=_.getMessages().find(W=>W.id===h))!=null?T:null;o.emit("message:read-aloud",{messageId:h,message:b,state:u,timestamp:Date.now()}),u==="idle"&&(lt=null)}),hs=!0,((Kd=(Vd=r.voiceRecognition)==null?void 0:Vd.provider)==null?void 0:Kd.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&_.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(pe||r.onSSEEvent)&&_.setSSEEventCallback((l,u)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,u),me==null||me.processEvent(l,u),pe==null||pe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),c&&c.then(l=>{var u,h,b;if(l){if(l.metadata&&(d=Ac(l.metadata),A.syncFromMetadata()),(u=l.messages)!=null&&u.length){qo=!0;try{_.hydrateMessages(l.messages)}finally{qo=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let ot=()=>{var u,h,b;!N()||L||!((b=(h=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||E(!0,"auto")},Bt=l=>{var T;if(l.preventDefault(),_.isStreaming()){_.cancel(),me==null||me.reset(),K==null||K.update();return}let u=Pe.value.trim(),h=(T=vt==null?void 0:vt.hasAttachments())!=null?T:!1;if(!u&&!h)return;ot();let b;h&&(b=[],b.push(...vt.getContentParts()),u&&b.push(Ea(u))),Pe.value="",Pe.style.height="auto",Mt(),_.sendMessage(u,{contentParts:b}),h&&vt.clearAttachments()},qt=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},cn={...ji},St=!1,Mt=()=>{cn={...ji}},xn=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var u;return(u=l.content)!=null?u:""}).filter(l=>l.length>0),Wn=l=>{if(!Pe)return;St=!0,Pe.value=l,Pe.dispatchEvent(new Event("input",{bubbles:!0})),St=!1;let u=Pe.value.length;Pe.setSelectionRange(u,u)},Sn=()=>{St||Mt()},en=l=>{if(Pe){if(qt()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let u=Pe.selectionStart===0&&Pe.selectionEnd===0,h=mg({direction:l.key==="ArrowUp"?"up":"down",history:xn(),currentValue:Pe.value,atStart:u,state:cn});if(cn=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Wn(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Mt(),l.preventDefault(),Ge.click()}}},cr=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(ge)&&(_.cancel(),me==null||me.reset(),K==null||K.update(),Mt(),l.preventDefault(),l.stopImmediatePropagation())},jc=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!vt)return;let u=Db(l.clipboardData);u.length!==0&&(l.preventDefault(),await vt.handleFiles(u))},dr=null,Or=!1,Ss=null,gt=null,Uc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,li=(l="user")=>{var W,q,F,R,ce,de,Z;if(Or||_.isStreaming())return;let u=Uc();if(!u)return;dr=new u;let b=(q=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?q:2e3;dr.continuous=!0,dr.interimResults=!0,dr.lang="en-US";let T=Pe.value;dr.onresult=we=>{let Fe="",Te="";for(let ze=0;ze<we.results.length;ze++){let ft=we.results[ze],ct=ft[0].transcript;ft.isFinal?Fe+=ct+" ":Te=ct}let it=T+Fe+Te;Pe.value=it,Ss&&clearTimeout(Ss),(Fe||Te)&&(Ss=window.setTimeout(()=>{let ze=Pe.value.trim();ze&&dr&&Or&&(Co(),Pe.value="",Pe.style.height="auto",_.sendMessage(ze,{viaVoice:!0}))},b))},dr.onerror=we=>{we.error!=="no-speech"&&Co()},dr.onend=()=>{if(Or){let we=Pe.value.trim();we&&we!==T.trim()&&(Pe.value="",Pe.style.height="auto",_.sendMessage(we,{viaVoice:!0})),Co()}};try{if(dr.start(),Or=!0,yt.active=!0,l!=="system"&&(yt.manuallyDeactivated=!1),lr(l),$n(),V){let we=(F=r.voiceRecognition)!=null?F:{};gt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(R=we.iconName)!=null?R:"mic",iconSize:parseFloat((Z=(de=we.iconSize)!=null?de:(ce=r.sendButton)==null?void 0:ce.size)!=null?Z:"40")||24};let Fe=we.recordingBackgroundColor,Te=we.recordingIconColor,it=we.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let ze=V.querySelector("svg");ze&&ze.setAttribute("stroke",Te)}it&&(V.style.borderColor=it),V.setAttribute("aria-label","Stop voice recognition")}}catch{Co("system")}},Co=(l="user")=>{if(Or){if(Or=!1,Ss&&(clearTimeout(Ss),Ss=null),dr){try{dr.stop()}catch{}dr=null}if(yt.active=!1,lr(l),$n(),V){if(V.classList.remove("persona-voice-recording"),gt){V.style.backgroundColor=gt.backgroundColor,V.style.color=gt.color,V.style.borderColor=gt.borderColor;let u=V.querySelector("svg");u&&u.setAttribute("stroke",gt.color||"currentColor"),gt=null}V.setAttribute("aria-label","Start voice recognition")}}},Qf=(l,u)=>{var ct,Ie,Le,Ve,Ye,xt,P,De,Re;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((ct=l==null?void 0:l.provider)==null?void 0:ct.type)==="runtype",T=((Ie=l==null?void 0:l.provider)==null?void 0:Ie.type)==="custom";if(!(h||b||T))return null;let q=y("div","persona-send-button-wrapper"),F=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let R=(Le=l==null?void 0:l.iconName)!=null?Le:"mic",ce=(Ve=u==null?void 0:u.size)!=null?Ve:"40px",de=(Ye=l==null?void 0:l.iconSize)!=null?Ye:ce,Z=parseFloat(de)||24,we=(xt=l==null?void 0:l.backgroundColor)!=null?xt:u==null?void 0:u.backgroundColor,Fe=(P=l==null?void 0:l.iconColor)!=null?P:u==null?void 0:u.textColor;F.style.width=de,F.style.height=de,F.style.minWidth=de,F.style.minHeight=de,F.style.fontSize="18px",F.style.lineHeight="1",Fe?F.style.color=Fe:F.style.color="var(--persona-text, #111827)";let it=ve(R,Z,Fe||"currentColor",1.5);it?F.appendChild(it):F.textContent="\u{1F3A4}",we?F.style.backgroundColor=we:F.style.backgroundColor="",l!=null&&l.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l!=null&&l.borderColor&&(F.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),q.appendChild(F);let ze=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((Re=l==null?void 0:l.showTooltip)!=null?Re:!1)&&ze){let he=y("div","persona-send-button-tooltip");he.textContent=ze,q.appendChild(he)}return{micButton:F,micButtonWrapper:q}},El=()=>{var u,h,b,T,W;if(!V||gt)return;let l=(u=r.voiceRecognition)!=null?u:{};gt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((W=(T=l.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?W:"40")||24}},Ml=(l,u)=>{var W,q,F,R,ce;if(!V)return;let h=V.querySelector("svg");h&&h.remove();let b=(ce=gt==null?void 0:gt.iconSize)!=null?ce:parseFloat((R=(F=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?F:(q=r.sendButton)==null?void 0:q.size)!=null?R:"40")||24,T=ve(l,b,u,1.5);T&&V.appendChild(T)},ci=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},As=()=>{var T;if(!V)return;El();let l=(T=r.voiceRecognition)!=null?T:{},u=l.recordingBackgroundColor,h=l.recordingIconColor,b=l.recordingBorderColor;if(ci(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=u!=null?u:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let W=V.querySelector("svg");W&&W.setAttribute("stroke",h)}b&&(V.style.borderColor=b),V.setAttribute("aria-label","Stop voice recognition")},Xf=()=>{var F,R,ce,de,Z,we,Fe,Te;if(!V)return;El();let l=(F=r.voiceRecognition)!=null?F:{},u=_.getVoiceInterruptionMode(),h=(R=l.processingIconName)!=null?R:"loader",b=(de=(ce=l.processingIconColor)!=null?ce:gt==null?void 0:gt.color)!=null?de:"",T=(we=(Z=l.processingBackgroundColor)!=null?Z:gt==null?void 0:gt.backgroundColor)!=null?we:"",W=(Te=(Fe=l.processingBorderColor)!=null?Fe:gt==null?void 0:gt.borderColor)!=null?Te:"";ci(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=T,V.style.borderColor=W;let q=b||"currentColor";V.style.color=q,Ml(h,q),V.setAttribute("aria-label","Processing voice input"),u==="none"&&(V.style.cursor="default")},Yf=()=>{var ce,de,Z,we,Fe,Te,it,ze,ft,ct,Ie,Le;if(!V)return;El();let l=(ce=r.voiceRecognition)!=null?ce:{},u=_.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",b=(de=l.speakingIconName)!=null?de:h,T=(Te=l.speakingIconColor)!=null?Te:u==="barge-in"?(we=(Z=l.recordingIconColor)!=null?Z:gt==null?void 0:gt.color)!=null?we:"":(Fe=gt==null?void 0:gt.color)!=null?Fe:"",W=(ft=l.speakingBackgroundColor)!=null?ft:u==="barge-in"?(it=l.recordingBackgroundColor)!=null?it:"var(--persona-voice-recording-bg, #ef4444)":(ze=gt==null?void 0:gt.backgroundColor)!=null?ze:"",q=(Le=l.speakingBorderColor)!=null?Le:u==="barge-in"?(ct=l.recordingBorderColor)!=null?ct:"":(Ie=gt==null?void 0:gt.borderColor)!=null?Ie:"";ci(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=W,V.style.borderColor=q;let F=T||"currentColor";V.style.color=F,Ml(b,F);let R=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",R),u==="none"&&(V.style.cursor="default"),u==="barge-in"&&V.classList.add("persona-voice-recording")},Xr=()=>{var l,u,h;V&&(ci(),gt&&(V.style.backgroundColor=(l=gt.backgroundColor)!=null?l:"",V.style.color=(u=gt.color)!=null?u:"",V.style.borderColor=(h=gt.borderColor)!=null?h:"",Ml(gt.iconName,gt.color||"currentColor"),gt=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},di=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=_.getVoiceStatus(),b=_.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),lr("user"),Xr()});return}_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),yt.manuallyDeactivated=!_.isVoiceActive(),$n(),lr("user"),_.isVoiceActive()?As():Xr()});return}if(Or){let h=Pe.value.trim();yt.manuallyDeactivated=!0,$n(),Co("user"),h&&(Pe.value="",Pe.style.height="auto",_.sendMessage(h))}else yt.manuallyDeactivated=!1,$n(),li("user")};qn=di,V&&(V.addEventListener("click",di),ut.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Xr()):Co("system"),V&&V.removeEventListener("click",di)}));let Zf=o.on("assistant:complete",()=>{Zs&&(yt.active||yt.manuallyDeactivated||Zs==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!yt.active&&!yt.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("auto"),_.isVoiceActive()&&As()}):li("auto"))},600))});ut.push(Zf);let eh=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});ut.push(eh);let qc=()=>{E(!L,"user")},rn=null,fn=null;if(M&&!N()){let{instance:l,element:u}=pc({config:r,plugins:s,onToggle:qc});rn=l,l||(fn=u)}rn?e.appendChild(rn.element):fn&&e.appendChild(fn),$(),gs(),J(),X(_.isStreaming()),at()==="follow"?Nr(!0):aa(),Ya(),D&&(!M||N()?setTimeout(()=>se(),0):L&&setTimeout(()=>se(),200));let pa=()=>{var R,ce,de,Z,we,Fe,Te,it,ze,ft,ct,Ie,Le,Ve,Ye,xt,P,De,Re,he,$t,Ft;if(N()){Fn(),$();return}let l=un(r),u=(ce=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?ce:!1,h=l||u||((Z=(de=r.launcher)==null?void 0:de.fullHeight)!=null?Z:!1),b=(we=e.ownerDocument.defaultView)!=null?we:window,T=(Te=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Te:!0,W=(ze=(it=r.launcher)==null?void 0:it.mobileBreakpoint)!=null?ze:640,q=b.innerWidth<=W,F=T&&q&&M;try{if(F){xe(),Ro(e,r);return}if(I&&(I=!1,xe(),Ro(e,r)),!M&&!l){fe.style.height="",fe.style.width="";return}if(!u&&!l){let Jt=(ct=(ft=r==null?void 0:r.launcher)==null?void 0:ft.width)!=null?ct:r==null?void 0:r.launcherWidth,wt=Jt!=null?Jt:tr;fe.style.width=wt,fe.style.maxWidth=wt}if(Lr(),!h){let Jt=b.innerHeight,wt=64,zt=(Le=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Le:0,Yn=Math.max(200,Jt-wt),on=Math.min(640,Yn),et=Math.max(200,on-zt);fe.style.height=`${et}px`}}finally{if(Fn(),$(),L&&M){let wt=((Ve=e.ownerDocument.defaultView)!=null?Ve:window).innerWidth<=((xt=(Ye=r.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?xt:640),zt=(De=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?De:!1,Yn=(he=(Re=r.launcher)==null?void 0:Re.mobileFullscreen)!=null?he:!0,on=un(r)&&Yn&&wt,et=zt||Yn&&wt&&M||on;if(et&&!gn){let It=e.getRootNode(),pn=It instanceof ShadowRoot?It.host:e.closest(".persona-host");pn&&!nn&&(nn=sc(pn,(Ft=($t=r.launcher)==null?void 0:$t.zIndex)!=null?Ft:kn)),gn=ac(e.ownerDocument)}else et||(nn==null||nn(),nn=null,gn==null||gn(),gn=null)}}};pa();let zc=(Gd=e.ownerDocument.defaultView)!=null?Gd:window;if(zc.addEventListener("resize",pa),ut.push(()=>zc.removeEventListener("resize",pa)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Fn()});l.observe($e),ut.push(()=>l.disconnect())}Xn=Me.scrollTop;let Vc=oo(Me),th=()=>{let l=Me.getRootNode(),u=typeof l.getSelection=="function"?l.getSelection():null;return u!=null?u:Me.ownerDocument.getSelection()},kl=()=>xg(th(),Me),Kc=()=>{let l=Me.scrollTop,u=oo(Me),h=u<Vc;if(Vc=u,at()!=="follow"){Xn=l,jn();return}let{action:b,nextLastScrollTop:T}=qi({following:Qn.isFollowing(),currentScrollTop:l,lastScrollTop:Xn,nearBottom:ls(Me,bs),userScrollThreshold:Qa,isAutoScrolling:xr||Uo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Xn=T,b==="resume"){kl()||Dr();return}b==="pause"&&ws()};if(Me.addEventListener("scroll",Kc,{passive:!0}),ut.push(()=>Me.removeEventListener("scroll",Kc)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{ni()});l.observe(Ze),l.observe(Me),ut.push(()=>l.disconnect())}let Gc=()=>{at()==="follow"&&Qn.isFollowing()&&kl()&&ws()},Jc=Me.ownerDocument;Jc.addEventListener("selectionchange",Gc),ut.push(()=>{Jc.removeEventListener("selectionchange",Gc)});let Qc=l=>{if(at()!=="follow")return;let u=zi({following:Qn.isFollowing(),deltaY:l.deltaY,nearBottom:ls(Me,bs),resumeWhenNearBottom:!0});u==="pause"?ws():u==="resume"&&!kl()&&Dr()};Me.addEventListener("wheel",Qc,{passive:!0}),ut.push(()=>Me.removeEventListener("wheel",Qc)),pt.addEventListener("click",()=>{zo(),Me.scrollTop=Me.scrollHeight,Xn=Me.scrollTop,Dr(),Nr(!0),jn()}),ut.push(()=>pt.remove()),ut.push(()=>{ta(),zo()});let Xc=()=>{G&&(Ir&&(G.removeEventListener("click",Ir),Ir=null),O()?(G.style.display="",Ir=()=>{E(!1,"user")},G.addEventListener("click",Ir)):G.style.display="none")};Xc(),(()=>{let{clearChatButton:l}=te;l&&l.addEventListener("click",()=>{_.clearMessages(),Wr.clear(),Dr(),ko(te.composerOverlay);try{localStorage.removeItem(Xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Xs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},A.syncFromMetadata(),pe==null||pe.clear(),me==null||me.reset(),K==null||K.update()})})(),Wt&&Wt.addEventListener("submit",Bt),Pe==null||Pe.addEventListener("keydown",en),Pe==null||Pe.addEventListener("input",Sn),Pe==null||Pe.addEventListener("paste",jc);let Yc=(Jd=e.ownerDocument)!=null?Jd:document;Yc.addEventListener("keydown",cr,!0);let Zc="persona-attachment-drop-active",ua=0,Ll=()=>{ua=0,ge.classList.remove(Zc)},Ts=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&vt!==null},ed=l=>{!yl(l.dataTransfer)||!Ts()||(ua++,ua===1&&ge.classList.add(Zc))},td=l=>{!yl(l.dataTransfer)||!Ts()||(ua--,ua<=0&&Ll())},nd=l=>{!yl(l.dataTransfer)||!Ts()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},rd=l=>{var h;if(!yl(l.dataTransfer)||!Ts())return;l.preventDefault(),l.stopPropagation(),Ll();let u=Array.from((h=l.dataTransfer.files)!=null?h:[]);u.length!==0&&vt.handleFiles(u)},So=!0;ge.addEventListener("dragenter",ed,So),ge.addEventListener("dragleave",td,So),e.addEventListener("dragover",nd,So),e.addEventListener("drop",rd,So);let pi=e.ownerDocument,od=l=>{Ts()&&l.preventDefault()},sd=l=>{Ts()&&l.preventDefault()};pi.addEventListener("dragover",od),pi.addEventListener("drop",sd),ut.push(()=>{Wt&&Wt.removeEventListener("submit",Bt),Pe==null||Pe.removeEventListener("keydown",en),Pe==null||Pe.removeEventListener("input",Sn),Pe==null||Pe.removeEventListener("paste",jc),Yc.removeEventListener("keydown",cr,!0)}),ut.push(()=>{ge.removeEventListener("dragenter",ed,So),ge.removeEventListener("dragleave",td,So),e.removeEventListener("dragover",nd,So),e.removeEventListener("drop",rd,So),pi.removeEventListener("dragover",od),pi.removeEventListener("drop",sd),Ll()}),ut.push(()=>{_.cancel()}),rn?ut.push(()=>{rn==null||rn.destroy()}):fn&&ut.push(()=>{fn==null||fn.remove()});let dn={update(l){var Tn,Hn,Fr,vn,Bn,Dn,Qo,ma,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Sp,Ap,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Qp,Xp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Su,Au,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Nu,Ou,Fu,_u,$u,ju,Uu,qu,zu,Vu,Ku,Gu,Ju,Qu,Xu,Yu,Zu,em;let u=r.toolCall,h=r.messageActions,b=(Tn=r.layout)==null?void 0:Tn.messages,T=r.colorScheme,W=r.loadingIndicator,q=r.iterationDisplay,F=(Hn=r.features)==null?void 0:Hn.showReasoning,R=(Fr=r.features)==null?void 0:Fr.showToolCalls,ce=(vn=r.features)==null?void 0:vn.toolCallDisplay,de=(Bn=r.features)==null?void 0:Bn.reasoningDisplay;r={...r,...l},xe(),Ro(e,r),ll(e,r),cl(e,r),Jn(),r.colorScheme!==T&&Ys();let Z=qa.getForInstance(r.plugins);s.length=0,s.push(...Z),M=(Qo=(Dn=r.launcher)==null?void 0:Dn.enabled)!=null?Qo:!0,B=(np=(ma=r.launcher)==null?void 0:ma.autoExpand)!=null?np:!1,Ke=(op=(rp=r.features)==null?void 0:rp.showReasoning)!=null?op:!0,Ce=(ap=(sp=r.features)==null?void 0:sp.showToolCalls)!=null?ap:!0,Ne=(lp=(ip=r.features)==null?void 0:ip.scrollToBottom)!=null?lp:{};let we=at();be=(dp=(cp=r.features)==null?void 0:cp.scrollBehavior)!=null?dp:{},we!==at()&&(zo(),Dr()),Er(),jn();let Fe=We;if(We=(up=(pp=r.features)==null?void 0:pp.showEventStreamToggle)!=null?up:!1,We&&!Fe){if(pe||(Q=new ja(ue),pe=new $a(ne,Q),me=me!=null?me:new Ua,Q.open().then(()=>pe==null?void 0:pe.restore()).catch(()=>{}),_.setSSEEventCallback((re,kt)=>{var Vt;(Vt=r.onSSEEvent)==null||Vt.call(r,re,kt),me==null||me.processEvent(re,kt),pe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(kt)})})),!bt&&Ue){let re=(gp=(mp=r.features)==null?void 0:mp.eventStream)==null?void 0:gp.classNames,kt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(re!=null&&re.toggleButton?" "+re.toggleButton:"");bt=y("button",kt),bt.style.width="28px",bt.style.height="28px",bt.style.color=On.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let Vt=ve("activity","18px","currentColor",1.5);Vt&&bt.appendChild(Vt);let dt=te.clearChatButtonWrapper,Rt=te.closeButtonWrapper,yn=dt||Rt;yn&&yn.parentNode===Ue?Ue.insertBefore(bt,yn):Ue.appendChild(bt),bt.addEventListener("click",()=>{ae?hr():Ur()})}}else!We&&Fe&&(hr(),bt&&(bt.remove(),bt=null),pe==null||pe.clear(),Q==null||Q.destroy(),pe=null,Q=null,me==null||me.reset(),me=null);if(((fp=r.launcher)==null?void 0:fp.enabled)===!1&&rn&&(rn.destroy(),rn=null),((hp=r.launcher)==null?void 0:hp.enabled)===!1&&fn&&(fn.remove(),fn=null),((yp=r.launcher)==null?void 0:yp.enabled)!==!1&&!rn&&!fn){let{instance:re,element:kt}=pc({config:r,plugins:s,onToggle:qc});rn=re,re||(fn=kt),e.appendChild(kt)}rn&&rn.update(r),Xe&&((bp=r.launcher)==null?void 0:bp.title)!==void 0&&(Xe.textContent=r.launcher.title),rt&&((xp=r.launcher)==null?void 0:xp.subtitle)!==void 0&&(rt.textContent=r.launcher.subtitle);let Te=(vp=r.layout)==null?void 0:vp.header;if((Te==null?void 0:Te.layout)!==S&&Ue){let re=Te?qs(r,Te,{showClose:O(),onClose:()=>E(!1,"user")}):so({config:r,showClose:O(),onClose:()=>E(!1,"user")});Qe.replaceHeader(re),Ue=Qe.header.element,ye=Qe.header.iconHolder,Xe=Qe.header.headerTitle,rt=Qe.header.headerSubtitle,G=Qe.header.closeButton,S=Te==null?void 0:Te.layout}else if(Te&&(ye&&(ye.style.display=Te.showIcon===!1?"none":""),Xe&&(Xe.style.display=Te.showTitle===!1?"none":""),rt&&(rt.style.display=Te.showSubtitle===!1?"none":""),G&&(G.style.display=Te.showCloseButton===!1?"none":""),te.clearChatButtonWrapper)){let re=Te.showClearChat;if(re!==void 0){te.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:kt}=te;kt&&!kt.classList.contains("persona-absolute")&&(re?kt.classList.remove("persona-ml-auto"):kt.classList.add("persona-ml-auto"))}}let ze=((wp=r.layout)==null?void 0:wp.showHeader)!==!1;Ue&&(Ue.style.display=ze?"":"none");let ft=((Cp=r.layout)==null?void 0:Cp.showFooter)!==!1;$e&&($e.style.display=ft?"":"none"),Fn(),jn(),M!==H?M?E(B,"auto"):(L=!0,$()):B!==k&&E(B,"auto"),k=B,H=M,pa(),Xc();let Le=JSON.stringify(l.toolCall)!==JSON.stringify(u),Ve=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ye=JSON.stringify((Sp=r.layout)==null?void 0:Sp.messages)!==JSON.stringify(b),xt=((Ap=r.loadingIndicator)==null?void 0:Ap.render)!==(W==null?void 0:W.render)||((Tp=r.loadingIndicator)==null?void 0:Tp.renderIdle)!==(W==null?void 0:W.renderIdle)||((Ep=r.loadingIndicator)==null?void 0:Ep.showBubble)!==(W==null?void 0:W.showBubble),P=r.iterationDisplay!==q,De=((kp=(Mp=r.features)==null?void 0:Mp.showReasoning)!=null?kp:!0)!==(F!=null?F:!0)||((Pp=(Lp=r.features)==null?void 0:Lp.showToolCalls)!=null?Pp:!0)!==(R!=null?R:!0)||JSON.stringify((Ip=r.features)==null?void 0:Ip.toolCallDisplay)!==JSON.stringify(ce)||JSON.stringify((Rp=r.features)==null?void 0:Rp.reasoningDisplay)!==JSON.stringify(de);(Le||Ve||Ye||xt||P||De)&&_&&(fs++,bo(Ze,_.getMessages(),ke));let he=(Wp=r.launcher)!=null?Wp:{},$t=(Hp=he.headerIconHidden)!=null?Hp:!1,Ft=(Dp=(Bp=r.layout)==null?void 0:Bp.header)==null?void 0:Dp.showIcon,Jt=$t||Ft===!1,wt=he.headerIconName,zt=(Np=he.headerIconSize)!=null?Np:"48px";if(ye){let re=ge.querySelector(".persona-border-b-persona-divider"),kt=re==null?void 0:re.querySelector(".persona-flex-col");if(Jt)ye.style.display="none",re&&kt&&!re.contains(kt)&&re.insertBefore(kt,re.firstChild);else{if(ye.style.display="",ye.style.height=zt,ye.style.width=zt,re&&kt&&(re.contains(ye)?ye.nextSibling!==kt&&(ye.remove(),re.insertBefore(ye,kt)):re.insertBefore(ye,kt)),wt){let dt=parseFloat(zt)||24,Rt=ve(wt,dt*.6,"currentColor",1);Rt?ye.replaceChildren(Rt):ye.textContent=(Op=he.agentIconText)!=null?Op:"\u{1F4AC}"}else if(he.iconUrl){let dt=ye.querySelector("img");if(dt)dt.src=he.iconUrl,dt.style.height=zt,dt.style.width=zt;else{let Rt=document.createElement("img");Rt.src=he.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=zt,Rt.style.width=zt,ye.replaceChildren(Rt)}}else{let dt=ye.querySelector("svg"),Rt=ye.querySelector("img");(dt||Rt)&&ye.replaceChildren(),ye.textContent=(Fp=he.agentIconText)!=null?Fp:"\u{1F4AC}"}let Vt=ye.querySelector("img");Vt&&(Vt.style.height=zt,Vt.style.width=zt)}}let Yn=($p=(_p=r.layout)==null?void 0:_p.header)==null?void 0:$p.showTitle,on=(Up=(jp=r.layout)==null?void 0:jp.header)==null?void 0:Up.showSubtitle;if(Xe&&(Xe.style.display=Yn===!1?"none":""),rt&&(rt.style.display=on===!1?"none":""),G){((zp=(qp=r.layout)==null?void 0:qp.header)==null?void 0:zp.showCloseButton)===!1?G.style.display="none":G.style.display="";let kt=(Vp=he.closeButtonSize)!=null?Vp:"32px",Vt=(Kp=he.closeButtonPlacement)!=null?Kp:"inline";G.style.height=kt,G.style.width=kt;let{closeButtonWrapper:dt}=te,Rt=Vt==="top-right",yn=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Rt!==yn)if(dt.remove(),Rt)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ge.style.position="relative",ge.appendChild(dt);else{let mt=(Jp=(Gp=he.clearChat)==null?void 0:Gp.placement)!=null?Jp:"inline",bn=(Xp=(Qp=he.clearChat)==null?void 0:Qp.enabled)!=null?Xp:!0;dt.className=bn&&mt==="inline"?"":"persona-ml-auto";let Un=ge.querySelector(".persona-border-b-persona-divider");Un&&Un.appendChild(dt)}if(G.style.color=he.closeButtonColor||On.actionIconColor,he.closeButtonBackgroundColor?(G.style.backgroundColor=he.closeButtonBackgroundColor,G.classList.remove("hover:persona-bg-gray-100")):(G.style.backgroundColor="",G.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let mt=he.closeButtonBorderWidth||"0px",bn=he.closeButtonBorderColor||"transparent";G.style.border=`${mt} solid ${bn}`,G.classList.remove("persona-border-none")}else G.style.border="",G.classList.add("persona-border-none");he.closeButtonBorderRadius?(G.style.borderRadius=he.closeButtonBorderRadius,G.classList.remove("persona-rounded-full")):(G.style.borderRadius="",G.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(G.style.paddingLeft=he.closeButtonPaddingX,G.style.paddingRight=he.closeButtonPaddingX):(G.style.paddingLeft="",G.style.paddingRight=""),he.closeButtonPaddingY?(G.style.paddingTop=he.closeButtonPaddingY,G.style.paddingBottom=he.closeButtonPaddingY):(G.style.paddingTop="",G.style.paddingBottom="");let En=(Yp=he.closeButtonIconName)!=null?Yp:"x",wr=(Zp=he.closeButtonIconText)!=null?Zp:"\xD7";G.innerHTML="";let Nn=ve(En,"28px","currentColor",1);Nn?G.appendChild(Nn):G.textContent=wr;let tn=(eu=he.closeButtonTooltipText)!=null?eu:"Close chat",er=(tu=he.closeButtonShowTooltip)!=null?tu:!0;if(G.setAttribute("aria-label",tn),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),er&&tn)){let mt=null,bn=()=>{if(mt||!G)return;let Xo=G.ownerDocument,ga=Xo.body;if(!ga)return;mt=$r(Xo,"div","persona-clear-chat-tooltip"),mt.textContent=tn;let fa=$r(Xo,"div");fa.className="persona-clear-chat-tooltip-arrow",mt.appendChild(fa);let Yo=G.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(Wo),mt.style.left=`${Yo.left+Yo.width/2}px`,mt.style.top=`${Yo.top-8}px`,mt.style.transform="translate(-50%, -100%)",ga.appendChild(mt)},Un=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};dt.addEventListener("mouseenter",bn),dt.addEventListener("mouseleave",Un),G.addEventListener("focus",bn),G.addEventListener("blur",Un),dt._cleanupTooltip=()=>{Un(),dt&&(dt.removeEventListener("mouseenter",bn),dt.removeEventListener("mouseleave",Un)),G&&(G.removeEventListener("focus",bn),G.removeEventListener("blur",Un))}}}let{clearChatButton:et,clearChatButtonWrapper:It}=te;if(et){let re=(nu=he.clearChat)!=null?nu:{},kt=(ru=re.enabled)!=null?ru:!0,Vt=(su=(ou=r.layout)==null?void 0:ou.header)==null?void 0:su.showClearChat,dt=Vt!==void 0?Vt:kt,Rt=(au=re.placement)!=null?au:"inline";if(It){It.style.display=dt?"":"none";let{closeButtonWrapper:yn}=te;!N()&&yn&&!yn.classList.contains("persona-absolute")&&(dt?yn.classList.remove("persona-ml-auto"):yn.classList.add("persona-ml-auto"));let En=Rt==="top-right",wr=It.classList.contains("persona-absolute");if(!N()&&En!==wr&&dt){if(It.remove(),En)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",ge.style.position="relative",ge.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let tn=ge.querySelector(".persona-border-b-persona-divider"),er=te.closeButtonWrapper;tn&&er&&er.parentElement===tn?tn.insertBefore(It,er):tn&&tn.appendChild(It)}let Nn=te.closeButtonWrapper;Nn&&!Nn.classList.contains("persona-absolute")&&(En?Nn.classList.add("persona-ml-auto"):Nn.classList.remove("persona-ml-auto"))}}if(dt){if(!N()){let mt=(iu=re.size)!=null?iu:"32px";et.style.height=mt,et.style.width=mt}let yn=(lu=re.iconName)!=null?lu:"refresh-cw",En=(cu=re.iconColor)!=null?cu:"";et.style.color=En||On.actionIconColor,et.innerHTML="";let wr=N()?"14px":"20px",Nn=ve(yn,wr,"currentColor",2);if(Nn&&et.appendChild(Nn),re.backgroundColor?(et.style.backgroundColor=re.backgroundColor,et.classList.remove("hover:persona-bg-gray-100")):(et.style.backgroundColor="",et.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let mt=re.borderWidth||"0px",bn=re.borderColor||"transparent";et.style.border=`${mt} solid ${bn}`,et.classList.remove("persona-border-none")}else et.style.border="",et.classList.add("persona-border-none");re.borderRadius?(et.style.borderRadius=re.borderRadius,et.classList.remove("persona-rounded-full")):(et.style.borderRadius="",et.classList.add("persona-rounded-full")),re.paddingX?(et.style.paddingLeft=re.paddingX,et.style.paddingRight=re.paddingX):(et.style.paddingLeft="",et.style.paddingRight=""),re.paddingY?(et.style.paddingTop=re.paddingY,et.style.paddingBottom=re.paddingY):(et.style.paddingTop="",et.style.paddingBottom="");let tn=(du=re.tooltipText)!=null?du:"Clear chat",er=(pu=re.showTooltip)!=null?pu:!0;if(et.setAttribute("aria-label",tn),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),er&&tn)){let mt=null,bn=()=>{if(mt||!et)return;let Xo=et.ownerDocument,ga=Xo.body;if(!ga)return;mt=$r(Xo,"div","persona-clear-chat-tooltip"),mt.textContent=tn;let fa=$r(Xo,"div");fa.className="persona-clear-chat-tooltip-arrow",mt.appendChild(fa);let Yo=et.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(Wo),mt.style.left=`${Yo.left+Yo.width/2}px`,mt.style.top=`${Yo.top-8}px`,mt.style.transform="translate(-50%, -100%)",ga.appendChild(mt)},Un=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};It.addEventListener("mouseenter",bn),It.addEventListener("mouseleave",Un),et.addEventListener("focus",bn),et.addEventListener("blur",Un),It._cleanupTooltip=()=>{Un(),It&&(It.removeEventListener("mouseenter",bn),It.removeEventListener("mouseleave",Un)),et&&(et.removeEventListener("focus",bn),et.removeEventListener("blur",Un))}}}}let pn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[za],ur=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[us.message,us.messageAndClick];A=Va({parsers:pn,handlers:ur,getSessionMetadata:g,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),ke=cf(r,A,oe),_.updateConfig(r),bo(Ze,_.getMessages(),ke),gs(),J(),X(_.isStreaming());let Zn=((uu=r.voiceRecognition)==null?void 0:uu.enabled)===!0,Vo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ko=((gu=(mu=r.voiceRecognition)==null?void 0:mu.provider)==null?void 0:gu.type)==="runtype";if(Zn&&(Vo||Ko))if(!V||!Ht){let re=Qf(r.voiceRecognition,r.sendButton);re&&(V=re.micButton,Ht=re.micButtonWrapper,Yt.insertBefore(Ht,wn),V.addEventListener("click",di),V.disabled=_.isStreaming())}else{let re=(fu=r.voiceRecognition)!=null?fu:{},kt=(hu=r.sendButton)!=null?hu:{},Vt=(yu=re.iconName)!=null?yu:"mic",dt=(bu=kt.size)!=null?bu:"40px",Rt=(xu=re.iconSize)!=null?xu:dt,yn=parseFloat(Rt)||24;V.style.width=Rt,V.style.height=Rt,V.style.minWidth=Rt,V.style.minHeight=Rt;let En=(wu=(vu=re.iconColor)!=null?vu:kt.textColor)!=null?wu:"currentColor";V.innerHTML="";let wr=ve(Vt,yn,En,2);wr?V.appendChild(wr):V.textContent="\u{1F3A4}";let Nn=(Cu=re.backgroundColor)!=null?Cu:kt.backgroundColor;Nn?V.style.backgroundColor=Nn:V.style.backgroundColor="",En?V.style.color=En:V.style.color="var(--persona-text, #111827)",re.borderWidth?(V.style.borderWidth=re.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),re.borderColor?V.style.borderColor=re.borderColor:V.style.borderColor="",re.paddingX?(V.style.paddingLeft=re.paddingX,V.style.paddingRight=re.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),re.paddingY?(V.style.paddingTop=re.paddingY,V.style.paddingBottom=re.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let tn=Ht==null?void 0:Ht.querySelector(".persona-send-button-tooltip"),er=(Su=re.tooltipText)!=null?Su:"Start voice recognition";if(((Au=re.showTooltip)!=null?Au:!1)&&er)if(tn)tn.textContent=er,tn.style.display="";else{let bn=document.createElement("div");bn.className="persona-send-button-tooltip",bn.textContent=er,Ht==null||Ht.insertBefore(bn,V)}else tn&&(tn.style.display="none");Ht.style.display="",V.disabled=_.isStreaming()}else V&&Ht&&(Ht.style.display="none",((Eu=(Tu=r.voiceRecognition)==null?void 0:Tu.provider)==null?void 0:Eu.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Or&&Co());if(((Mu=r.attachments)==null?void 0:Mu.enabled)===!0)if(!Ae||!le){let re=(ku=r.attachments)!=null?ku:{},Vt=(Pu=((Lu=r.sendButton)!=null?Lu:{}).size)!=null?Pu:"40px";Tt||(Tt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Tt.style.display="none",Wt.insertBefore(Tt,Pe)),_e||(_e=document.createElement("input"),_e.type="file",_e.accept=((Iu=re.allowedTypes)!=null?Iu:ro).join(","),_e.multiple=((Ru=re.maxFiles)!=null?Ru:4)>1,_e.style.display="none",_e.setAttribute("aria-label","Attach files"),Wt.insertBefore(_e,Pe)),Ae=y("div","persona-send-button-wrapper"),le=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",(Wu=re.buttonTooltipText)!=null?Wu:"Attach file");let dt=(Hu=re.buttonIconName)!=null?Hu:"paperclip",Rt=Vt,yn=parseFloat(Rt)||40,En=Math.round(yn*.6);le.style.width=Rt,le.style.height=Rt,le.style.minWidth=Rt,le.style.minHeight=Rt,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let wr=ve(dt,En,"currentColor",1.5);wr?le.appendChild(wr):le.textContent="\u{1F4CE}",le.addEventListener("click",er=>{er.preventDefault(),_e==null||_e.click()}),Ae.appendChild(le);let Nn=(Bu=re.buttonTooltipText)!=null?Bu:"Attach file",tn=y("div","persona-send-button-tooltip");tn.textContent=Nn,Ae.appendChild(tn),Gt.append(Ae),!vt&&_e&&Tt&&(vt=is.fromConfig(re),vt.setPreviewsContainer(Tt),_e.addEventListener("change",async()=>{vt&&(_e!=null&&_e.files)&&(await vt.handleFileSelect(_e.files),_e.value="")})),ge.querySelector(".persona-attachment-drop-overlay")||ge.appendChild(df(re.dropOverlay))}else{Ae.style.display="";let re=(Du=r.attachments)!=null?Du:{};_e&&(_e.accept=((Nu=re.allowedTypes)!=null?Nu:ro).join(","),_e.multiple=((Ou=re.maxFiles)!=null?Ou:4)>1),vt&&vt.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}else Ae&&(Ae.style.display="none"),vt&&vt.clearAttachments(),(Fu=ge.querySelector(".persona-attachment-drop-overlay"))==null||Fu.remove();let Qt=(_u=r.sendButton)!=null?_u:{},Go=($u=Qt.useIcon)!=null?$u:!1,Ao=(ju=Qt.iconText)!=null?ju:"\u2191",To=Qt.iconName,Yr=(Uu=Qt.tooltipText)!=null?Uu:"Send message",Jo=(qu=Qt.showTooltip)!=null?qu:!1,vr=(zu=Qt.size)!=null?zu:"40px",st=Qt.backgroundColor,hn=Qt.textColor;if(Go){if(Ge.style.width=vr,Ge.style.height=vr,Ge.style.minWidth=vr,Ge.style.minHeight=vr,Ge.style.fontSize="18px",Ge.style.lineHeight="1",Ge.innerHTML="",hn?Ge.style.color=hn:Ge.style.color="var(--persona-button-primary-fg, #ffffff)",To){let re=parseFloat(vr)||24,kt=(hn==null?void 0:hn.trim())||"currentColor",Vt=ve(To,re,kt,2);Vt?Ge.appendChild(Vt):Ge.textContent=Ao}else Ge.textContent=Ao;Ge.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",st?(Ge.style.backgroundColor=st,Ge.classList.remove("persona-bg-persona-primary")):(Ge.style.backgroundColor="",Ge.classList.add("persona-bg-persona-primary"))}else Ge.textContent=(Ku=(Vu=r.copy)==null?void 0:Vu.sendButtonLabel)!=null?Ku:"Send",Ge.style.width="",Ge.style.height="",Ge.style.minWidth="",Ge.style.minHeight="",Ge.style.fontSize="",Ge.style.lineHeight="",Ge.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",st?(Ge.style.backgroundColor=st,Ge.classList.remove("persona-bg-persona-accent")):Ge.classList.add("persona-bg-persona-accent"),hn?Ge.style.color=hn:Ge.classList.add("persona-text-white");Qt.borderWidth?(Ge.style.borderWidth=Qt.borderWidth,Ge.style.borderStyle="solid"):(Ge.style.borderWidth="",Ge.style.borderStyle=""),Qt.borderColor?Ge.style.borderColor=Qt.borderColor:Ge.style.borderColor="",Qt.paddingX?(Ge.style.paddingLeft=Qt.paddingX,Ge.style.paddingRight=Qt.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),Qt.paddingY?(Ge.style.paddingTop=Qt.paddingY,Ge.style.paddingBottom=Qt.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Ut=wn==null?void 0:wn.querySelector(".persona-send-button-tooltip");if(Jo&&Yr)if(Ut)Ut.textContent=Yr,Ut.style.display="";else{let re=document.createElement("div");re.className="persona-send-button-tooltip",re.textContent=Yr,wn==null||wn.insertBefore(re,Ge)}else Ut&&(Ut.style.display="none");let jt=(Yu=(Gu=r.layout)==null?void 0:Gu.contentMaxWidth)!=null?Yu:N()?(Xu=(Qu=(Ju=r.launcher)==null?void 0:Ju.composerBar)==null?void 0:Qu.contentMaxWidth)!=null?Xu:"720px":void 0;jt?(Ze.style.maxWidth=jt,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%",Wt&&(Wt.style.maxWidth=jt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Je&&(Je.style.maxWidth=jt,Je.style.marginLeft="auto",Je.style.marginRight="auto")):(Ze.style.maxWidth="",Ze.style.marginLeft="",Ze.style.marginRight="",Ze.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Je&&(Je.style.maxWidth="",Je.style.marginLeft="",Je.style.marginRight=""));let ht=(Zu=r.statusIndicator)!=null?Zu:{},Xt=(em=ht.visible)!=null?em:!0;if(mn.style.display=Xt?"":"none",_){let re=_.getStatus();tt(mn,(Vt=>{var dt,Rt,yn,En;return Vt==="idle"?(dt=ht.idleText)!=null?dt:Mn.idle:Vt==="connecting"?(Rt=ht.connectingText)!=null?Rt:Mn.connecting:Vt==="connected"?(yn=ht.connectedText)!=null?yn:Mn.connected:Vt==="error"?(En=ht.errorText)!=null?En:Mn.error:Mn[Vt]})(re),ht,re)}mn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let At=ht.align==="left"?"persona-text-left":ht.align==="center"?"persona-text-center":"persona-text-right";mn.classList.add(At)},open(){O()&&E(!0,"api")},close(){O()&&E(!1,"api")},toggle(){O()&&E(!L,"api")},clearChat(){In=!1,_.clearMessages(),Wr.clear(),Dr();try{localStorage.removeItem(Xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xs}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Xs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}d={},A.syncFromMetadata(),pe==null||pe.clear(),me==null||me.reset(),K==null||K.update()},setMessage(l){return!Pe||_.isStreaming()?!1:(!L&&O()&&E(!0,"system"),Pe.value=l,Pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let u=(l==null?void 0:l.trim())||Pe.value.trim();return u?(!L&&O()&&E(!0,"system"),Pe.value="",Pe.style.height="auto",_.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return _.isStreaming()?!1:((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!L&&O()&&E(!0,"system"),yt.manuallyDeactivated=!1,$n(),_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),lr("user"),_.isVoiceActive()&&As()})),!0):Or?!0:Uc()?(!L&&O()&&E(!0,"system"),yt.manuallyDeactivated=!1,$n(),li("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),lr("user"),Xr()}),!0):!1:Or?(yt.manuallyDeactivated=!0,$n(),Co("user"),!0):!1},injectMessage(l){return!L&&O()&&E(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!L&&O()&&E(!0,"system");let u=_.injectAssistantMessage(l);return j&&(j=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),u},injectUserMessage(l){return!L&&O()&&E(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!L&&O()&&E(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!L&&O()&&E(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!L&&O()&&E(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!L&&O()&&E(!0,"system"),_.injectTestEvent(l)},async connectStream(l,u){return _.connectStream(l,u)},__pushEventStreamEvent(l){pe&&(me==null||me.processEvent(l.type,l.payload),pe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!We||!pe||Ur()},hideEventStream(){ae&&hr()},isEventStreamVisible(){return ae},showArtifacts(){fr(r)&&(In=!1,Jn(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){fr(r)&&(In=!0,Jn())},upsertArtifact(l){return fr(r)?(In=!1,_.upsertArtifact(l)):null},selectArtifact(l){fr(r)&&_.selectArtifact(l)},clearArtifacts(){fr(r)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return M&&!L&&!N()||!Pe?!1:(Pe.focus(),!0)},async resolveApproval(l,u,h){let T=_.getMessages().find(W=>{var q;return W.variant==="approval"&&((q=W.approval)==null?void 0:q.id)===l});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${l}`);if(T.approval.toolType==="webmcp"){_.resolveWebMcpApproval(T.id,u);return}return _.resolveApproval(T.approval,u,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){f(l)},on(l,u){return o.on(l,u)},off(l,u){o.off(l,u)},isOpen(){return O()&&L},isVoiceActive(){return yt.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:O()&&L,launcherEnabled:M,voiceActive:yt.active,streaming:_.isStreaming()}},showCSATFeedback(l){!L&&O()&&E(!0,"system");let u=Ze.querySelector(".persona-feedback-container");u&&u.remove();let h=fl({onSubmit:async(b,T)=>{var W;_.isClientTokenMode()&&await _.submitCSATFeedback(b,T),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!L&&O()&&E(!0,"system");let u=Ze.querySelector(".persona-feedback-container");u&&u.remove();let h=hl({onSubmit:async(b,T)=>{var W;_.isClientTokenMode()&&await _.submitNPSFeedback(b,T),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return _.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return _.submitNPSFeedback(l,u)},destroy(){Ee!=null&&(clearInterval(Ee),Ee=null),ut.forEach(l=>l()),Oe.remove(),nt==null||nt.remove(),rn==null||rn.destroy(),fn==null||fn.remove(),Ir&&G.removeEventListener("click",Ir)}};if((((Qd=n==null?void 0:n.debugTools)!=null?Qd:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:dn,getMessages:dn.getMessages,getStatus:dn.getStatus,getMetadata:dn.getPersistentMetadata,updateMetadata:dn.updatePersistentMetadata,clearHistory:()=>dn.clearChat(),setVoiceActive:h=>h?dn.startVoiceRecognition():dn.stopVoiceRecognition()};window.AgentWidgetBrowser=u,ut.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&dn.focusInput()};if(window.addEventListener("persona:focusInput",u),ut.push(()=>{window.removeEventListener("persona:focusInput",u)}),We){let F=ce=>{let de=ce.detail;(!(de!=null&&de.instanceId)||de.instanceId===l)&&dn.showEventStream()},R=ce=>{let de=ce.detail;(!(de!=null&&de.instanceId)||de.instanceId===l)&&dn.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",R),ut.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",R)})}let h=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&dn.showArtifacts()},b=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&dn.hideArtifacts()},T=F=>{let R=F.detail;R!=null&&R.instanceId&&R.instanceId!==l||R!=null&&R.artifact&&dn.upsertArtifact(R.artifact)},W=F=>{let R=F.detail;R!=null&&R.instanceId&&R.instanceId!==l||typeof(R==null?void 0:R.id)=="string"&&dn.selectArtifact(R.id)},q=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&dn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",q),ut.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",q)})}let pr=Nb(r.persistState);if(pr&&O()){let l=Ob(pr.storage),u=`${pr.keyPrefix}widget-open`,h=`${pr.keyPrefix}widget-voice`,b=`${pr.keyPrefix}widget-voice-mode`;if(l){let T=((Xd=pr.persist)==null?void 0:Xd.openState)&&l.getItem(u)==="true",W=((Yd=pr.persist)==null?void 0:Yd.voiceState)&&l.getItem(h)==="true",q=((Zd=pr.persist)==null?void 0:Zd.voiceState)&&l.getItem(b)==="true";if(T&&setTimeout(()=>{dn.open(),setTimeout(()=>{var F;if(W||q)dn.startVoiceRecognition();else if((F=pr.persist)!=null&&F.focusInput){let R=e.querySelector("textarea");R&&R.focus()}},100)},0),(ep=pr.persist)!=null&&ep.openState&&(o.on("widget:opened",()=>{l.setItem(u,"true")}),o.on("widget:closed",()=>{l.setItem(u,"false")})),(tp=pr.persist)!=null&&tp.voiceState&&(o.on("voice:state",F=>{l.setItem(h,F.active?"true":"false")}),o.on("user:message",F=>{l.setItem(b,F.viaVoice?"true":"false")})),pr.clearOnChatClear){let F=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(b)},R=()=>F();window.addEventListener("persona:clear-chat",R),ut.push(()=>{window.removeEventListener("persona:clear-chat",R)})}}}return p&&O()&&setTimeout(()=>{dn.open()},0),qe(),Ja||lm().then(()=>{_&&(fs++,Wr.clear(),bo(Ze,_.getMessages(),ke))}).catch(()=>{}),dn};var Fb=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},_b=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},$b=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},jb=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let s=r.offsetHeight>0;r.style.height="100%";let o=r.offsetHeight>0;r.remove(),!(!s||o)&&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.")},pf=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},kc=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=""},uf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",kc(e)},Tc=e=>{e.style.transition=""},Ec=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=""},Mc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},xl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ub=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},qb=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},mf=(e,t,n,r,s,o,a)=>{var x,v,A,M,B,D;let i=nr(o),d=i.reveal==="push";Ub(e,t,n,r,d),qb(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(v=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,m=(M=(A=o==null?void 0:o.launcher)==null?void 0:A.mobileBreakpoint)!=null?M:640,g=c!=null?c.innerWidth<=m:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ec(t),Tc(r),uf(r),Mc(n),xl(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((D=(B=o==null?void 0:o.launcher)==null?void 0:B.zIndex)!=null?D:kn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),uf(r),_b(r,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",Ec(t),Tc(r),Mc(n),xl(s,r);let k=i.animate?"transform 180ms ease":"none",H=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":H;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=k,r.style.transform=S,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Tc(r),kc(r),xl(s,r);let k=Fb(i.width,e.clientWidth),H=Math.max(0,e.clientWidth),S=i.animate?"margin-left 180ms ease":"none",I=i.side==="right"?a?-k:0:a?0:-k;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=`${H+k}px`,t.style.transition=S,t.style.marginLeft=`${I}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${H}px`,n.style.maxWidth=`${H}px`,n.style.minWidth=`${H}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ec(t),kc(r),Mc(n),xl(s,r);let k=i.reveal==="emerge";k?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let H=a?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",I=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${H}`,r.style.width=H,r.style.maxWidth=H,r.style.minWidth=H,r.style.minHeight="0",$b(r,i.maxHeight),r.style.overflow=k||I?"hidden":"visible",r.style.transition=S,k&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},zb=(e,t)=>{let n=e.ownerDocument.createElement("div");return pf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){pf(n,r)},destroy(){n.remove()}}},Vb=(e,t)=>{var D,k,H,S;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),m=(k=(D=t==null?void 0:t.launcher)==null?void 0:D.enabled)==null||k?(S=(H=t==null?void 0:t.launcher)==null?void 0:H.autoExpand)!=null?S:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,f=()=>{g==null||g.disconnect(),g=null},x=()=>{f(),nr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{mf(a,i,d,c,p,t,m)}),g.observe(a))},v=!1,A=()=>{mf(a,i,d,c,p,t,m),x(),m&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,jb(a,nr(t)))},M=a.ownerDocument.defaultView,B=()=>{A()};return M==null||M.addEventListener("resize",B),nr(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),A(),{mode:"docked",host:p,shell:a,syncWidgetState(I){let N=I.launcherEnabled?I.open:!0;m!==N&&(m=N,A())},updateConfig(I){var N,O;t=I,((O=(N=t==null?void 0:t.launcher)==null?void 0:N.enabled)!=null?O:!0)===!1&&(m=!0),A()},destroy(){M==null||M.removeEventListener("resize",B),f(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},Ka=(e,t)=>un(t)?Vb(e,t):zb(e,t);var Lc={},gf=!1,Kb=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},Gb=()=>{try{if(typeof Lc!="undefined"&&Lc.url)return new URL("../widget.css",Lc.url).href}catch{}return null},ff=(e,t)=>{let n=Gb(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},Pc=e=>{let t=Kb(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=Ka(t,s),a,i=[],d=(A,M)=>{var H,S;let D=!((S=(H=M==null?void 0:M.launcher)==null?void 0:H.enabled)!=null?S:!0)||un(M),k=r.createElement("div");if(k.setAttribute("data-persona-root","true"),D&&(k.style.height="100%",k.style.display="flex",k.style.flexDirection="column",k.style.flex="1",k.style.minHeight="0"),n){let I=A.attachShadow({mode:"open"});I.appendChild(k),ff(I,r)}else A.appendChild(k),ff(A,r);return t.id&&k.setAttribute("data-persona-instance",t.id),k},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},m=()=>{let A=d(o.host,s);a=bl(A,s,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(A=>A()),i=[],a.destroy()};m(),e.onChatReady?e.onChatReady():e.onReady&&(gf||(gf=!0,console.warn("[Persona] `onReady` is deprecated: use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let f=A=>{g(),o.destroy(),o=Ka(t,A),s=A,m()},x={update(A){var S,I,N,O,L,j;let M={...s,...A,launcher:{...(S=s==null?void 0:s.launcher)!=null?S:{},...(I=A==null?void 0:A.launcher)!=null?I:{},dock:{...(O=(N=s==null?void 0:s.launcher)==null?void 0:N.dock)!=null?O:{},...(j=(L=A==null?void 0:A.launcher)==null?void 0:L.dock)!=null?j:{}}}},B=un(s),D=un(M),k=Bo(s),H=Bo(M);if(B!==D||k!==H){f(M);return}s=M,o.updateConfig(s),a.update(A),c()},destroy(){g(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(x,{get(A,M,B){if(M==="host")return o.host;if(M in A)return Reflect.get(A,M,B);let D=a[M];return typeof D=="function"?D.bind(a):D}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var vf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Jb=new Set(["button","a","input","select","textarea","details","summary"]),Qb=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ic=/\b(product|card|item|listing|result)\b/i,Wc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Xb=3e3,Yb=100;function wf(e){let t=typeof e.className=="string"?e.className:"";if(Ic.test(t)||e.id&&Ic.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Ic.test(r.value))return!0}return!1}function Cf(e){var t;return Wc.test(((t=e.textContent)!=null?t:"").trim())}function Sf(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Zb(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function hf(e){let t=e.match(Wc);return t?t[0]:null}function yf(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function ex(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var tx="commerce-card",nx="result-card";function bf(e){return!wf(e)||!Cf(e)||!Sf(e)&&!Zb(e)?0:5200}function xf(e){var r;return!wf(e)||Cf(e)||!Sf(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Hc=[{id:tx,scoreElement(e){return bf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||Wc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(bf(e)===0)return null;let{title:n,href:r}=yf(e),s=(p=(c=hf(((d=e.textContent)!=null?d:"").trim()))!=null?c:hf(t.text))!=null?p:"",o=ex(e);return[r&&n?`[${n}](${r})${s?`: ${s}`:""}`:n?`${n}${s?`: ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
110
+ `)}},{id:nx,scoreElement(e){return xf(e)},formatSummary(e,t){if(xf(e)===0)return null;let{title:n,href:r}=yf(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
111
+ `)}}];function rx(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function ox(e){var p,m,g,f,x,v,A,M,B,D,k,H,S;let t=(p=e.options)!=null?p:{},n=(g=(m=t.maxElements)!=null?m:e.maxElements)!=null?g:80,r=(x=(f=t.excludeSelector)!=null?f:e.excludeSelector)!=null?x:".persona-host",s=(A=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?A:200,o=(B=(M=t.visibleOnly)!=null?M:e.visibleOnly)!=null?B:!0,a=(D=t.root)!=null?D:e.root,i=(k=t.mode)!=null?k:"structured",d=(H=t.maxCandidates)!=null?H:Math.max(500,n*10),c=(S=e.rules)!=null?S:Hc;return i==="simple"&&e.rules&&e.rules.length>0?(rx(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function Rc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var sx=["data-testid","data-product","data-action","data-id","data-name","data-type"];function ax(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||Jb.has(t)||n&&Qb.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Af(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 ix(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Bc(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${Rc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of sx){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${Rc(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>Rc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function lx(e){return e==="static"?Yb:Xb}function Tf(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:Bc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:ax(e),attributes:ix(e)}}function cx(e,t,n,r){let s=lx(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function dx(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function px(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(vf.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Af(c)){i=a.nextNode();continue}let m=Tf(c,e.maxTextLength),g=m.text.length>0,f=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(A=>A==="role");if(!g&&!f){i=a.nextNode();continue}if(r.has(m.selector)){i=a.nextNode();continue}r.add(m.selector);let{score:x,formattingRule:v}=cx(c,m,e.rules,n);s.push({el:c,domIndex:o,enriched:m,score:x,formattingRule:v}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let m=c.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;dx(d,c)||d.push(c)}return d.sort((c,p)=>{let m=c.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return m!==g?m-g:m===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var g;let p;if((g=c.formattingRule)!=null&&g.formatSummary){let f=c.formattingRule.formatSummary(c.el,c.enriched,n);f&&(p=f)}let m={...c.enriched};return p&&(m.formattedSummary=p),m})}function ux(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,c=d.tagName.toLowerCase();if(vf.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Af(d)){o=s.nextNode();continue}let p=Tf(d,e.maxTextLength),m=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(f=>f==="role");if(!m&&!g){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}o=s.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Ef(e={}){var r;let t=ox(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?ux(t,n):px(t,n):[]}var vl=100;function Mf(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
112
112
  ${a.map(i=>`- ${i.split(`
113
113
  `).join(`
114
114
  `)}`).join(`
@@ -122,7 +122,7 @@ ${a.join(`
122
122
  ${a.join(`
123
123
  `)}`)}return r.join(`
124
124
 
125
- `)}var Mf="3.35.0";var us=Mf;function kf(){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 Lf(){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 Pf(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:$r(e.colors.primary,.95),100:$r(e.colors.primary,.9),200:$r(e.colors.primary,.8),300:$r(e.colors.primary,.7),400:$r(e.colors.primary,.6),500:e.colors.primary,600:$r(e.colors.primary,.8),700:$r(e.colors.primary,.7),800:$r(e.colors.primary,.6),900:$r(e.colors.primary,.5),950:$r(e.colors.primary,.45)}}),{...t,palette:n}}}}function If(){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 Rf(){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 $r(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Wf(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var mx={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"}}},Hf={components:{panel:{borderRadius:"0",shadow:"none"}}},Dc={id:"shop",label:"Shopping Assistant",config:{theme:mx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:tr},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?"]}},Nc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Hf}},Oc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Hf}},Fc={shop:Dc,minimal:Nc,fullscreen:Oc};function Bf(e){return Fc[e]}var Df=Pc;function ao(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function gx(e){if(e)return{getHeaders:ao(e.getHeaders),onFeedback:ao(e.onFeedback),onCopy:ao(e.onCopy),requestMiddleware:ao(e.requestMiddleware),actionHandlers:ao(e.actionHandlers),actionParsers:ao(e.actionParsers),postprocessMessage:ao(e.postprocessMessage),contextProviders:ao(e.contextProviders),streamParser:ao(e.streamParser)}}var Nf=`({ text, message }: any) => {
125
+ `)}function kf(){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 Lf(){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 Pf(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:jr(e.colors.primary,.95),100:jr(e.colors.primary,.9),200:jr(e.colors.primary,.8),300:jr(e.colors.primary,.7),400:jr(e.colors.primary,.6),500:e.colors.primary,600:jr(e.colors.primary,.8),700:jr(e.colors.primary,.7),800:jr(e.colors.primary,.6),900:jr(e.colors.primary,.5),950:jr(e.colors.primary,.45)}}),{...t,palette:n}}}}function If(){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 Rf(){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 jr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Wf(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var mx={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"}}},Hf={components:{panel:{borderRadius:"0",shadow:"none"}}},Dc={id:"shop",label:"Shopping Assistant",config:{theme:mx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:tr},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?"]}},Nc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Hf}},Oc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Hf}},Fc={shop:Dc,minimal:Nc,fullscreen:Oc};function Bf(e){return Fc[e]}var Df=Pc;function io(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function gx(e){if(e)return{getHeaders:io(e.getHeaders),onFeedback:io(e.onFeedback),onCopy:io(e.onCopy),requestMiddleware:io(e.requestMiddleware),actionHandlers:io(e.actionHandlers),actionParsers:io(e.actionParsers),postprocessMessage:io(e.postprocessMessage),contextProviders:io(e.contextProviders),streamParser:io(e.streamParser)}}var Nf=`({ text, message }: any) => {
126
126
  const jsonSource = (message as any).rawContent || text || message.content;
127
127
  if (!jsonSource || typeof jsonSource !== 'string') return null;
128
128
  let cleanJson = jsonSource
@@ -194,13 +194,13 @@ ${a.join(`
194
194
  if (parsed.action === 'message') return parsed.text || '';
195
195
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
196
196
  return parsed.text || null;
197
- }`;function yx(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function wl(e){var t,n;return(n=(t=e.parserType)!=null?t:yx(e.streamParser))!=null?n:"plain"}function Cl(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&n.push(`${t} ${r}: "${s}",`)}),n.push(`${t}},`)),n}function Sl(e,t,n){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(s||o)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Al(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Tl(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?n.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${d}: ${c},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function _c(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function $f(e,t,n){Object.entries(t).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${r}: {`),$f(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function Do(e,t,n,r){n&&(e.push(`${r}${t}: {`),$f(e,n,`${r} `),e.push(`${r}},`))}function Ga(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function jf(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:gx(n.hooks)}:void 0;return t==="esm"?bx(r,s):t==="script-installer"?wx(r,s):t==="script-advanced"?Sx(r,s):t==="react-component"?xx(r,s):t==="react-advanced"?vx(r,s):Cx(r,s)}function bx(e,t){let n=t==null?void 0:t.hooks,r=wl(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ga(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Do(o,"theme",e.theme," "),e.launcher&&Do(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Cl(e," ")),o.push(...Sl(e," ",n)),o.push(...Al(e," ")),o.push(...Tl(e," ")),o.push(..._c(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
198
- `)}function xx(e,t){let n=t==null?void 0:t.hooks,r=wl(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Ga(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Do(o,"theme",e.theme," "),e.launcher&&Do(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Cl(e," ")),o.push(...Sl(e," ",n)),o.push(...Al(e," ")),o.push(...Tl(e," ")),o.push(..._c(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
199
- `)}function vx(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ga(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Do(r,"theme",e.theme," "),e.launcher&&Do(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Cl(e," ")),r.push(...Sl(e," ",n)),r.push(...Al(e," ")),r.push(...Tl(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${fx}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Nf}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Nf}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Ff}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Ff}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
200
- `)}function Uf(e){var s;let t=wl(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([p,m])=>{p!=="format"&&(typeof m=="string"||typeof m=="boolean")&&(c[p]=m)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function wx(e,t){let n=Uf(e),s=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,o=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${us}/dist/install.global.js" data-config='${o}'></script>`}function Cx(e,t){let n=t==null?void 0:t.hooks,r=wl(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${us}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${us}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ga(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Do(o,"theme",e.theme," "),e.launcher&&Do(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Cl(e," ")),o.push(...Sl(e," ",n)),o.push(...Al(e," ")),o.push(...Tl(e," ")),o.push(..._c(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
197
+ }`;function yx(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function wl(e){var t,n;return(n=(t=e.parserType)!=null?t:yx(e.streamParser))!=null?n:"plain"}function Cl(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&n.push(`${t} ${r}: "${s}",`)}),n.push(`${t}},`)),n}function Sl(e,t,n){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(s||o)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Al(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Tl(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?n.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${d}: ${c},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function _c(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function $f(e,t,n){Object.entries(t).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${r}: {`),$f(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function No(e,t,n,r){n&&(e.push(`${r}${t}: {`),$f(e,n,`${r} `),e.push(`${r}},`))}function Ga(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function jf(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:gx(n.hooks)}:void 0;return t==="esm"?bx(r,s):t==="script-installer"?wx(r,s):t==="script-advanced"?Sx(r,s):t==="react-component"?xx(r,s):t==="react-advanced"?vx(r,s):Cx(r,s)}function bx(e,t){let n=t==null?void 0:t.hooks,r=wl(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ga(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&No(o,"theme",e.theme," "),e.launcher&&No(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Cl(e," ")),o.push(...Sl(e," ",n)),o.push(...Al(e," ")),o.push(...Tl(e," ")),o.push(..._c(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
198
+ `)}function xx(e,t){let n=t==null?void 0:t.hooks,r=wl(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Ga(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&No(o,"theme",e.theme," "),e.launcher&&No(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Cl(e," ")),o.push(...Sl(e," ",n)),o.push(...Al(e," ")),o.push(...Tl(e," ")),o.push(..._c(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
199
+ `)}function vx(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ga(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&No(r,"theme",e.theme," "),e.launcher&&No(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Cl(e," ")),r.push(...Sl(e," ",n)),r.push(...Al(e," ")),r.push(...Tl(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${fx}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Nf}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Nf}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Ff}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Ff}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
200
+ `)}function Uf(e){var s;let t=wl(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([p,m])=>{p!=="format"&&(typeof m=="string"||typeof m=="boolean")&&(c[p]=m)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function wx(e,t){let n=Uf(e),s=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,o=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${gr}/dist/install.global.js" data-config='${o}'></script>`}function Cx(e,t){let n=t==null?void 0:t.hooks,r=wl(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${gr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${gr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ga(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&No(o,"theme",e.theme," "),e.launcher&&No(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Cl(e," ")),o.push(...Sl(e," ",n)),o.push(...Al(e," ")),o.push(...Tl(e," ")),o.push(..._c(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
201
201
  `)}function Sx(e,t){let n=t==null?void 0:t.hooks,r=Uf(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
202
202
  `).map((a,i)=>i===0?a:" "+a).join(`
203
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${us}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${hx});`),o.push(" };")),o.push(""),n!=null&&n.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${n.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Of}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Of}`),o.push(" ];")),o.push(""),n!=null&&n.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${n.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${_f}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${_f}`),o.push(" ];")),o.push(""),n!=null&&n.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${n.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),n!=null&&n.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Ga(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
203
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${gr}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${hx});`),o.push(" };")),o.push(""),n!=null&&n.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${n.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Of}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Of}`),o.push(" ];")),o.push(""),n!=null&&n.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${n.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${_f}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${_f}`),o.push(" ];")),o.push(""),n!=null&&n.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${n.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),n!=null&&n.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Ga(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
204
204
  `)}var qf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},zf=.1,Vf=.15,Kf=1.5,$c=24,Gf=40,Ax=`
205
205
  /* \u2500\u2500 Root \u2500\u2500 */
206
206
  .persona-dc-root {