@runtypelabs/persona 4.11.1 → 4.13.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,36 +1,36 @@
1
- "use strict";var $m=Object.create;var Ea=Object.defineProperty;var jm=Object.getOwnPropertyDescriptor;var Um=Object.getOwnPropertyNames;var zm=Object.getPrototypeOf,qm=Object.prototype.hasOwnProperty;var br=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ma=(e,t)=>{for(var n in t)Ea(e,n,{get:t[n],enumerable:!0})},dp=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Um(t))!qm.call(e,r)&&r!==n&&Ea(e,r,{get:()=>t[r],enumerable:!(o=jm(t,r))||o.enumerable});return e};var ms=(e,t,n)=>(n=e!=null?$m(zm(e)):{},dp(t||!e||!e.__esModule?Ea(n,"default",{value:e,enumerable:!0}):n,e)),Vm=e=>dp(Ea({},"__esModule",{value:!0}),e);var gp={};Ma(gp,{DOMPurify:()=>up.default,Marked:()=>pp.Marked});var pp,up,fp=br(()=>{"use strict";pp=require("marked"),up=ms(require("dompurify"),1)});var kr,Gl=br(()=>{"use strict";kr=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;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,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 o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}r.onended=()=>{let a=this.activeSources.indexOf(r);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),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function Xh(e){return e.replace(/\/+$/,"")}async function Qh(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Xa,yu=br(()=>{"use strict";Gl();Xa=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new kr(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${Xh(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await Qh(a));let i=a.body.getReader();for(;;){let{done:p,value:d}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(p)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(t!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var Qa,bu=br(()=>{"use strict";Qa=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var vu={};Ma(vu,{FallbackSpeechEngine:()=>Qa,RuntypeSpeechEngine:()=>Xa});var xu=br(()=>{"use strict";yu();bu()});var wu={};Ma(wu,{createReconnectController:()=>Zh});function Zh(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let y=n;n=null,y()}},a=()=>{let y=e.getStatus();y!=="resuming"&&y!=="paused"||s()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},u=y=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},y)}),b=()=>{let y=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let P of e.getMessages())P.streaming&&(P.streaming=!1,C=!0);let k=e.buildErrorContent("Connection lost and the response could not be resumed.");k?e.appendMessage({id:`reconnect-failed-${y?.executionId??e.nextSequence()}`,role:"assistant",content:k,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{let y=e.config.reconnect?.backoffMs??Yh,C=e.config.reconnect?.maxAttempts??y.length,k=e.config.reconnectStream;if(!k){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let P=e.getResumable(),W=P.lastEventId,S=new AbortController;e.setAbortController(S),e.emitReconnect({phase:"resuming",handle:P,attempt:t});let I=null;try{let j=await k({executionId:P.executionId,after:P.lastEventId,signal:S.signal});j&&j.ok&&j.body&&(I=j.body)}catch{I=null}if(S.signal.aborted)return;if(I){let j=e.getMessages().find(w=>w.id===P.assistantMessageId)?.content,q=typeof j=="string"?j:"";try{await e.resumeConnect(I,P.assistantMessageId,q)}catch{}if(S.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:P});return}e.getResumable().lastEventId!==W&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(y[Math.min(t-1,y.length-1)]??1e3),S.signal.aborted))return}e.getResumable()&&b()};return{begin(){t=0,d(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:s}}var Yh,Au=br(()=>{"use strict";Yh=[1e3,2e3,4e3,8e3,8e3]});var Tx={};Ma(Tx,{ASK_USER_QUESTION_CLIENT_TOOL:()=>ql,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>zl,ASK_USER_QUESTION_TOOL_NAME:()=>vs,AgentWidgetClient:()=>Go,AgentWidgetSession:()=>Pr,AttachmentManager:()=>Qo,BrowserSpeechEngine:()=>xo,DEFAULT_COMPONENTS:()=>rc,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ei,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>sn,DEFAULT_PALETTE:()=>nc,DEFAULT_SEMANTIC:()=>oc,DEFAULT_WIDGET_CONFIG:()=>it,PRESETS:()=>Yc,PRESET_FULLSCREEN:()=>Qc,PRESET_MINIMAL:()=>Xc,PRESET_SHOP:()=>Jc,ReadAloudController:()=>Xo,SUGGEST_REPLIES_CLIENT_TOOL:()=>Ba,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>$l,SUGGEST_REPLIES_TOOL_NAME:()=>Sn,THEME_ZONES:()=>Du,VERSION:()=>fn,WEBMCP_TOOL_PREFIX:()=>An,WebMcpBridge:()=>wr,accessibilityPlugin:()=>kf,animationsPlugin:()=>Lf,applyThemeVariables:()=>Yo,attachHeaderToContainer:()=>er,brandPlugin:()=>Pf,buildComposer:()=>Nr,buildDefaultHeader:()=>yc,buildHeader:()=>Jn,buildHeaderWithLayout:()=>Dr,buildMinimalHeader:()=>bc,builtInClientToolsForDispatch:()=>Er,collectEnrichedPageContext:()=>Ef,componentRegistry:()=>Tn,createActionManager:()=>Js,createAgentExperience:()=>ji,createAskUserQuestionBubble:()=>Qp,createBestAvailableVoiceProvider:()=>Ja,createBubbleWithLayout:()=>Lg,createCSATFeedback:()=>Fi,createComboButton:()=>ci,createComponentMiddleware:()=>nf,createComponentStreamParser:()=>Oi,createDefaultSanitizer:()=>Wl,createDemoCarousel:()=>Jf,createDirectivePostprocessor:()=>wp,createDropdownMenu:()=>So,createFlexibleJsonStreamParser:()=>tu,createIconButton:()=>ct,createImagePart:()=>lu,createJsonStreamParser:()=>Ua,createLabelButton:()=>Kn,createLocalStorageAdapter:()=>Bi,createMarkdownProcessor:()=>hs,createMarkdownProcessorFromConfig:()=>qo,createMessageActions:()=>Tc,createNPSFeedback:()=>_i,createPlainTextParser:()=>$a,createPlugin:()=>Wf,createRegexJsonParser:()=>ja,createRovingTablist:()=>Wi,createSlashCommandsSource:()=>mf,createStandardBubble:()=>Fr,createStaticMentionSource:()=>ff,createTextPart:()=>bo,createTheme:()=>Ps,createThemeObserver:()=>Ir,createToggleGroup:()=>Gn,createTypingIndicator:()=>tr,createVoiceProvider:()=>vo,createWidgetHostLayout:()=>Qs,createXmlParser:()=>za,default:()=>Of,defaultActionHandlers:()=>sr,defaultJsonActionParser:()=>Gs,defaultMentionFilter:()=>zi,defaultParseRules:()=>Kc,detectColorScheme:()=>Rs,directivePostprocessor:()=>Ap,ensureAskUserQuestionSheet:()=>Tr,escapeHtml:()=>Pn,extractComponentDirectiveFromMessage:()=>Ni,fileToImagePart:()=>cu,formatEnrichedContext:()=>Mf,generateAssistantMessageId:()=>yo,generateCodeSnippet:()=>jf,generateMessageId:()=>ru,generateStableSelector:()=>Gc,generateUserMessageId:()=>Mr,getActiveTheme:()=>Co,getColorScheme:()=>si,getDisplayText:()=>au,getHeaderLayout:()=>vc,getImageParts:()=>iu,getPreset:()=>Bf,hasComponentDirective:()=>Xs,hasImages:()=>Ka,headerLayouts:()=>Ai,highContrastPlugin:()=>If,initAgentWidget:()=>Uc,isAskUserQuestionMessage:()=>Un,isComponentDirectiveType:()=>tf,isDockedMountMode:()=>Lt,isSuggestRepliesMessage:()=>Cs,isVoiceSupported:()=>Es,isWebMcpToolName:()=>po,latestAgentSuggestions:()=>Oa,listRegisteredStreamAnimations:()=>bg,loadMarkdownParsers:()=>Rl,markdownPostprocessor:()=>Il,mergeWithDefaults:()=>Rr,normalizeContent:()=>su,onMarkdownParsersReady:()=>xr,parseAskUserQuestionPayload:()=>zn,parseSuggestRepliesPayload:()=>Ul,pickBestVoice:()=>Lr,pluginRegistry:()=>Ks,reducedMotionPlugin:()=>Rf,registerStreamAnimationPlugin:()=>hg,removeAskUserQuestionSheet:()=>fo,renderComponentDirective:()=>Di,renderLoadingIndicatorWithFallback:()=>Sc,renderLucideIcon:()=>ne,resolveDockConfig:()=>Zt,resolveSanitizer:()=>Cr,resolveTokens:()=>oi,stripWebMcpPrefix:()=>Pa,themeToCssVariables:()=>ri,unregisterStreamAnimationPlugin:()=>yg,validateImageFile:()=>du,validateTheme:()=>sc});module.exports=Vm(Tx);var yp=require("marked"),bp=ms(require("dompurify"),1);var vr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:Ix,load:Km,provide:Gm,getSync:Pl}=vr({fallbackImport:()=>Promise.resolve().then(()=>(fp(),gp))}),ka=new Set,mp=()=>{let e=[...ka];ka.clear();for(let t of e)try{t()}catch{}};var Rl=()=>{let e=Pl();return e?Promise.resolve(e):Km().then(t=>(mp(),t))},xr=e=>Pl()?()=>{}:(ka.add(e),Rl().catch(()=>{}),()=>{ka.delete(e)}),hp=e=>{Gm(e),mp()},$n=Pl;hp({Marked:yp.Marked,DOMPurify:bp.default});var Jm=e=>{if(e)return e},hs=e=>{let t=null;return n=>{let o=$n();if(!o)return Pn(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=Jm(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},qo=e=>e?hs({markedOptions:e.options,renderer:e.renderer}):hs(),Xm=hs(),Il=e=>Xm(e),Pn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),xp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Cp=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=vp(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=vp(t.length);return t.push({token:s,type:r}),s}),n},wp=e=>{let t=qo(e);return n=>{let o=[],r=Cp(n,o),s=t(r);return o.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${xp(i)}"></div>`;s=s.replace(p,c)}),s}},Ap=e=>{let t=[],n=Cp(e,t),o=Il(n);return t.forEach(({token:r,type:s})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${xp(s)}"></div>`;o=o.replace(a,p)}),o};var Qm={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"]},Ym=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Wl=()=>{let e=null;return t=>{let n=$n();if(!n)return Pn(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Ym.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Qm)}},Cr=e=>e===!1?null:typeof e=="function"?e:Wl();var Sp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Tp=e=>e.includes("|"),Ep=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},Zm=e=>`| ${e.join(" | ")} |`,eh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,th=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Mp=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
- `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!Tp(r)||Sp.test(r)||!Sp.test(s))continue;let a=Ep(r).length;if(a<1)continue;let i=eh(a);t[o+1]!==i&&(t[o+1]=i,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!Tp(d))break;let c=Zm(th(Ep(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
- `):e};var kp="var(--persona-md-table-scroll-fade, 24px)",Lp=new WeakSet;function Rp(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Pp(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":kp),e.style.setProperty("--persona-fade-r",r<=1?"0px":kp)}function Hl(e){Lp.has(e)||(Lp.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Pp(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Pp)}var An="webmcp:",Bl=new Map,Ip=e=>{Bl.clear();for(let t of e){let n=t.title?.trim();n&&Bl.set(t.name,n)}},ys=e=>Bl.get(Pa(e)),La={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Wp=null;function Bp(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${nh(t.join(""))}`}function Hp(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function nh(e){let t=Hp(e,0).toString(36),n=Hp(e,2654435761).toString(36);return`${t}.${n}`}var wr=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??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(r){return La.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Ip(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=rh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return wn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let y=typeof document<"u"&&!!document.modelContext;return wn(y?"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 s=Pa(t),a;try{a=await r.getTools()}catch(y){let C=y instanceof Error?y.message:String(y);return wn(`Failed to read WebMCP registry: ${C}`)}Ip(a);let i=a.find(y=>y.name===s);if(!i)return wn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return wn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return wn("Aborted by cancel()");let p=ys(s),d={toolName:s,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return wn("User declined the tool call.");if(o?.aborted)return wn("Aborted by cancel()");let c=new AbortController,u=!1,b=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),g=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",g,{once:!0}));try{let y=await r.executeTool(i,lh(n),{signal:c.signal});return sh(y)}catch(y){if(u)return wn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return wn("Aborted by cancel()");let C=y instanceof Error?y.message:String(y);return wn(C)}finally{clearTimeout(b),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Wp?await Wp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){La.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")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,La.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){let n=this.confirmHandler??ah;try{return await n(t)}catch(o){return La.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>oh(t,o))}},Pa=e=>e.startsWith(An)?e.slice(An.length):e,po=e=>e.startsWith(An),oh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},rh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},sh=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:ch(t)}]}},wn=e=>({isError:!0,content:[{type:"text",text:e}]}),ah=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=ih(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var Km=Object.create;var Ia=Object.defineProperty;var Gm=Object.getOwnPropertyDescriptor;var Jm=Object.getOwnPropertyNames;var Xm=Object.getPrototypeOf,Qm=Object.prototype.hasOwnProperty;var vr=(e,t)=>()=>(e&&(t=e(e=0)),t);var Wa=(e,t)=>{for(var n in t)Ia(e,n,{get:t[n],enumerable:!0})},mp=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Jm(t))!Qm.call(e,r)&&r!==n&&Ia(e,r,{get:()=>t[r],enumerable:!(o=Gm(t,r))||o.enumerable});return e};var ys=(e,t,n)=>(n=e!=null?Km(Xm(e)):{},mp(t||!e||!e.__esModule?Ia(n,"default",{value:e,enumerable:!0}):n,e)),Ym=e=>mp(Ia({},"__esModule",{value:!0}),e);var bp={};Wa(bp,{DOMPurify:()=>yp.default,Marked:()=>hp.Marked});var hp,yp,vp=vr(()=>{"use strict";hp=require("marked"),yp=ys(require("dompurify"),1)});var Lr,Ql=vr(()=>{"use strict";Lr=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;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,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 o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}r.onended=()=>{let a=this.activeSources.indexOf(r);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),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function ny(e){return e.replace(/\/+$/,"")}async function oy(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var ni,wu=vr(()=>{"use strict";Ql();ni=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Lr(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${ny(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await oy(a));let i=a.body.getReader();for(;;){let{done:p,value:d}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(p)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(t!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var oi,Au=vr(()=>{"use strict";oi=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var Su={};Wa(Su,{FallbackSpeechEngine:()=>oi,RuntypeSpeechEngine:()=>ni});var Tu=vr(()=>{"use strict";wu();Au()});var Mu={};Wa(Mu,{createReconnectController:()=>sy});function sy(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let y=n;n=null,y()}},a=()=>{let y=e.getStatus();y!=="resuming"&&y!=="paused"||s()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},u=y=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},y)}),b=()=>{let y=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let P of e.getMessages())P.streaming&&(P.streaming=!1,C=!0);let k=e.buildErrorContent("Connection lost and the response could not be resumed.");k?e.appendMessage({id:`reconnect-failed-${y?.executionId??e.nextSequence()}`,role:"assistant",content:k,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{let y=e.config.reconnect?.backoffMs??ry,C=e.config.reconnect?.maxAttempts??y.length,k=e.config.reconnectStream;if(!k){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let P=e.getResumable(),W=P.lastEventId,S=new AbortController;e.setAbortController(S),e.emitReconnect({phase:"resuming",handle:P,attempt:t});let I=null;try{let j=await k({executionId:P.executionId,after:P.lastEventId,signal:S.signal});j&&j.ok&&j.body&&(I=j.body)}catch{I=null}if(S.signal.aborted)return;if(I){let j=e.getMessages().find(w=>w.id===P.assistantMessageId)?.content,q=typeof j=="string"?j:"";try{await e.resumeConnect(I,P.assistantMessageId,q)}catch{}if(S.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:P});return}e.getResumable().lastEventId!==W&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(y[Math.min(t-1,y.length-1)]??1e3),S.signal.aborted))return}e.getResumable()&&b()};return{begin(){t=0,d(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:s}}var ry,ku=vr(()=>{"use strict";ry=[1e3,2e3,4e3,8e3,8e3]});var Rx={};Wa(Rx,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Gl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Kl,ASK_USER_QUESTION_TOOL_NAME:()=>Cs,AgentWidgetClient:()=>Jo,AgentWidgetSession:()=>Rr,AttachmentManager:()=>Yo,BrowserSpeechEngine:()=>xo,DEFAULT_COMPONENTS:()=>ic,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ai,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>sn,DEFAULT_PALETTE:()=>sc,DEFAULT_SEMANTIC:()=>ac,DEFAULT_WIDGET_CONFIG:()=>it,PRESETS:()=>td,PRESET_FULLSCREEN:()=>ed,PRESET_MINIMAL:()=>Zc,PRESET_SHOP:()=>Yc,ReadAloudController:()=>Qo,SUGGEST_REPLIES_CLIENT_TOOL:()=>$a,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>zl,SUGGEST_REPLIES_TOOL_NAME:()=>An,THEME_ZONES:()=>ju,VERSION:()=>qn,WEBMCP_TOOL_PREFIX:()=>wn,WebMcpBridge:()=>Ar,accessibilityPlugin:()=>Hf,animationsPlugin:()=>Bf,applyThemeVariables:()=>Zo,attachHeaderToContainer:()=>tr,brandPlugin:()=>Of,buildComposer:()=>Fr,buildDefaultHeader:()=>xc,buildHeader:()=>Jn,buildHeaderWithLayout:()=>Nr,buildMinimalHeader:()=>Cc,builtInClientToolsForDispatch:()=>Mr,collectEnrichedPageContext:()=>If,componentRegistry:()=>Sn,createActionManager:()=>Qs,createAgentExperience:()=>Gi,createAskUserQuestionBubble:()=>nu,createBestAvailableVoiceProvider:()=>ti,createBubbleWithLayout:()=>Bg,createCSATFeedback:()=>qi,createComboButton:()=>mi,createComponentMiddleware:()=>cf,createComponentStreamParser:()=>ji,createDefaultSanitizer:()=>Ol,createDemoCarousel:()=>tm,createDirectivePostprocessor:()=>Mp,createDropdownMenu:()=>So,createFlexibleJsonStreamParser:()=>au,createIconButton:()=>ct,createImagePart:()=>gu,createJsonStreamParser:()=>Ja,createLabelButton:()=>Kn,createLocalStorageAdapter:()=>$i,createMarkdownProcessor:()=>bs,createMarkdownProcessorFromConfig:()=>Vo,createMessageActions:()=>kc,createNPSFeedback:()=>Vi,createPlainTextParser:()=>Ka,createPlugin:()=>Ff,createRegexJsonParser:()=>Ga,createRovingTablist:()=>Fi,createSlashCommandsSource:()=>Cf,createStandardBubble:()=>_r,createStaticMentionSource:()=>xf,createTextPart:()=>bo,createTheme:()=>Is,createThemeObserver:()=>Wr,createToggleGroup:()=>Gn,createTypingIndicator:()=>nr,createVoiceProvider:()=>vo,createWidgetHostLayout:()=>Zs,createXmlParser:()=>Xa,default:()=>jf,defaultActionHandlers:()=>ar,defaultJsonActionParser:()=>Xs,defaultMentionFilter:()=>Xi,defaultParseRules:()=>Xc,detectColorScheme:()=>Ws,directivePostprocessor:()=>kp,ensureAskUserQuestionSheet:()=>Er,escapeHtml:()=>Ln,extractComponentDirectiveFromMessage:()=>zi,fileToImagePart:()=>fu,formatEnrichedContext:()=>Wf,generateAssistantMessageId:()=>yo,generateCodeSnippet:()=>Gf,generateMessageId:()=>cu,generateStableSelector:()=>Qc,generateUserMessageId:()=>kr,getActiveTheme:()=>Co,getColorScheme:()=>pi,getDisplayText:()=>pu,getHeaderLayout:()=>wc,getImageParts:()=>uu,getPreset:()=>$f,hasComponentDirective:()=>Ys,hasImages:()=>Za,headerLayouts:()=>Li,highContrastPlugin:()=>Nf,initAgentWidget:()=>Vc,isAskUserQuestionMessage:()=>jn,isComponentDirectiveType:()=>lf,isDockedMountMode:()=>Lt,isSuggestRepliesMessage:()=>As,isVoiceSupported:()=>ks,isWebMcpToolName:()=>po,latestAgentSuggestions:()=>ja,listRegisteredStreamAnimations:()=>Sg,loadMarkdownParsers:()=>Hl,markdownPostprocessor:()=>Bl,mergeWithDefaults:()=>Ir,normalizeContent:()=>du,onMarkdownParsersReady:()=>Cr,parseAskUserQuestionPayload:()=>Un,parseSuggestRepliesPayload:()=>Vl,pickBestVoice:()=>Pr,pluginRegistry:()=>Js,reducedMotionPlugin:()=>Df,registerStreamAnimationPlugin:()=>wg,removeAskUserQuestionSheet:()=>fo,renderComponentDirective:()=>Ui,renderLoadingIndicatorWithFallback:()=>Mc,renderLucideIcon:()=>ne,resolveDockConfig:()=>Zt,resolveSanitizer:()=>wr,resolveTokens:()=>ci,stripWebMcpPrefix:()=>Oa,themeToCssVariables:()=>di,unregisterStreamAnimationPlugin:()=>Ag,validateImageFile:()=>mu,validateTheme:()=>lc});module.exports=Ym(Rx);var wp=require("marked"),Ap=ys(require("dompurify"),1);var xr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:Nx,load:Zm,provide:eh,getSync:Wl}=xr({fallbackImport:()=>Promise.resolve().then(()=>(vp(),bp))}),Ha=new Set,xp=()=>{let e=[...Ha];Ha.clear();for(let t of e)try{t()}catch{}};var Hl=()=>{let e=Wl();return e?Promise.resolve(e):Zm().then(t=>(xp(),t))},Cr=e=>Wl()?()=>{}:(Ha.add(e),Hl().catch(()=>{}),()=>{Ha.delete(e)}),Cp=e=>{eh(e),xp()},_n=Wl;Cp({Marked:wp.Marked,DOMPurify:Ap.default});var th=e=>{if(e)return e},bs=e=>{let t=null;return n=>{let o=_n();if(!o)return Ln(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=th(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Vo=e=>e?bs({markedOptions:e.options,renderer:e.renderer}):bs(),nh=bs(),Bl=e=>nh(e),Ln=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Tp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Sp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ep=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Sp(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=Sp(t.length);return t.push({token:s,type:r}),s}),n},Mp=e=>{let t=Vo(e);return n=>{let o=[],r=Ep(n,o),s=t(r);return o.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${Tp(i)}"></div>`;s=s.replace(p,c)}),s}},kp=e=>{let t=[],n=Ep(e,t),o=Bl(n);return t.forEach(({token:r,type:s})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Tp(s)}"></div>`;o=o.replace(a,p)}),o};var oh={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"]},rh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ol=()=>{let e=null;return t=>{let n=_n();if(!n)return Ln(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!rh.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,oh)}},wr=e=>e===!1?null:typeof e=="function"?e:Ol();var Lp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Pp=e=>e.includes("|"),Rp=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},sh=e=>`| ${e.join(" | ")} |`,ah=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,ih=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Ip=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
+ `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!Pp(r)||Lp.test(r)||!Lp.test(s))continue;let a=Rp(r).length;if(a<1)continue;let i=ah(a);t[o+1]!==i&&(t[o+1]=i,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!Pp(d))break;let c=sh(ih(Rp(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
+ `):e};var Wp="var(--persona-md-table-scroll-fade, 24px)",Hp=new WeakSet;function Op(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Bp(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":Wp),e.style.setProperty("--persona-fade-r",r<=1?"0px":Wp)}function Dl(e){Hp.has(e)||(Hp.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Bp(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Bp)}var wn="webmcp:",Nl=new Map,Dp=e=>{Nl.clear();for(let t of e){let n=t.title?.trim();n&&Nl.set(t.name,n)}},vs=e=>Nl.get(Oa(e)),Ba={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Np=null;function _p(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${lh(t.join(""))}`}function Fp(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function lh(e){let t=Fp(e,0).toString(36),n=Fp(e,2654435761).toString(36);return`${t}.${n}`}var Ar=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??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(r){return Ba.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Dp(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=dh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Cn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let y=typeof document<"u"&&!!document.modelContext;return Cn(y?"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 s=Oa(t),a;try{a=await r.getTools()}catch(y){let C=y instanceof Error?y.message:String(y);return Cn(`Failed to read WebMCP registry: ${C}`)}Dp(a);let i=a.find(y=>y.name===s);if(!i)return Cn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Cn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Cn("Aborted by cancel()");let p=vs(s),d={toolName:s,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return Cn("User declined the tool call.");if(o?.aborted)return Cn("Aborted by cancel()");let c=new AbortController,u=!1,b=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),g=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",g,{once:!0}));try{let y=await r.executeTool(i,fh(n),{signal:c.signal});return ph(y)}catch(y){if(u)return Cn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Cn("Aborted by cancel()");let C=y instanceof Error?y.message:String(y);return Cn(C)}finally{clearTimeout(b),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Np?await Np():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ba.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")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,Ba.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){let n=this.confirmHandler??uh;try{return await n(t)}catch(o){return Ba.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>ch(t,o))}},Oa=e=>e.startsWith(wn)?e.slice(wn.length):e,po=e=>e.startsWith(wn),ch=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},dh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},ph=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:mh(t)}]}},Cn=e=>({isError:!0,content:[{type:"text",text:e}]}),uh=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=gh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
4
4
 
5
5
  Arguments:
6
6
  ${t}`:"")+(e.description?`
7
7
 
8
- ${e.description}`:"");return window.confirm(n)},ih=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)}},lh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},ch=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Vo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function Ra(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var dh="agent_",ph="flow_";function Op(e){return e.startsWith(dh)?{kind:"agentId",agentId:e}:e.startsWith(ph)?{kind:"flowId",flowId:e}:null}function Dp(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let d=Op(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let r=Op(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var uo=require("partial-json");var m=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Np=()=>document.createDocumentFragment(),_e=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(s[i]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},jn=(...e)=>e.filter(Boolean).join(" ");var vs="ask_user_question",bs=8,Ar="data-persona-ask-sheet-for",uh="Other",gh="Other\u2026",_p="Type your own answer here",$p="Send",fh="Next",mh="Back",hh="Submit all",yh="Skip",bh=3,Ol="data-ask-current-index",Dl="data-ask-question-count",jp="data-ask-answers",Nl="data-ask-grouped",Up="data-ask-layout",vh=e=>e.layout==="pills"?"pills":"rows",xh=e=>e.getAttribute(Up)==="pills"?"pills":"rows",Fp=!1,zp=e=>e.replace(/["\\]/g,"\\$&"),Un=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===vs,Ia=e=>e?.features?.askUserQuestion??{},zn=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 o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,uo.parse)(r,uo.STR|uo.OBJ|uo.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},xs=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>bs&&!Fp&&(Fp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${bs}.`)),t.slice(0,bs)},Ch=e=>xs(e)[0]??null,wh=(e,t)=>xs(e)[t]??null,qp=(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))},Vp=(e,t,n)=>{if(e!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=m("span","persona-ask-row-check");o.appendChild(r)}else{let r=m("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ah=(e,t,n,o)=>{let s=m("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=m("span","persona-ask-row-content"),i=m("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=m("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=Vp(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Sh=e=>{let n=m("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},Th=(e,t,n,o)=>{let s=m("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<bh;c++)s.appendChild(Sh(o));return s}if(p.forEach((c,u)=>{s.appendChild(Ah(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?uh:gh;if(o==="rows"){let u=m("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let b=m("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??_p,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),b.appendChild(g),u.appendChild(b);let y=Vp(o,a,p.length);y&&u.appendChild(y),s.appendChild(u)}else{let u=m("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,s.appendChild(u)}}return s},Kp=(e,t)=>{let o=m("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??_p,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=m("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??$p,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Eh=e=>{let t=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??$p,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Mh=(e,t,n)=>{let o=m("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=m("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??mh,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??yh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=m("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??hh:n.nextLabel??fh,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Ko=e=>{let t=e.getAttribute(jp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Gp=(e,t)=>{e.setAttribute(jp,JSON.stringify(t))},gn=e=>{let t=Number(e.getAttribute(Ol)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},kh=(e,t)=>{e.setAttribute(Ol,String(Math.max(0,Math.floor(t))))},Sr=e=>{let t=Number(e.getAttribute(Dl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},go=e=>e.getAttribute(Nl)==="true",Lh=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[s]=i)}}),o},Ph=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Wa=(e,t)=>{let{payload:n}=zn(t),o=xs(n),r=Ko(e),s={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},Jp=e=>{let t=Ko(e),n=gn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},Xp=e=>{if(!go(e))return;let t=Ko(e),n=gn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);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 o=Ia(n),r=xh(e),{payload:s,complete:a}=zn(t),i=go(e),p=gn(e),d=Sr(e),c=i?wh(s,p):Ch(s),u=!!c?.multiSelect,b=e.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=i?`${p+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let W=typeof c?.question=="string"?c.question:"";y.textContent=W,y.classList.toggle("persona-ask-question-skeleton",!W&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let W=Th(c,o,a,r);C.replaceWith(W)}if(r!=="rows"){let W=e.querySelector('[data-ask-free-text-row="true"]');W&&W.replaceWith(Kp(o,r))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!k?e.appendChild(Eh(o)):(!u||i)&&k&&k.remove(),e.setAttribute("data-multi-select",u?"true":"false");let P=e.querySelector('[data-ask-nav-row="true"]');if(i){let W=Mh(p,d,o);P?P.replaceWith(W):e.appendChild(W)}else P&&P.remove();Jp(e),Xp(e)},Rh=(e,t,n)=>{let o=Ia(t),r=vh(o),s=e.toolCall.id,a=xs(n),i=Math.max(1,a.length),p=i>1,d=Lh(e,a),c=p?Ph(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ar,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Dl,String(i)),u.setAttribute(Ol,String(c)),u.setAttribute(Nl,p?"true":"false"),u.setAttribute(Up,r),Gp(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),qp(u,o);let b=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=m("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",b.appendChild(g);let y=m("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",b.appendChild(y),u.appendChild(b);let k=m("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");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),u.appendChild(k),r!=="rows"&&u.appendChild(Kp(o,r)),Fl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Ih=(e,t,n)=>{let{payload:o}=zn(t),r=Math.max(1,xs(o).length);r>Sr(e)&&(e.setAttribute(Dl,String(r)),r>1&&!go(e)&&e.setAttribute(Nl,"true")),Fl(e,t,n)},Qp=(e,t)=>{let n=m("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 o=Ia(t);qp(n,o);let r=m("span","persona-ask-stub-label"),{complete:s}=zn(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Tr=(e,t,n)=>{if(!n||!Un(e)||Ia(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Ar}]`).forEach(d=>{d.getAttribute(Ar)!==r&&d.remove()});let a=n.querySelector(`[${Ar}="${zp(r)}"]`);if(a){Ih(a,e,t);return}let{payload:i}=zn(e),p=Rh(e,t,i);n.appendChild(p)},fo=(e,t)=>{if(!e)return;let n=t?`[${Ar}="${zp(t)}"]`:`[${Ar}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s: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),mo=(e,t)=>{let n=Ko(e),o=gn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Gp(e,n),Jp(e),Xp(e)},Ha=(e,t,n,o)=>{let r=Sr(e),s=Math.max(0,Math.min(r-1,o));kh(e,s),Fl(e,t,n)};var Sn="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},Ba={name:Sn,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."}]}),Cs=e=>e.variant==="tool"&&e.toolCall?.name===Sn,Ul=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Oa=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Cs(n))continue;let o=Ul(n.toolCall?.args);return o.length>0?o:null}return null},Yp=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var zl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:bs,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},ql={name:vs,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:zl,origin:"sdk",annotations:{readOnlyHint:!0}},Er=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(ql),Yp(e)&&t.push(Ba),t};var qn=require("partial-json"),Da=e=>e.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ho=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)}},Wh=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Zp=e=>e.status==="complete"?Wh(e):e.status==="pending"?"Waiting":"",Hh=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??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 eu=e=>e.status==="complete"?Hh(e):"Using tool...",Na=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},As=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Na(t)},Fa=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Na(t)},Vl=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=As(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},_a=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&ws(o,n.slice(s,a.index),[]),a[1]!==void 0?ws(o,a[1],["bold"]):a[2]!==void 0?ws(o,a[2],["italic"]):a[3]!==void 0&&ws(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ws(o,n.slice(s),[]),o},ws=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Bh=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
+ ${e.description}`:"");return window.confirm(n)},gh=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)}},fh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},mh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Ko(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function Da(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var hh="agent_",yh="flow_";function $p(e){return e.startsWith(hh)?{kind:"agentId",agentId:e}:e.startsWith(yh)?{kind:"flowId",flowId:e}:null}function jp(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let d=$p(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let r=$p(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var uo=require("partial-json");var m=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Up=()=>document.createDocumentFragment(),_e=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(s[i]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},$n=(...e)=>e.filter(Boolean).join(" ");var Cs="ask_user_question",xs=8,Sr="data-persona-ask-sheet-for",bh="Other",vh="Other\u2026",qp="Type your own answer here",Vp="Send",xh="Next",Ch="Back",wh="Submit all",Ah="Skip",Sh=3,Fl="data-ask-current-index",_l="data-ask-question-count",Kp="data-ask-answers",$l="data-ask-grouped",Gp="data-ask-layout",Th=e=>e.layout==="pills"?"pills":"rows",Eh=e=>e.getAttribute(Gp)==="pills"?"pills":"rows",zp=!1,Jp=e=>e.replace(/["\\]/g,"\\$&"),jn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Cs,Na=e=>e?.features?.askUserQuestion??{},Un=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 o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,uo.parse)(r,uo.STR|uo.OBJ|uo.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ws=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>xs&&!zp&&(zp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${xs}.`)),t.slice(0,xs)},Mh=e=>ws(e)[0]??null,kh=(e,t)=>ws(e)[t]??null,Xp=(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))},Qp=(e,t,n)=>{if(e!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=m("span","persona-ask-row-check");o.appendChild(r)}else{let r=m("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Lh=(e,t,n,o)=>{let s=m("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=m("span","persona-ask-row-content"),i=m("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=m("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=Qp(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Ph=e=>{let n=m("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},Rh=(e,t,n,o)=>{let s=m("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Sh;c++)s.appendChild(Ph(o));return s}if(p.forEach((c,u)=>{s.appendChild(Lh(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?bh:vh;if(o==="rows"){let u=m("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let b=m("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??qp,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),b.appendChild(g),u.appendChild(b);let y=Qp(o,a,p.length);y&&u.appendChild(y),s.appendChild(u)}else{let u=m("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,s.appendChild(u)}}return s},Yp=(e,t)=>{let o=m("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??qp,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=m("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Vp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Ih=e=>{let t=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Vp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Wh=(e,t,n)=>{let o=m("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=m("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Ch,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Ah,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=m("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??wh:n.nextLabel??xh,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Go=e=>{let t=e.getAttribute(Kp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Zp=(e,t)=>{e.setAttribute(Kp,JSON.stringify(t))},gn=e=>{let t=Number(e.getAttribute(Fl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Hh=(e,t)=>{e.setAttribute(Fl,String(Math.max(0,Math.floor(t))))},Tr=e=>{let t=Number(e.getAttribute(_l)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},go=e=>e.getAttribute($l)==="true",Bh=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[s]=i)}}),o},Oh=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Fa=(e,t)=>{let{payload:n}=Un(t),o=ws(n),r=Go(e),s={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},eu=e=>{let t=Go(e),n=gn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},tu=e=>{if(!go(e))return;let t=Go(e),n=gn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);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}},jl=(e,t,n)=>{let o=Na(n),r=Eh(e),{payload:s,complete:a}=Un(t),i=go(e),p=gn(e),d=Tr(e),c=i?kh(s,p):Mh(s),u=!!c?.multiSelect,b=e.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=i?`${p+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let W=typeof c?.question=="string"?c.question:"";y.textContent=W,y.classList.toggle("persona-ask-question-skeleton",!W&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let W=Rh(c,o,a,r);C.replaceWith(W)}if(r!=="rows"){let W=e.querySelector('[data-ask-free-text-row="true"]');W&&W.replaceWith(Yp(o,r))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!k?e.appendChild(Ih(o)):(!u||i)&&k&&k.remove(),e.setAttribute("data-multi-select",u?"true":"false");let P=e.querySelector('[data-ask-nav-row="true"]');if(i){let W=Wh(p,d,o);P?P.replaceWith(W):e.appendChild(W)}else P&&P.remove();eu(e),tu(e)},Dh=(e,t,n)=>{let o=Na(t),r=Th(o),s=e.toolCall.id,a=ws(n),i=Math.max(1,a.length),p=i>1,d=Bh(e,a),c=p?Oh(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Sr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(_l,String(i)),u.setAttribute(Fl,String(c)),u.setAttribute($l,p?"true":"false"),u.setAttribute(Gp,r),Zp(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Xp(u,o);let b=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=m("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",b.appendChild(g);let y=m("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",b.appendChild(y),u.appendChild(b);let k=m("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");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),u.appendChild(k),r!=="rows"&&u.appendChild(Yp(o,r)),jl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Nh=(e,t,n)=>{let{payload:o}=Un(t),r=Math.max(1,ws(o).length);r>Tr(e)&&(e.setAttribute(_l,String(r)),r>1&&!go(e)&&e.setAttribute($l,"true")),jl(e,t,n)},nu=(e,t)=>{let n=m("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 o=Na(t);Xp(n,o);let r=m("span","persona-ask-stub-label"),{complete:s}=Un(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Er=(e,t,n)=>{if(!n||!jn(e)||Na(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sr}]`).forEach(d=>{d.getAttribute(Sr)!==r&&d.remove()});let a=n.querySelector(`[${Sr}="${Jp(r)}"]`);if(a){Nh(a,e,t);return}let{payload:i}=Un(e),p=Dh(e,t,i);n.appendChild(p)},fo=(e,t)=>{if(!e)return;let n=t?`[${Sr}="${Jp(t)}"]`:`[${Sr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Ul=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),mo=(e,t)=>{let n=Go(e),o=gn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Zp(e,n),eu(e),tu(e)},_a=(e,t,n,o)=>{let r=Tr(e),s=Math.max(0,Math.min(r-1,o));Hh(e,s),jl(e,t,n)};var An="suggest_replies";var zl={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},$a={name:An,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:zl,origin:"sdk",annotations:{readOnlyHint:!0}},ql=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),As=e=>e.variant==="tool"&&e.toolCall?.name===An,Vl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},ja=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!As(n))continue;let o=Vl(n.toolCall?.args);return o.length>0?o:null}return null},ou=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var Kl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:xs,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},Gl={name:Cs,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Kl,origin:"sdk",annotations:{readOnlyHint:!0}},Mr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Gl),ou(e)&&t.push($a),t};var zn=require("partial-json"),Ua=e=>e.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ho=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)}},Fh=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},ru=e=>e.status==="complete"?Fh(e):e.status==="pending"?"Waiting":"",_h=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??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 su=e=>e.status==="complete"?_h(e):"Using tool...",za=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ts=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return za(t)},qa=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return za(t)},Jl=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ts(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Va=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ss(o,n.slice(s,a.index),[]),a[1]!==void 0?Ss(o,a[1],["bold"]):a[2]!==void 0?Ss(o,a[2],["italic"]):a[3]!==void 0&&Ss(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ss(o,n.slice(s),[]),o},Ss=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},$h=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ss=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},$a=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ja=()=>{let e=Bh();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Ua=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,qn.parse)(n,qn.STR|qn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Da(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Da(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},tu=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Da(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,qn.parse)(s,qn.STR|qn.OBJ),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},za=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var nu="4.11.1";var fn=nu;var Dh="https://api.runtype.com/v1/dispatch",qa="https://api.runtype.com";function Nh(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}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 Fh(e){switch(e){case"json":return Ua;case"regex-json":return ja;case"xml":return za;default:return $a}}var ou=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function _h(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=ou(n);if(!ou(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Ss(e);return Ss(t)!==null&&a===null?t:e}var Go=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Dh,this.headers={"Content-Type":"application/json","X-Persona-Version":fn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Fh(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new wr(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Dp(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/feedback`}async sendFeedback(t){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 r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fn},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Kl).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fn},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(i.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Bp(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=s&&i&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let b=0;;b++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&b===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||qa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,b=>{let g={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:i,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Kl).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Kl).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=p);let s=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let p=i;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.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<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,u=M=>{let _=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,v=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,E=M.tools?M.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...M,reasoning:_,toolCall:v,tools:E}},b=M=>{if(M.role!=="assistant"||M.variant)return!0;let _=Array.isArray(M.contentParts)&&M.contentParts.length>0,v=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||_||v||!!M.stopReason},g=M=>{b(M)&&n({type:"message",message:u(M)})},y=null,C=null,k={current:null},P={current:null},W=null,S="",I=new Map,j=new Map,q=new Map,w=new Map,z=new Map,V={lastId:null,byStep:new Map},Y={lastId:null,byCall:new Map},D=M=>{if(M==null)return null;try{return String(M)}catch{return null}},N=M=>D(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),le=M=>D(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),he=o,Ae=!1,Me=()=>{if(y)return y;let M,_="",v=W;return!Ae&&he?(M=he,Ae=!0,_=r??""):he&&v?M=`${he}_${v}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:M,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(y),y},ae=(M,_)=>{V.lastId=_,M&&V.byStep.set(M,_)},me=(M,_)=>{let v=M.reasoningId??M.id,E=N(M);if(v){let B=String(v);return ae(E,B),B}if(E){let B=V.byStep.get(E);if(B)return V.lastId=B,B}if(V.lastId&&!_)return V.lastId;if(!_)return null;let L=`reason-${c()}`;return ae(E,L),L},Z=M=>{let _=w.get(M);if(_)return _;let v={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return w.set(M,v),g(v),v},de=(M,_)=>{Y.lastId=_,M&&Y.byCall.set(M,_)},ee=new Set,ve=new Map,ye=new Set,pe=new Map,ke=M=>{if(!M)return!1;let _=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return _==="emit_artifact_markdown"||_==="emit_artifact_component"},Ne=(M,_)=>{let v=M.toolId??M.id,E=le(M);if(v){let B=String(v);return de(E,B),B}if(E){let B=Y.byCall.get(E);if(B)return Y.lastId=B,B}if(Y.lastId&&!_)return Y.lastId;if(!_)return null;let L=`tool-${c()}`;return de(E,L),L},$e=M=>{let _=z.get(M);if(_)return _;let v={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,v),g(v),v},Be=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let _=Number(M);if(!Number.isNaN(_)&&Number.isFinite(_))return _;let v=Date.parse(M);if(!Number.isNaN(v))return v}return Date.now()},ze=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},Ke=new Map,Le=new Map,oe=new Map,Oe=(M,_,v)=>{let E=oe.get(M);E||(E=[],oe.set(M,E));let L=0,B=E.length;for(;L<B;){let O=L+B>>>1;E[O].seq<_?L=O+1:B=O}E[L]?.seq===_?E[L]={seq:_,text:v}:E.splice(L,0,{seq:_,text:v});let K="";for(let O=0;O<E.length;O++)K+=E[O].text;return K},xt=(M,_)=>{let v=ze(_),E=Le.get(M.id),L=_h(E,v);M.rawContent=L;let B=Ke.get(M.id),K=Ee=>{let st=M.content??"";Ee.trim()!==""&&(st.trim().length===0||Ee.startsWith(st)||Ee.trimStart().startsWith(st.trim()))&&(M.content=Ee)},O=()=>{if(B){let Ee=B.close?.();Ee instanceof Promise&&Ee.catch(()=>{})}Ke.delete(M.id),Le.delete(M.id),M.streaming=!1,g(M)};if(!B){K(v),O();return}let U=Ss(L);if(U!==null&&U.trim()!==""){K(U),O();return}let ie=Ee=>{let st=typeof Ee=="string"?Ee:Ee?.text??null;if(st!==null&&st.trim()!=="")return st;let G=B.getExtractedText();return G!==null&&G.trim()!==""?G:v},Je;try{Je=B.processChunk(L)}catch{K(v),O();return}if(Je instanceof Promise){Je.then(Ee=>{K(ie(Ee)),O()}).catch(()=>{K(v),O()});return}K(ie(Je)),O()},ht=null,lt=(M,_,v,E)=>{M.rawContent=_,Ke.has(M.id)||Ke.set(M.id,this.createStreamParser());let L=Ke.get(M.id),B=_.trim().startsWith("{")||_.trim().startsWith("[");if(B&&Le.set(M.id,_),L.__isPlainTextParser===!0){M.content=E!==void 0?_:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,g(M);return}let O=L.processChunk(_);if(O instanceof Promise)O.then(U=>{let ie=typeof U=="string"?U:U?.text??null;ie!==null&&ie.trim()!==""?(M.content=ie,g(M)):!B&&!_.trim().startsWith("<")&&(M.content=E!==void 0?_:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=E!==void 0?_:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,g(M)});else{let U=typeof O=="string"?O:O?.text??null;U!==null&&U.trim()!==""?(M.content=U,g(M)):!B&&!_.trim().startsWith("<")&&(M.content=E!==void 0?_:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,g(M))}},De=(M,_)=>{let v=_??M.content;if(v==null||v===""){M.streaming=!1,g(M);return}let L=Le.get(M.id)??ze(v);M.rawContent=L;let B=Ke.get(M.id),K=null,O=!1;if(B&&(K=B.getExtractedText(),K===null&&(K=Ss(L)),K===null)){let U=B.processChunk(L);U instanceof Promise?(O=!0,U.then(ie=>{let Je=typeof ie=="string"?ie:ie?.text??null;Je!==null&&(M.content=Je,M.streaming=!1,Ke.delete(M.id),Le.delete(M.id),g(M))}).catch(()=>{})):K=typeof U=="string"?U:U?.text??null}if(!O){K!==null&&K.trim()!==""?M.content=K:Le.has(M.id)||(M.content=ze(v));let U=Ke.get(M.id);if(U){let ie=U.close?.();ie instanceof Promise&&ie.catch(()=>{}),Ke.delete(M.id)}Le.delete(M.id),M.streaming=!1,g(M)}},be=(M,_,v)=>{let E=j.get(M);if(E)return E;let L={id:`nested-${_}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:_}};return j.set(M,L),g(L),L},Qe=[],Pe,ge=new Map,ce=0,xe="agent",Ct=!1,Ce=null,ue=null,mn=new Map,Q=this.config.iterationDisplay??"separate";for(Pe=()=>{for(let M=0;M<Qe.length;M++){let _=Qe[M].payloadType,v=Qe[M].payload;if(!Ct&&xe!=="flow"&&typeof v.stepType=="string"&&(xe="flow"),_==="reasoning_start"){let E=typeof v.id=="string"?v.id:null,L=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(E&&L){I.set(E,L),be(E,L,"reasoning");continue}let B=me(v,!0)??`reason-${c()}`,K=Z(B);K.reasoning=K.reasoning??{id:B,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Be(v.startedAt??v.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(K.reasoning.scope=v.scope),K.streaming=!0,K.reasoning.status="streaming",g(K)}else if(_==="reasoning_delta"){let E=typeof v.id=="string"?v.id:null;if(E&&I.has(E)&&j.has(E)){let O=j.get(E),U=v.reasoningText??v.text??v.delta??"";U&&v.hidden!==!0&&O.reasoning&&(O.reasoning.chunks.push(String(U)),g(O));continue}let L=me(v,!1)??me(v,!0)??`reason-${c()}`,B=Z(L);B.reasoning=B.reasoning??{id:L,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Be(v.startedAt??v.timestamp);let K=v.reasoningText??v.text??v.delta??"";if(K&&v.hidden!==!0){let O=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(O!==void 0){let U=Oe(L,O,String(K));B.reasoning.chunks=[U]}else B.reasoning.chunks.push(String(K))}if(B.reasoning.status=v.done?"complete":"streaming",v.done){B.reasoning.completedAt=Be(v.completedAt??v.timestamp);let O=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-O)}B.streaming=B.reasoning.status!=="complete",g(B)}else if(_==="reasoning_complete"){let E=typeof v.id=="string"?v.id:null;if(E&&I.has(E)&&j.has(E)){let U=j.get(E);if(U.reasoning){let ie=typeof v.text=="string"?v.text:"";ie&&U.reasoning.chunks.length===0&&U.reasoning.chunks.push(ie),U.reasoning.status="complete",U.streaming=!1,g(U)}I.delete(E),j.delete(E);continue}let L=me(v,!1)??me(v,!0)??`reason-${c()}`,B=typeof v.text=="string"?v.text:"";!w.get(L)&&(B||v.scope==="loop")&&Z(L);let K=w.get(L);if(K?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(K.reasoning.scope=v.scope),B&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(B),K.reasoning.status="complete",K.reasoning.completedAt=Be(v.completedAt??v.timestamp);let U=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-U),K.streaming=!1,g(K)}let O=N(v);O&&V.byStep.delete(O)}else if(_==="tool_start"){y&&(y.streaming=!1,g(y),y=null),typeof v.iteration=="number"&&(ce=v.iteration);let E=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Ne(v,!0)??`tool-${c()}`,L=v.toolName??v.name;if(ke(L)){ee.add(E);continue}de(le(v),E);let B=$e(E),K=B.toolCall??{id:E,status:"pending"};K.name=L??K.name,K.status="running",v.parameters!==void 0?K.args=v.parameters:v.args!==void 0&&(K.args=v.args),K.startedAt=K.startedAt??Be(v.startedAt??v.timestamp),K.completedAt=void 0,K.durationMs=void 0,B.toolCall=K,B.streaming=!0,v.executionId&&(B.agentMetadata={executionId:v.executionId,iteration:v.iteration}),g(B)}else if(_==="tool_output_delta"){let E=Ne(v,!1)??Ne(v,!0)??`tool-${c()}`;if(ee.has(E))continue;let L=$e(E),B=L.toolCall??{id:E,status:"running"};B.startedAt=B.startedAt??Be(v.startedAt??v.timestamp);let K=v.text??v.delta??v.message??"";K&&(B.chunks=B.chunks??[],B.chunks.push(String(K))),B.status="running",L.toolCall=B,L.streaming=!0;let O=v.agentContext;(O||v.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:O?.executionId??v.executionId,iteration:O?.iteration??v.iteration}),g(L)}else if(_==="tool_complete"){let E=Ne(v,!1)??Ne(v,!0)??`tool-${c()}`;if(ee.has(E)){ee.delete(E);continue}let L=$e(E),B=L.toolCall??{id:E,status:"running"};B.status="complete",v.result!==void 0&&(B.result=v.result),typeof v.duration=="number"&&(B.duration=v.duration),B.completedAt=Be(v.completedAt??v.timestamp);let K=v.duration??v.executionTime;if(typeof K=="number")B.durationMs=K;else{let ie=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-ie)}L.toolCall=B,L.streaming=!1;let O=v.agentContext;(O||v.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:O?.executionId??v.executionId,iteration:O?.iteration??v.iteration}),g(L);let U=le(v);U&&Y.byCall.delete(U)}else if(_==="await"&&v.toolName){let E=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,L=E??v.toolId??`local-${c()}`,B=$e(L),K=v.toolName,O=v.origin==="webmcp"&&!po(K)?`webmcp:${K}`:K,U=po(O),ie=B.toolCall??{id:L,status:"pending"};ie.name=O,ie.args=v.parameters,ie.status=U?"running":"complete",ie.chunks=ie.chunks??[],ie.startedAt=ie.startedAt??Be(v.startedAt??v.timestamp??v.awaitedAt),U?(ie.completedAt=void 0,ie.duration=void 0,ie.durationMs=void 0):ie.completedAt=ie.completedAt??ie.startedAt,B.toolCall=ie,B.streaming=!1,B.agentMetadata={...B.agentMetadata,executionId:v.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...E?{webMcpToolCallId:E}:{}},g(B)}else if(_==="text_start"){let E=typeof v.id=="string"?v.id:null,L=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(E&&L){I.set(E,L);continue}let B=y;B&&(xe==="flow"?(De(B),ht=B):(B.streaming=!1,g(B)),y=null),W=typeof v.id=="string"?v.id:W,S=""}else if(_==="text_delta"){let E=typeof v.id=="string"?v.id:null,L=E?I.get(E):void 0;if(E&&L){let K=typeof v.delta=="string"?v.delta:"",O=(q.get(E)??"")+K;if(q.set(E,O),O.trim()==="")continue;let U=be(E,L);U.agentMetadata={...U.agentMetadata,executionId:v.executionId,parentToolId:L},lt(U,O,K,void 0);continue}if(W=typeof v.id=="string"?v.id:W,xe==="flow"){let K=typeof v.delta=="string"?v.delta:"";if(S+=K,S.trim()==="")continue;let O=Me();O.agentMetadata={executionId:v.executionId,iteration:v.iteration},lt(O,S,K,void 0),C=O;continue}let B=Me();B.content+=v.delta??"",B.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:Ce??void 0,agentName:ue?.agentName},C=B,g(B)}else if(_==="text_complete"){let E=typeof v.id=="string"?v.id:null;if(E&&I.has(E)){let B=j.get(E);B&&De(B),I.delete(E),q.delete(E),j.delete(E);continue}let L=y;L&&(xe==="flow"?(De(L),ht=L):((L.content??"")===""&&typeof v.text=="string"&&(L.content=v.text),L.streaming=!1,g(L)),y=null),W=null,S=""}else if(_==="step_complete"){let E=v.stepType,L=v.executionType;if(E==="tool"||L==="context")continue;if(v.success===!1){let B=v.error,K=typeof B=="string"&&B!==""?B:B!=null&&typeof B=="object"&&Reflect.has(B,"message")?String(B.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let O=y;O&&O.streaming&&(O.streaming=!1,g(O)),n({type:"status",status:"idle"});continue}{let B=ht;ht=null;let K=v.stopReason,O=v.result?.response;if(B)K&&(B.stopReason=K),O!=null?xt(B,O):B.streaming!==!1&&(Ke.delete(B.id),Le.delete(B.id),B.streaming=!1,g(B));else{let U=O!=null&&O!=="";if(U||K){let ie=Me();K&&(ie.stopReason=K),U?De(ie,O):(ie.streaming=!1,g(ie))}}continue}}else if(_==="execution_start")xe=v.kind==="flow"?"flow":"agent",Ct=!0,xe==="agent"&&(ue={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:Be(v.startedAt)});else if(_==="turn_start"){let E=typeof v.iteration=="number"?v.iteration:ce;if(E!==ce){if(ue&&(ue.currentIteration=E),Q==="separate"&&E>1){let L=y;L&&(L.streaming=!1,g(L),mn.set(E-1,L),y=null)}ce=E}Ce=typeof v.id=="string"?v.id:null,C=null}else if(_==="tool_input_delta"){let E=v.toolCallId??Y.lastId;if(E){let L=z.get(E);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(v.delta??""),g(L))}}else{if(_==="tool_input_complete")continue;if(_==="turn_complete"){let E=v.stopReason,L=y??C;if(E&&L!==null){let B=v.id;(!B||L.agentMetadata?.turnId===B)&&(L.stopReason=E,g(L))}Ce===v.id&&(Ce=null)}else if(_==="media_start"){let E=String(v.id);ge.set(E,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(_==="media_delta"){let E=ge.get(String(v.id));E&&typeof v.delta=="string"&&E.parts.push(v.delta)}else if(_==="media_complete"){let E=String(v.id),L=ge.get(E);ge.delete(E);let B=(typeof v.mediaType=="string"?v.mediaType:void 0)??L?.mediaType??"application/octet-stream",K=typeof v.data=="string"?v.data:void 0,O=typeof v.url=="string"?v.url:L&&L.parts.length>0?L.parts.join(""):void 0,U=null;if(K)U={type:"media",data:K,mediaType:B};else if(O){let st=B.toLowerCase();U={type:st==="image"||st.startsWith("image/")?"image-url":"file-url",url:O,mediaType:B}}let ie=v.toolCallId??L?.toolCallId,Je=U?[U]:[],Ee=[];for(let st of Je){if(!st||typeof st!="object")continue;let G=st,qe=typeof G.type=="string"?G.type:void 0,Se=typeof G.mediaType=="string"?G.mediaType.toLowerCase():"",He=null,Re="";if(qe==="media"){let Ze=typeof G.data=="string"?G.data:void 0;if(!Ze)continue;Re=Se.length>0?Se:"application/octet-stream",He=`data:${Re};base64,${Ze}`}else if(qe==="image-url"){let Ze=typeof G.url=="string"?G.url:void 0;if(!Ze)continue;Re=Se,He=Ze}else if(qe==="file-url"){let Ze=typeof G.url=="string"?G.url:void 0;if(!Ze)continue;Re=Se,He=Ze}else continue;if(He)if(qe==="image-url"||Re.startsWith("image/"))Ee.push({type:"image",image:He,...Re.includes("/")?{mimeType:Re}:{}});else if(Re.startsWith("audio/"))Ee.push({type:"audio",audio:He,mimeType:Re});else if(Re.startsWith("video/"))Ee.push({type:"video",video:He,mimeType:Re});else{let Ze=Re||"application/octet-stream";Ee.push({type:"file",data:He,mimeType:Ze,filename:Nh(Ze)})}}if(Ee.length>0){let st=c(),G=ie,Se={id:`agent-media-${typeof G=="string"&&G.length>0?`${G}-${st}`:String(st)}`,role:"assistant",content:"",contentParts:Ee,createdAt:new Date().toISOString(),streaming:!1,sequence:st,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:ce}};g(Se);let He=y;He&&(He.streaming=!1,g(He)),y=null,k.current=null}}else if(_==="execution_complete"){let E=v.kind??xe;E==="agent"&&ue&&(ue.status=v.success?"complete":"error",ue.completedAt=Be(v.completedAt),ue.stopReason=v.stopReason);let L=y;L&&(E==="flow"&&L.streaming!==!1?De(L):(L.streaming=!1,g(L)),y=null),W=null,S="",ht=null,n({type:"status",status:"idle",terminal:!0})}else if(_==="execution_error"){let E=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(E)})}else if(_!=="ping"){if(_==="approval_start"){let E=v.approvalId??`approval-${c()}`,L={id:`approval-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:E,status:"pending",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(L)}else if(_==="step_await"&&v.awaitReason==="approval_required"){let E=v.approvalId??`approval-${c()}`,L={id:`approval-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:E,status:"pending",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(L)}else if(_==="approval_complete"){let E=v.approvalId;if(E){let B={id:`approval-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:E,status:v.decision??"approved",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};g(B)}}else if(_==="artifact_start"||_==="artifact_delta"||_==="artifact_update"||_==="artifact_complete"){if(_==="artifact_start"){let E=v.artifactType,L=String(v.id),B=typeof v.title=="string"?v.title:void 0,K=v.file,O;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(O={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:L,artifactType:E,title:B,component:typeof v.component=="string"?v.component:void 0,...O?{file:O}:{}});let U=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(pe.set(L,{markdown:"",title:B,file:O,...U?{props:U}:{}}),!ye.has(L)){ye.add(L);let ie=Vo(this.config.features?.artifacts,E),Je=typeof v.component=="string"?v.component:void 0,Ee={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Ra(ie,{artifactId:L,title:B,artifactType:E,status:"streaming",...O?{file:O}:{},...Je?{component:Je}:{}})};ve.set(L,Ee),g(Ee)}}else if(_==="artifact_delta"){let E=String(v.id),L=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:E,artDelta:L});let B=pe.get(E);B&&(B.markdown+=L)}else if(_==="artifact_update"){let E=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:E,component:typeof v.component=="string"?v.component:void 0});let L=pe.get(String(v.id));L&&(L.props={...L.props??{},...E})}else if(_==="artifact_complete"){let E=String(v.id);n({type:"artifact_complete",id:E});let L=ve.get(E);if(L){L.streaming=!1;try{let B=JSON.parse(L.rawContent??"{}");if(B.props){B.props.status="complete";let K=pe.get(E);K?.markdown&&(B.props.markdown=K.markdown),K?.file&&(B.props.file=K.file),B.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(B.props.componentProps=K.props)}L.rawContent=JSON.stringify(B)}catch{}pe.delete(E),g(L),ve.delete(E)}}}else if(_==="transcript_insert"){let E=v.message;if(!E||typeof E!="object")continue;let L=String(E.id??`msg-${c()}`),B=E.role,O={id:L,role:B==="user"?"user":B==="system"?"system":"assistant",content:typeof E.content=="string"?E.content:"",rawContent:typeof E.rawContent=="string"?E.rawContent:void 0,createdAt:typeof E.createdAt=="string"?E.createdAt:new Date().toISOString(),streaming:E.streaming===!0,...typeof E.variant=="string"?{variant:E.variant}:{},sequence:c()};if(g(O),O.rawContent)try{let ie=JSON.parse(O.rawContent)?.props?.artifactId;typeof ie=="string"&&ye.add(ie)}catch{}y=null,k.current=null,Ke.delete(L),Le.delete(L)}else if(_==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let E=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(E)});let L=y;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}else if(_==="step_error"||_==="dispatch_error"||_==="flow_error"){let E=null;if(v.error instanceof Error)E=v.error;else if(_==="dispatch_error"){let L=v.message??v.error;L!=null&&L!==""&&(E=new Error(String(L)))}else{let L=v.error;typeof L=="string"&&L!==""?E=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(E=new Error(String(L.message??L)))}if(E){n({type:"error",error:E});let L=y;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}Qe.length=0};;){let{done:M,value:_}=await s.read();if(M)break;i+=a.decode(_,{stream:!0});let v=i.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ka=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ga=()=>{let e=$h();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Ja=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,zn.parse)(n,zn.STR|zn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Ua(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Ua(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},au=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Ua(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ua(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,zn.parse)(s,zn.STR|zn.OBJ),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Xa=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var iu="4.13.0";var qn=iu;var Uh="https://api.runtype.com/v1/dispatch",Qa="https://api.runtype.com";function zh(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Xl=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 qh(e){switch(e){case"json":return Ja;case"regex-json":return Ga;case"xml":return Xa;default:return Ka}}var lu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Vh(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=lu(n);if(!lu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Es(e);return Es(t)!==null&&a===null?t:e}var Jo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Uh,this.headers={"Content-Type":"application/json","X-Persona-Version":qn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??qh(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Ar(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=jp(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Qa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Qa}/v1/client/feedback`}async sendFeedback(t){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 r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qn},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Xl).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qn},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(i.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Qa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?_p(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=s&&i&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let b=0;;b++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&b===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Qa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...Mr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,b=>{let g={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:i,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Xl).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Mr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Xl).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=p);let s=[...Mr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let p=i;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.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<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,u=M=>{let _=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,v=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,E=M.tools?M.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...M,reasoning:_,toolCall:v,tools:E}},b=M=>{if(M.role!=="assistant"||M.variant)return!0;let _=Array.isArray(M.contentParts)&&M.contentParts.length>0,v=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||_||v||!!M.stopReason},g=M=>{b(M)&&n({type:"message",message:u(M)})},y=null,C=null,k={current:null},P={current:null},W=null,S="",I=new Map,j=new Map,q=new Map,w=new Map,z=new Map,V={lastId:null,byStep:new Map},Y={lastId:null,byCall:new Map},D=M=>{if(M==null)return null;try{return String(M)}catch{return null}},N=M=>D(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),ce=M=>D(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),he=o,Ae=!1,Me=()=>{if(y)return y;let M,_="",v=W;return!Ae&&he?(M=he,Ae=!0,_=r??""):he&&v?M=`${he}_${v}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:M,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(y),y},ae=(M,_)=>{V.lastId=_,M&&V.byStep.set(M,_)},me=(M,_)=>{let v=M.reasoningId??M.id,E=N(M);if(v){let B=String(v);return ae(E,B),B}if(E){let B=V.byStep.get(E);if(B)return V.lastId=B,B}if(V.lastId&&!_)return V.lastId;if(!_)return null;let L=`reason-${c()}`;return ae(E,L),L},Z=M=>{let _=w.get(M);if(_)return _;let v={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return w.set(M,v),g(v),v},de=(M,_)=>{Y.lastId=_,M&&Y.byCall.set(M,_)},ee=new Set,ve=new Map,ye=new Set,pe=new Map,ke=M=>{if(!M)return!1;let _=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return _==="emit_artifact_markdown"||_==="emit_artifact_component"},Ne=(M,_)=>{let v=M.toolId??M.id,E=ce(M);if(v){let B=String(v);return de(E,B),B}if(E){let B=Y.byCall.get(E);if(B)return Y.lastId=B,B}if(Y.lastId&&!_)return Y.lastId;if(!_)return null;let L=`tool-${c()}`;return de(E,L),L},$e=M=>{let _=z.get(M);if(_)return _;let v={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,v),g(v),v},Be=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let _=Number(M);if(!Number.isNaN(_)&&Number.isFinite(_))return _;let v=Date.parse(M);if(!Number.isNaN(v))return v}return Date.now()},ze=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},Ke=new Map,Le=new Map,oe=new Map,Oe=(M,_,v)=>{let E=oe.get(M);E||(E=[],oe.set(M,E));let L=0,B=E.length;for(;L<B;){let O=L+B>>>1;E[O].seq<_?L=O+1:B=O}E[L]?.seq===_?E[L]={seq:_,text:v}:E.splice(L,0,{seq:_,text:v});let K="";for(let O=0;O<E.length;O++)K+=E[O].text;return K},xt=(M,_)=>{let v=ze(_),E=Le.get(M.id),L=Vh(E,v);M.rawContent=L;let B=Ke.get(M.id),K=Ee=>{let st=M.content??"";Ee.trim()!==""&&(st.trim().length===0||Ee.startsWith(st)||Ee.trimStart().startsWith(st.trim()))&&(M.content=Ee)},O=()=>{if(B){let Ee=B.close?.();Ee instanceof Promise&&Ee.catch(()=>{})}Ke.delete(M.id),Le.delete(M.id),M.streaming=!1,g(M)};if(!B){K(v),O();return}let U=Es(L);if(U!==null&&U.trim()!==""){K(U),O();return}let ie=Ee=>{let st=typeof Ee=="string"?Ee:Ee?.text??null;if(st!==null&&st.trim()!=="")return st;let G=B.getExtractedText();return G!==null&&G.trim()!==""?G:v},Je;try{Je=B.processChunk(L)}catch{K(v),O();return}if(Je instanceof Promise){Je.then(Ee=>{K(ie(Ee)),O()}).catch(()=>{K(v),O()});return}K(ie(Je)),O()},ht=null,lt=(M,_,v,E)=>{M.rawContent=_,Ke.has(M.id)||Ke.set(M.id,this.createStreamParser());let L=Ke.get(M.id),B=_.trim().startsWith("{")||_.trim().startsWith("[");if(B&&Le.set(M.id,_),L.__isPlainTextParser===!0){M.content=E!==void 0?_:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,g(M);return}let O=L.processChunk(_);if(O instanceof Promise)O.then(U=>{let ie=typeof U=="string"?U:U?.text??null;ie!==null&&ie.trim()!==""?(M.content=ie,g(M)):!B&&!_.trim().startsWith("<")&&(M.content=E!==void 0?_:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=E!==void 0?_:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,g(M)});else{let U=typeof O=="string"?O:O?.text??null;U!==null&&U.trim()!==""?(M.content=U,g(M)):!B&&!_.trim().startsWith("<")&&(M.content=E!==void 0?_:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,g(M))}},De=(M,_)=>{let v=_??M.content;if(v==null||v===""){M.streaming=!1,g(M);return}let L=Le.get(M.id)??ze(v);M.rawContent=L;let B=Ke.get(M.id),K=null,O=!1;if(B&&(K=B.getExtractedText(),K===null&&(K=Es(L)),K===null)){let U=B.processChunk(L);U instanceof Promise?(O=!0,U.then(ie=>{let Je=typeof ie=="string"?ie:ie?.text??null;Je!==null&&(M.content=Je,M.streaming=!1,Ke.delete(M.id),Le.delete(M.id),g(M))}).catch(()=>{})):K=typeof U=="string"?U:U?.text??null}if(!O){K!==null&&K.trim()!==""?M.content=K:Le.has(M.id)||(M.content=ze(v));let U=Ke.get(M.id);if(U){let ie=U.close?.();ie instanceof Promise&&ie.catch(()=>{}),Ke.delete(M.id)}Le.delete(M.id),M.streaming=!1,g(M)}},be=(M,_,v)=>{let E=j.get(M);if(E)return E;let L={id:`nested-${_}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:_}};return j.set(M,L),g(L),L},Qe=[],Pe,ge=new Map,le=0,xe="agent",Ct=!1,Ce=null,ue=null,fn=new Map,Q=this.config.iterationDisplay??"separate";for(Pe=()=>{for(let M=0;M<Qe.length;M++){let _=Qe[M].payloadType,v=Qe[M].payload;if(!Ct&&xe!=="flow"&&typeof v.stepType=="string"&&(xe="flow"),_==="reasoning_start"){let E=typeof v.id=="string"?v.id:null,L=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(E&&L){I.set(E,L),be(E,L,"reasoning");continue}let B=me(v,!0)??`reason-${c()}`,K=Z(B);K.reasoning=K.reasoning??{id:B,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Be(v.startedAt??v.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(K.reasoning.scope=v.scope),K.streaming=!0,K.reasoning.status="streaming",g(K)}else if(_==="reasoning_delta"){let E=typeof v.id=="string"?v.id:null;if(E&&I.has(E)&&j.has(E)){let O=j.get(E),U=v.reasoningText??v.text??v.delta??"";U&&v.hidden!==!0&&O.reasoning&&(O.reasoning.chunks.push(String(U)),g(O));continue}let L=me(v,!1)??me(v,!0)??`reason-${c()}`,B=Z(L);B.reasoning=B.reasoning??{id:L,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Be(v.startedAt??v.timestamp);let K=v.reasoningText??v.text??v.delta??"";if(K&&v.hidden!==!0){let O=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(O!==void 0){let U=Oe(L,O,String(K));B.reasoning.chunks=[U]}else B.reasoning.chunks.push(String(K))}if(B.reasoning.status=v.done?"complete":"streaming",v.done){B.reasoning.completedAt=Be(v.completedAt??v.timestamp);let O=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-O)}B.streaming=B.reasoning.status!=="complete",g(B)}else if(_==="reasoning_complete"){let E=typeof v.id=="string"?v.id:null;if(E&&I.has(E)&&j.has(E)){let U=j.get(E);if(U.reasoning){let ie=typeof v.text=="string"?v.text:"";ie&&U.reasoning.chunks.length===0&&U.reasoning.chunks.push(ie),U.reasoning.status="complete",U.streaming=!1,g(U)}I.delete(E),j.delete(E);continue}let L=me(v,!1)??me(v,!0)??`reason-${c()}`,B=typeof v.text=="string"?v.text:"";!w.get(L)&&(B||v.scope==="loop")&&Z(L);let K=w.get(L);if(K?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(K.reasoning.scope=v.scope),B&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(B),K.reasoning.status="complete",K.reasoning.completedAt=Be(v.completedAt??v.timestamp);let U=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-U),K.streaming=!1,g(K)}let O=N(v);O&&V.byStep.delete(O)}else if(_==="tool_start"){y&&(y.streaming=!1,g(y),y=null),typeof v.iteration=="number"&&(le=v.iteration);let E=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Ne(v,!0)??`tool-${c()}`,L=v.toolName??v.name;if(ke(L)){ee.add(E);continue}de(ce(v),E);let B=$e(E),K=B.toolCall??{id:E,status:"pending"};K.name=L??K.name,K.status="running",v.parameters!==void 0?K.args=v.parameters:v.args!==void 0&&(K.args=v.args),K.startedAt=K.startedAt??Be(v.startedAt??v.timestamp),K.completedAt=void 0,K.durationMs=void 0,B.toolCall=K,B.streaming=!0,v.executionId&&(B.agentMetadata={executionId:v.executionId,iteration:v.iteration}),g(B)}else if(_==="tool_output_delta"){let E=Ne(v,!1)??Ne(v,!0)??`tool-${c()}`;if(ee.has(E))continue;let L=$e(E),B=L.toolCall??{id:E,status:"running"};B.startedAt=B.startedAt??Be(v.startedAt??v.timestamp);let K=v.text??v.delta??v.message??"";K&&(B.chunks=B.chunks??[],B.chunks.push(String(K))),B.status="running",L.toolCall=B,L.streaming=!0;let O=v.agentContext;(O||v.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:O?.executionId??v.executionId,iteration:O?.iteration??v.iteration}),g(L)}else if(_==="tool_complete"){let E=Ne(v,!1)??Ne(v,!0)??`tool-${c()}`;if(ee.has(E)){ee.delete(E);continue}let L=$e(E),B=L.toolCall??{id:E,status:"running"};B.status="complete",v.result!==void 0&&(B.result=v.result),typeof v.duration=="number"&&(B.duration=v.duration),B.completedAt=Be(v.completedAt??v.timestamp);let K=v.duration??v.executionTime;if(typeof K=="number")B.durationMs=K;else{let ie=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-ie)}L.toolCall=B,L.streaming=!1;let O=v.agentContext;(O||v.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:O?.executionId??v.executionId,iteration:O?.iteration??v.iteration}),g(L);let U=ce(v);U&&Y.byCall.delete(U)}else if(_==="await"&&v.toolName){let E=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,L=E??v.toolId??`local-${c()}`,B=$e(L),K=v.toolName,O=v.origin==="webmcp"&&!po(K)?`webmcp:${K}`:K,U=po(O),ie=B.toolCall??{id:L,status:"pending"};ie.name=O,ie.args=v.parameters,ie.status=U?"running":"complete",ie.chunks=ie.chunks??[],ie.startedAt=ie.startedAt??Be(v.startedAt??v.timestamp??v.awaitedAt),U?(ie.completedAt=void 0,ie.duration=void 0,ie.durationMs=void 0):ie.completedAt=ie.completedAt??ie.startedAt,B.toolCall=ie,B.streaming=!1,B.agentMetadata={...B.agentMetadata,executionId:v.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...E?{webMcpToolCallId:E}:{}},g(B)}else if(_==="text_start"){let E=typeof v.id=="string"?v.id:null,L=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(E&&L){I.set(E,L);continue}let B=y;B&&(xe==="flow"?(De(B),ht=B):(B.streaming=!1,g(B)),y=null),W=typeof v.id=="string"?v.id:W,S=""}else if(_==="text_delta"){let E=typeof v.id=="string"?v.id:null,L=E?I.get(E):void 0;if(E&&L){let K=typeof v.delta=="string"?v.delta:"",O=(q.get(E)??"")+K;if(q.set(E,O),O.trim()==="")continue;let U=be(E,L);U.agentMetadata={...U.agentMetadata,executionId:v.executionId,parentToolId:L},lt(U,O,K,void 0);continue}if(W=typeof v.id=="string"?v.id:W,xe==="flow"){let K=typeof v.delta=="string"?v.delta:"";if(S+=K,S.trim()==="")continue;let O=Me();O.agentMetadata={executionId:v.executionId,iteration:v.iteration},lt(O,S,K,void 0),C=O;continue}let B=Me();B.content+=v.delta??"",B.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:Ce??void 0,agentName:ue?.agentName},C=B,g(B)}else if(_==="text_complete"){let E=typeof v.id=="string"?v.id:null;if(E&&I.has(E)){let B=j.get(E);B&&De(B),I.delete(E),q.delete(E),j.delete(E);continue}let L=y;L&&(xe==="flow"?(De(L),ht=L):((L.content??"")===""&&typeof v.text=="string"&&(L.content=v.text),L.streaming=!1,g(L)),y=null),W=null,S=""}else if(_==="step_complete"){let E=v.stepType,L=v.executionType;if(E==="tool"||L==="context")continue;if(v.success===!1){let B=v.error,K=typeof B=="string"&&B!==""?B:B!=null&&typeof B=="object"&&Reflect.has(B,"message")?String(B.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let O=y;O&&O.streaming&&(O.streaming=!1,g(O)),n({type:"status",status:"idle"});continue}{let B=ht;ht=null;let K=v.stopReason,O=v.result?.response;if(B)K&&(B.stopReason=K),O!=null?xt(B,O):B.streaming!==!1&&(Ke.delete(B.id),Le.delete(B.id),B.streaming=!1,g(B));else{let U=O!=null&&O!=="";if(U||K){let ie=Me();K&&(ie.stopReason=K),U?De(ie,O):(ie.streaming=!1,g(ie))}}continue}}else if(_==="execution_start")xe=v.kind==="flow"?"flow":"agent",Ct=!0,xe==="agent"&&(ue={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:Be(v.startedAt)});else if(_==="turn_start"){let E=typeof v.iteration=="number"?v.iteration:le;if(E!==le){if(ue&&(ue.currentIteration=E),Q==="separate"&&E>1){let L=y;L&&(L.streaming=!1,g(L),fn.set(E-1,L),y=null)}le=E}Ce=typeof v.id=="string"?v.id:null,C=null}else if(_==="tool_input_delta"){let E=v.toolCallId??Y.lastId;if(E){let L=z.get(E);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(v.delta??""),g(L))}}else{if(_==="tool_input_complete")continue;if(_==="turn_complete"){let E=v.stopReason,L=y??C;if(E&&L!==null){let B=v.id;(!B||L.agentMetadata?.turnId===B)&&(L.stopReason=E,g(L))}Ce===v.id&&(Ce=null)}else if(_==="media_start"){let E=String(v.id);ge.set(E,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(_==="media_delta"){let E=ge.get(String(v.id));E&&typeof v.delta=="string"&&E.parts.push(v.delta)}else if(_==="media_complete"){let E=String(v.id),L=ge.get(E);ge.delete(E);let B=(typeof v.mediaType=="string"?v.mediaType:void 0)??L?.mediaType??"application/octet-stream",K=typeof v.data=="string"?v.data:void 0,O=typeof v.url=="string"?v.url:L&&L.parts.length>0?L.parts.join(""):void 0,U=null;if(K)U={type:"media",data:K,mediaType:B};else if(O){let st=B.toLowerCase();U={type:st==="image"||st.startsWith("image/")?"image-url":"file-url",url:O,mediaType:B}}let ie=v.toolCallId??L?.toolCallId,Je=U?[U]:[],Ee=[];for(let st of Je){if(!st||typeof st!="object")continue;let G=st,qe=typeof G.type=="string"?G.type:void 0,Se=typeof G.mediaType=="string"?G.mediaType.toLowerCase():"",He=null,Re="";if(qe==="media"){let Ze=typeof G.data=="string"?G.data:void 0;if(!Ze)continue;Re=Se.length>0?Se:"application/octet-stream",He=`data:${Re};base64,${Ze}`}else if(qe==="image-url"){let Ze=typeof G.url=="string"?G.url:void 0;if(!Ze)continue;Re=Se,He=Ze}else if(qe==="file-url"){let Ze=typeof G.url=="string"?G.url:void 0;if(!Ze)continue;Re=Se,He=Ze}else continue;if(He)if(qe==="image-url"||Re.startsWith("image/"))Ee.push({type:"image",image:He,...Re.includes("/")?{mimeType:Re}:{}});else if(Re.startsWith("audio/"))Ee.push({type:"audio",audio:He,mimeType:Re});else if(Re.startsWith("video/"))Ee.push({type:"video",video:He,mimeType:Re});else{let Ze=Re||"application/octet-stream";Ee.push({type:"file",data:He,mimeType:Ze,filename:zh(Ze)})}}if(Ee.length>0){let st=c(),G=ie,Se={id:`agent-media-${typeof G=="string"&&G.length>0?`${G}-${st}`:String(st)}`,role:"assistant",content:"",contentParts:Ee,createdAt:new Date().toISOString(),streaming:!1,sequence:st,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:le}};g(Se);let He=y;He&&(He.streaming=!1,g(He)),y=null,k.current=null}}else if(_==="execution_complete"){let E=v.kind??xe;E==="agent"&&ue&&(ue.status=v.success?"complete":"error",ue.completedAt=Be(v.completedAt),ue.stopReason=v.stopReason);let L=y;L&&(E==="flow"&&L.streaming!==!1?De(L):(L.streaming=!1,g(L)),y=null),W=null,S="",ht=null,n({type:"status",status:"idle",terminal:!0})}else if(_==="execution_error"){let E=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(E)})}else if(_!=="ping"){if(_==="approval_start"){let E=v.approvalId??`approval-${c()}`,L={id:`approval-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:E,status:"pending",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(L)}else if(_==="step_await"&&v.awaitReason==="approval_required"){let E=v.approvalId??`approval-${c()}`,L={id:`approval-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:E,status:"pending",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(L)}else if(_==="approval_complete"){let E=v.approvalId;if(E){let B={id:`approval-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:E,status:v.decision??"approved",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};g(B)}}else if(_==="artifact_start"||_==="artifact_delta"||_==="artifact_update"||_==="artifact_complete"){if(_==="artifact_start"){let E=v.artifactType,L=String(v.id),B=typeof v.title=="string"?v.title:void 0,K=v.file,O;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(O={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:L,artifactType:E,title:B,component:typeof v.component=="string"?v.component:void 0,...O?{file:O}:{}});let U=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(pe.set(L,{markdown:"",title:B,file:O,...U?{props:U}:{}}),!ye.has(L)){ye.add(L);let ie=Ko(this.config.features?.artifacts,E),Je=typeof v.component=="string"?v.component:void 0,Ee={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Da(ie,{artifactId:L,title:B,artifactType:E,status:"streaming",...O?{file:O}:{},...Je?{component:Je}:{}})};ve.set(L,Ee),g(Ee)}}else if(_==="artifact_delta"){let E=String(v.id),L=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:E,artDelta:L});let B=pe.get(E);B&&(B.markdown+=L)}else if(_==="artifact_update"){let E=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:E,component:typeof v.component=="string"?v.component:void 0});let L=pe.get(String(v.id));L&&(L.props={...L.props??{},...E})}else if(_==="artifact_complete"){let E=String(v.id);n({type:"artifact_complete",id:E});let L=ve.get(E);if(L){L.streaming=!1;try{let B=JSON.parse(L.rawContent??"{}");if(B.props){B.props.status="complete";let K=pe.get(E);K?.markdown&&(B.props.markdown=K.markdown),K?.file&&(B.props.file=K.file),B.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(B.props.componentProps=K.props)}L.rawContent=JSON.stringify(B)}catch{}pe.delete(E),g(L),ve.delete(E)}}}else if(_==="transcript_insert"){let E=v.message;if(!E||typeof E!="object")continue;let L=String(E.id??`msg-${c()}`),B=E.role,O={id:L,role:B==="user"?"user":B==="system"?"system":"assistant",content:typeof E.content=="string"?E.content:"",rawContent:typeof E.rawContent=="string"?E.rawContent:void 0,createdAt:typeof E.createdAt=="string"?E.createdAt:new Date().toISOString(),streaming:E.streaming===!0,...typeof E.variant=="string"?{variant:E.variant}:{},sequence:c()};if(g(O),O.rawContent)try{let ie=JSON.parse(O.rawContent)?.props?.artifactId;typeof ie=="string"&&ye.add(ie)}catch{}y=null,k.current=null,Ke.delete(L),Le.delete(L)}else if(_==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let E=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(E)});let L=y;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}else if(_==="step_error"||_==="dispatch_error"||_==="flow_error"){let E=null;if(v.error instanceof Error)E=v.error;else if(_==="dispatch_error"){let L=v.message??v.error;L!=null&&L!==""&&(E=new Error(String(L)))}else{let L=v.error;typeof L=="string"&&L!==""?E=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(E=new Error(String(L.message??L)))}if(E){n({type:"error",error:E});let L=y;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}Qe.length=0};;){let{done:M,value:_}=await s.read();if(M)break;i+=a.decode(_,{stream:!0});let v=i.split(`
12
12
 
13
13
  `);i=v.pop()??"";for(let E of v){let L=E.split(`
14
- `),B="message",K="",O=null;for(let Ee of L)Ee.startsWith("event:")?B=Ee.replace("event:","").trim():Ee.startsWith("data:")?K+=Ee.replace("data:","").trim():Ee.startsWith("id:")&&(O=Ee.slice(3).trim());let U=()=>{O!==null&&O!==""&&n({type:"cursor",id:O})};if(!K){U();continue}let ie;try{ie=JSON.parse(K)}catch(Ee){n({type:"error",error:Ee instanceof Error?Ee:new Error("Failed to parse chat stream payload")});continue}let Je=B!=="message"?B:ie.type??"message";if(this.onSSEEvent?.(Je,ie),this.parseSSEEvent){k.current=y;let Ee=await this.handleCustomSSEEvent(ie,n,k,g,c,P);if(k.current&&k.current!==y&&(y=k.current),Ee){U();continue}}Qe.push({payloadType:Je,payload:ie}),Pe(),U()}}Pe()}};function ru(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Mr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function yo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Va="[Image]";function su(e){return typeof e=="string"?[{type:"text",text:e}]:e}function au(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ka(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function iu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function bo(e){return{type:"text",text:e}}function lu(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function cu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function du(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 pu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],$h=["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"],Vn=[...pu,...$h];function jh(e){return pu.includes(e)||e.startsWith("image/")}function Ga(e){return jh(e.type)}async function uu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ga(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function gu(e,t=Vn,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 Uh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function fu(e,t){let n=Uh(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 mu=16e3,zh=24e3,qh=4096,Vh=1380533830;function Kh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Vh?new Uint8Array(e,44):new Uint8Array(e)}function Gh(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Ts=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(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:mu,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:mu});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new kr(zh);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),i.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Gh(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let b=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}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,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(qh,1,1);this.processor=a,a.onaudioprocess=i=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Kh(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Jo=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<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}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 vo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ts(e.runtype);case"browser":if(!Jo.isSupported())throw new Error("Browser speech recognition not supported");return new Jo(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 Ja(e){if(e?.type==="custom"&&e.custom)return vo({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return vo({type:"runtype",runtype:e.runtype});if(Jo.isSupported())return vo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Es(e){try{return Ja(e),!0}catch{return!1}}function Lr(e){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 n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var xo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Lr(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Xo=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!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){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Jl(e){if(!e)return"";let t=Jh(e);return hu(t!==null?t:e)}function Jh(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 o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function hu(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
14
+ `),B="message",K="",O=null;for(let Ee of L)Ee.startsWith("event:")?B=Ee.replace("event:","").trim():Ee.startsWith("data:")?K+=Ee.replace("data:","").trim():Ee.startsWith("id:")&&(O=Ee.slice(3).trim());let U=()=>{O!==null&&O!==""&&n({type:"cursor",id:O})};if(!K){U();continue}let ie;try{ie=JSON.parse(K)}catch(Ee){n({type:"error",error:Ee instanceof Error?Ee:new Error("Failed to parse chat stream payload")});continue}let Je=B!=="message"?B:ie.type??"message";if(this.onSSEEvent?.(Je,ie),this.parseSSEEvent){k.current=y;let Ee=await this.handleCustomSSEEvent(ie,n,k,g,c,P);if(k.current&&k.current!==y&&(y=k.current),Ee){U();continue}}Qe.push({payloadType:Je,payload:ie}),Pe(),U()}}Pe()}};function cu(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function kr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function yo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ya="[Image]";function du(e){return typeof e=="string"?[{type:"text",text:e}]:e}function pu(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Za(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function uu(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function bo(e){return{type:"text",text:e}}function gu(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function fu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function mu(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 hu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Kh=["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"],Vn=[...hu,...Kh];function Gh(e){return hu.includes(e)||e.startsWith("image/")}function ei(e){return Gh(e.type)}async function yu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ei(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function bu(e,t=Vn,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 Jh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function vu(e,t){let n=Jh(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"}Ql();var xu=16e3,Xh=24e3,Qh=4096,Yh=1380533830;function Zh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Yh?new Uint8Array(e,44):new Uint8Array(e)}function ey(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Ms=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(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:xu,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:xu});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Lr(Xh);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),i.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${ey(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let b=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}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,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Qh,1,1);this.processor=a,a.onaudioprocess=i=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Zh(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Xo=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<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}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 vo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ms(e.runtype);case"browser":if(!Xo.isSupported())throw new Error("Browser speech recognition not supported");return new Xo(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 ti(e){if(e?.type==="custom"&&e.custom)return vo({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return vo({type:"runtype",runtype:e.runtype});if(Xo.isSupported())return vo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function ks(e){try{return ti(e),!0}catch{return!1}}function Pr(e){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 n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var xo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Pr(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Qo=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!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){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Yl(e){if(!e)return"";let t=ty(e);return Cu(t!==null?t:e)}function ty(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 o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Cu(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,`
15
15
  `),t=t.replace(/\n{2,}/g,`
16
- `),t.trim()}var Cu=null;var Xl=()=>Cu?Cu():Promise.resolve().then(()=>(xu(),vu));var ey=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function ty(e,t){return ey.some(n=>e[n]!==t[n])}function Ql(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 o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
16
+ `),t.trim()}var Eu=null;var Zl=()=>Eu?Eu():Promise.resolve().then(()=>(Tu(),Su));var ay=["apiUrl","clientToken","flowId","agentId","target","targetProviders","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 ec(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 o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
17
17
 
18
- _Details: ${n.message}_`:o}var Ms=e=>({isError:!0,content:[{type:"text",text:e}]}),Su=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Tu=e=>po(e)||e===Sn,Pr=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.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=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 Xo(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(po(n.name)||n.name===Sn&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.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:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Go(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])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(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Xl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Es(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=xo.isSupported()?new xo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return Xl().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:p})=>{let d=new i({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&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){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=vo(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,i)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=p.id}if(i){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:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=p.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),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(){return this.clientSession??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(!ty(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new Go(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,g={id:a??(n==="user"?Mr():n==="assistant"?yo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:b,rawContent:g}=o,C={id:p??(r==="user"?Mr():r==="assistant"?yo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...b!==void 0&&{voiceProcessing:b},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
18
+ _Details: ${n.message}_`:o}var Ls=e=>({isError:!0,content:[{type:"text",text:e}]}),Lu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Pu=e=>po(e)||e===An,Rr=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.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=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 Qo(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(po(n.name)||n.name===An&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.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:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Jo(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])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(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Zl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return ks(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=xo.isSupported()?new xo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return Zl().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:p})=>{let d=new i({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&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){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=vo(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,i)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=p.id}if(i){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:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=p.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),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(){return this.clientSession??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 o=this.client.getSSEEventCallback();this.config=n,this.client=new Jo(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,g={id:a??(n==="user"?kr():n==="assistant"?yo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:b,rawContent:g}=o,C={id:p??(r==="user"?kr():r==="assistant"?yo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...b!==void 0&&{voiceProcessing:b},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
19
19
 
20
20
  `),a=[s,n].filter(Boolean).join(`
21
21
 
22
- `),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(i){let d=[];s&&d.push(bo(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(bo(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Mr(),s=yo();this.activeAssistantMessageId=null;let a=n?.contentParts&&Ka(n.contentParts)?Va:"",i={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(i),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??i;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let b=Ql(c,this.config.errorMessage);if(b){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=yo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=Ql(r,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),i={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let b=await c.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{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(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(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 c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let b=typeof u[0]?.question=="string"?u[0].question:"";b&&(a={[b]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,b])=>`${u}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,b)=>{let g=typeof u?.question=="string"?u.question:"";if(!g)return;let y=c[g],C=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";this.appendMessage({id:`ask-user-q-${i}-${b}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.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:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Sn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.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,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let b=this.markWebMcpToolRunning(p),g=p.agentMetadata?.webMcpToolCallId??d;if(d===Sn)return{dedupeKey:u,resumeKey:g,output:jl(),toolMessage:p,startedAt:b,completedAt:Date.now()};let y=new AbortController;this.webMcpResolveControllers.add(y),r.push(y);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,y.signal),k;if(!C)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await C}catch(P){let W=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));return W||this.callbacks.onError?.(P instanceof Error?P:new Error(String(P))),this.markWebMcpToolComplete(p,Ms(W?"Aborted by cancel()":Su(P)),b),this.webMcpInflightKeys.delete(u),null}return y.signal.aborted?(this.markWebMcpToolComplete(p,Ms("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:g,output:k,toolMessage:p,startedAt:b,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let p={};for(let c of i)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Sn?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of i)this.markWebMcpToolComplete(c.toolMessage,Ms("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let y=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(y)||this.webMcpResolvedKeys.has(y))return;this.webMcpInflightKeys.add(y);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(y)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(y)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===Sn,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),b="execute",g=a;try{let y;if(d?y=jl():u?y=await u:y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),p.aborted){this.markWebMcpToolComplete(t,Ms("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,y,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,y,a,g,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(y){let C=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,Ms(C||p.aborted?"Aborted by cancel()":Su(y)),a),C||this.callbacks.onError?.(y instanceof Error?y:new Error(String(y)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.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(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),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){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Vo(this.config.features?.artifacts,t.artifactType),r=Ra(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){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:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Au(),wu)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Ql(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=yo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}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?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=Jl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Lr(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Jl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"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),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let i=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(i&&Tu(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),b=this.webMcpResolvedKeys.has(c),g=r.toolCall?.name,y=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&g!==void 0&&Tu(g)&&r.toolCall?.status==="complete";(u||b||y)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.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,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var T=require("lucide"),ny={activity:T.Activity,"arrow-down":T.ArrowDown,"arrow-up":T.ArrowUp,"arrow-up-right":T.ArrowUpRight,bot:T.Bot,"chevron-down":T.ChevronDown,"chevron-up":T.ChevronUp,"chevron-right":T.ChevronRight,"chevron-left":T.ChevronLeft,check:T.Check,clipboard:T.Clipboard,"clipboard-copy":T.ClipboardCopy,"code-xml":T.CodeXml,copy:T.Copy,file:T.File,"file-code":T.FileCode,"file-spreadsheet":T.FileSpreadsheet,"file-text":T.FileText,"image-plus":T.ImagePlus,loader:T.Loader,"loader-circle":T.LoaderCircle,mic:T.Mic,paperclip:T.Paperclip,"refresh-cw":T.RefreshCw,search:T.Search,send:T.Send,"shield-alert":T.ShieldAlert,"shield-check":T.ShieldCheck,"shield-x":T.ShieldX,square:T.Square,"thumbs-down":T.ThumbsDown,"thumbs-up":T.ThumbsUp,upload:T.Upload,"volume-2":T.Volume2,x:T.X,user:T.User,mail:T.Mail,phone:T.Phone,calendar:T.Calendar,clock:T.Clock,building:T.Building,"map-pin":T.MapPin,lock:T.Lock,key:T.Key,"credit-card":T.CreditCard,"at-sign":T.AtSign,hash:T.Hash,globe:T.Globe,link:T.Link,"circle-check":T.CircleCheck,"circle-x":T.CircleX,"triangle-alert":T.TriangleAlert,info:T.Info,ban:T.Ban,shield:T.Shield,"arrow-left":T.ArrowLeft,"arrow-right":T.ArrowRight,"external-link":T.ExternalLink,ellipsis:T.Ellipsis,"ellipsis-vertical":T.EllipsisVertical,menu:T.Menu,house:T.House,plus:T.Plus,minus:T.Minus,pencil:T.Pencil,trash:T.Trash,"trash-2":T.Trash2,save:T.Save,download:T.Download,share:T.Share,funnel:T.Funnel,settings:T.Settings,"rotate-cw":T.RotateCw,maximize:T.Maximize,minimize:T.Minimize,"shopping-cart":T.ShoppingCart,"shopping-bag":T.ShoppingBag,package:T.Package,truck:T.Truck,tag:T.Tag,gift:T.Gift,receipt:T.Receipt,wallet:T.Wallet,store:T.Store,"dollar-sign":T.DollarSign,percent:T.Percent,play:T.Play,pause:T.Pause,"volume-x":T.VolumeX,camera:T.Camera,image:T.Image,film:T.Film,headphones:T.Headphones,"message-circle":T.MessageCircle,"message-square":T.MessageSquare,bell:T.Bell,heart:T.Heart,star:T.Star,eye:T.Eye,"eye-off":T.EyeOff,bookmark:T.Bookmark,"calendar-days":T.CalendarDays,history:T.History,timer:T.Timer,folder:T.Folder,"folder-open":T.FolderOpen,files:T.Files,sparkles:T.Sparkles,zap:T.Zap,sun:T.Sun,moon:T.Moon,flag:T.Flag,monitor:T.Monitor,smartphone:T.Smartphone},ne=(e,t=24,n="currentColor",o=2)=>{let r=ny[e];return r?oy(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function oy(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),r.appendChild(p)}),r}var Ya={allowedTypes:Vn,maxFileSize:10*1024*1024,maxFiles:4};function ry(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function sy(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 Qo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ya.allowedTypes,maxFileSize:t.maxFileSize??Ya.maxFileSize,maxFiles:t.maxFiles??Ya.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:Ya.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){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=gu(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await uu(n),s=Ga(n)?URL.createObjectURL(n):null,a={id:ry(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ga(t.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=m("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",o.appendChild(a)}else{let a=m("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=sy(t.file.type),p=ne(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=fu(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=m("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ne("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Eu=/\s/;function ay(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
23
- `:o===""||Eu.test(o)}function iy(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let a=e[s];if(a===n)return ay(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
24
- `||a==="\uFFFC"||!r&&Eu.test(a))return null;s--}return null}function Mu(e,t,n){for(let o of n){let r=iy(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function ku(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Lu(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var Ht={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,Za=zt+1;var ly=8,cy=8,Yl=10,Zl=new WeakMap,Pu=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,dy=e=>{let t=e.getRootNode?.();return Pu(t)?t:e.ownerDocument.body},ec=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Nt(e){Zl.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=ly,viewportPadding:a=cy}=e,i=()=>t.ownerDocument,p=()=>i().defaultView??window,d=null,c=null,u=null,b=!1,g=!1,y=!1,C=()=>(typeof o=="function"?o():o).trim(),k=()=>{u?.(),u=null,d?.remove(),d=null,c=null},P=()=>{if(!d)return;let Y=i(),D=p(),N=t.getBoundingClientRect(),le=d.getBoundingClientRect(),he=Y.documentElement.clientWidth||D.innerWidth,Ae=Y.documentElement.clientHeight||D.innerHeight,Me=he-a-le.width,ae=N.left+N.width/2-le.width/2,me=ec(ae,a,Me),Z=N.top-a,de=Ae-a-N.bottom,ee=le.height+s,ve=Z>=ee||Z>=de?"top":"bottom",ye=ve==="top"?N.top-s-le.height:N.bottom+s,pe=Ae-a-le.height,ke=ec(ye,a,pe),Ne=N.left+N.width/2,$e=Math.max(Yl,le.width-Yl),Be=ec(Ne-me,Yl,$e);d.dataset.placement=ve,d.style.left=`${me}px`,d.style.top=`${ke}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Be}px`)},W=()=>{if(y||!r||d||!t.isConnected)return;let Y=C(),D=dy(t);if(!Y||!D)return;let N=i(),le=p();d=N.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Za),c=N.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=Y,d.appendChild(c);let he=N.createElement("span");he.className="persona-control-tooltip__arrow",d.appendChild(he),D.appendChild(d),P(),d.dataset.state="open";let Ae=()=>{if(!t.isConnected){k();return}c&&(c.textContent=C()),P()};le.addEventListener("scroll",Ae,!0),le.addEventListener("resize",Ae);let Me=t.getRootNode(),ae=Pu(Me)?Me:N.documentElement,me=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||k()});me?.observe(ae,{childList:!0,subtree:!0}),u=()=>{le.removeEventListener("scroll",Ae,!0),le.removeEventListener("resize",Ae),me?.disconnect()}},S=()=>{b||g?W():k()},I=()=>{let Y=p();(!Y.matchMedia||!Y.matchMedia("(hover: none)").matches)&&(b=!0,S())},j=()=>{b=!1,S()},q=()=>{g=!0,S()},w=()=>{g=!1,S()},z=Y=>{Y.key==="Escape"&&(b=!1,g=!1,k())};n.addEventListener("mouseenter",I),n.addEventListener("mouseleave",j),t.addEventListener("focus",q),t.addEventListener("blur",w),t.addEventListener("keydown",z);let V={get isOpen(){return d!==null},show:W,hide:k,reposition:P,destroy:()=>{y||(y=!0,k(),n.removeEventListener("mouseenter",I),n.removeEventListener("mouseleave",j),t.removeEventListener("focus",q),t.removeEventListener("blur",w),t.removeEventListener("keydown",z),Zl.delete(t))}};return Zl.set(t,V),V}function Ru(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",i=t.buttonTooltipText??"Add context",p=m("div","persona-send-button-wrapper"),d=_e("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":i,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ne(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Nt({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??i}),{button:d,wrapper:p}}var{setLoader:rw,load:py}=vr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var tc=py;var{setLoader:iw,load:uy}=vr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var Iu=uy;function ks(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=_e("span",{className:jn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ne(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=m("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(_e("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Wu(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Lu(t).filter(S=>S.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(S=>S.sources.some(I=>typeof I.matchCommand=="function")),r=S=>o.some(I=>I.trigger?I.position==="line-start"?S.split(`
22
+ `),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(i){let d=[];s&&d.push(bo(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(bo(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=kr(),s=yo();this.activeAssistantMessageId=null;let a=n?.contentParts&&Za(n.contentParts)?Ya:"",i={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(i),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??i;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let b=ec(c,this.config.errorMessage);if(b){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=yo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=ec(r,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),i={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let b=await c.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{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(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(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 c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let b=typeof u[0]?.question=="string"?u[0].question:"";b&&(a={[b]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,b])=>`${u}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,b)=>{let g=typeof u?.question=="string"?u.question:"";if(!g)return;let y=c[g],C=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";this.appendMessage({id:`ask-user-q-${i}-${b}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.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:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==An?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.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,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let b=this.markWebMcpToolRunning(p),g=p.agentMetadata?.webMcpToolCallId??d;if(d===An)return{dedupeKey:u,resumeKey:g,output:ql(),toolMessage:p,startedAt:b,completedAt:Date.now()};let y=new AbortController;this.webMcpResolveControllers.add(y),r.push(y);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,y.signal),k;if(!C)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await C}catch(P){let W=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));return W||this.callbacks.onError?.(P instanceof Error?P:new Error(String(P))),this.markWebMcpToolComplete(p,Ls(W?"Aborted by cancel()":Lu(P)),b),this.webMcpInflightKeys.delete(u),null}return y.signal.aborted?(this.markWebMcpToolComplete(p,Ls("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:g,output:k,toolMessage:p,startedAt:b,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let p={};for(let c of i)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===An?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of i)this.markWebMcpToolComplete(c.toolMessage,Ls("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let y=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(y)||this.webMcpResolvedKeys.has(y))return;this.webMcpInflightKeys.add(y);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(y)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(y)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===An,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),b="execute",g=a;try{let y;if(d?y=ql():u?y=await u:y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),p.aborted){this.markWebMcpToolComplete(t,Ls("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,y,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,y,a,g,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(y){let C=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,Ls(C||p.aborted?"Aborted by cancel()":Lu(y)),a),C||this.callbacks.onError?.(y instanceof Error?y:new Error(String(y)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.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(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),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){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Ko(this.config.features?.artifacts,t.artifactType),r=Da(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){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:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(ku(),Mu)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>ec(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=yo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}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?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=Yl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Pr(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Yl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"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),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let i=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(i&&Pu(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),b=this.webMcpResolvedKeys.has(c),g=r.toolCall?.name,y=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&g!==void 0&&Pu(g)&&r.toolCall?.status==="complete";(u||b||y)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.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,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var T=require("lucide"),ly={activity:T.Activity,"arrow-down":T.ArrowDown,"arrow-up":T.ArrowUp,"arrow-up-right":T.ArrowUpRight,bot:T.Bot,"chevron-down":T.ChevronDown,"chevron-up":T.ChevronUp,"chevron-right":T.ChevronRight,"chevron-left":T.ChevronLeft,check:T.Check,clipboard:T.Clipboard,"clipboard-copy":T.ClipboardCopy,"code-xml":T.CodeXml,copy:T.Copy,file:T.File,"file-code":T.FileCode,"file-spreadsheet":T.FileSpreadsheet,"file-text":T.FileText,"image-plus":T.ImagePlus,loader:T.Loader,"loader-circle":T.LoaderCircle,mic:T.Mic,paperclip:T.Paperclip,"refresh-cw":T.RefreshCw,search:T.Search,send:T.Send,"shield-alert":T.ShieldAlert,"shield-check":T.ShieldCheck,"shield-x":T.ShieldX,square:T.Square,"thumbs-down":T.ThumbsDown,"thumbs-up":T.ThumbsUp,upload:T.Upload,"volume-2":T.Volume2,x:T.X,user:T.User,mail:T.Mail,phone:T.Phone,calendar:T.Calendar,clock:T.Clock,building:T.Building,"map-pin":T.MapPin,lock:T.Lock,key:T.Key,"credit-card":T.CreditCard,"at-sign":T.AtSign,hash:T.Hash,globe:T.Globe,link:T.Link,"circle-check":T.CircleCheck,"circle-x":T.CircleX,"triangle-alert":T.TriangleAlert,info:T.Info,ban:T.Ban,shield:T.Shield,"arrow-left":T.ArrowLeft,"arrow-right":T.ArrowRight,"external-link":T.ExternalLink,ellipsis:T.Ellipsis,"ellipsis-vertical":T.EllipsisVertical,menu:T.Menu,house:T.House,plus:T.Plus,minus:T.Minus,pencil:T.Pencil,trash:T.Trash,"trash-2":T.Trash2,save:T.Save,download:T.Download,share:T.Share,funnel:T.Funnel,settings:T.Settings,"rotate-cw":T.RotateCw,maximize:T.Maximize,minimize:T.Minimize,"shopping-cart":T.ShoppingCart,"shopping-bag":T.ShoppingBag,package:T.Package,truck:T.Truck,tag:T.Tag,gift:T.Gift,receipt:T.Receipt,wallet:T.Wallet,store:T.Store,"dollar-sign":T.DollarSign,percent:T.Percent,play:T.Play,pause:T.Pause,"volume-x":T.VolumeX,camera:T.Camera,image:T.Image,film:T.Film,headphones:T.Headphones,"message-circle":T.MessageCircle,"message-square":T.MessageSquare,bell:T.Bell,heart:T.Heart,star:T.Star,eye:T.Eye,"eye-off":T.EyeOff,bookmark:T.Bookmark,"calendar-days":T.CalendarDays,history:T.History,timer:T.Timer,folder:T.Folder,"folder-open":T.FolderOpen,files:T.Files,sparkles:T.Sparkles,zap:T.Zap,sun:T.Sun,moon:T.Moon,flag:T.Flag,monitor:T.Monitor,smartphone:T.Smartphone},ne=(e,t=24,n="currentColor",o=2)=>{let r=ly[e];return r?cy(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function cy(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),r.appendChild(p)}),r}var ri={allowedTypes:Vn,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 Yo=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??ri.allowedTypes,maxFileSize:t.maxFileSize??ri.maxFileSize,maxFiles:t.maxFiles??ri.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:ri.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){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=bu(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await yu(n),s=ei(n)?URL.createObjectURL(n):null,a={id:dy(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=ei(t.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=m("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",o.appendChild(a)}else{let a=m("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),p=ne(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=vu(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=m("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ne("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Ru=/\s/;function uy(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
23
+ `:o===""||Ru.test(o)}function gy(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let a=e[s];if(a===n)return uy(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
24
+ `||a==="\uFFFC"||!r&&Ru.test(a))return null;s--}return null}function Iu(e,t,n){for(let o of n){let r=gy(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Wu(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Hu(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var Ht={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,si=zt+1;var fy=8,my=8,tc=10,nc=new WeakMap,Bu=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,hy=e=>{let t=e.getRootNode?.();return Bu(t)?t:e.ownerDocument.body},oc=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Nt(e){nc.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=fy,viewportPadding:a=my}=e,i=()=>t.ownerDocument,p=()=>i().defaultView??window,d=null,c=null,u=null,b=!1,g=!1,y=!1,C=()=>(typeof o=="function"?o():o).trim(),k=()=>{u?.(),u=null,d?.remove(),d=null,c=null},P=()=>{if(!d)return;let Y=i(),D=p(),N=t.getBoundingClientRect(),ce=d.getBoundingClientRect(),he=Y.documentElement.clientWidth||D.innerWidth,Ae=Y.documentElement.clientHeight||D.innerHeight,Me=he-a-ce.width,ae=N.left+N.width/2-ce.width/2,me=oc(ae,a,Me),Z=N.top-a,de=Ae-a-N.bottom,ee=ce.height+s,ve=Z>=ee||Z>=de?"top":"bottom",ye=ve==="top"?N.top-s-ce.height:N.bottom+s,pe=Ae-a-ce.height,ke=oc(ye,a,pe),Ne=N.left+N.width/2,$e=Math.max(tc,ce.width-tc),Be=oc(Ne-me,tc,$e);d.dataset.placement=ve,d.style.left=`${me}px`,d.style.top=`${ke}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Be}px`)},W=()=>{if(y||!r||d||!t.isConnected)return;let Y=C(),D=hy(t);if(!Y||!D)return;let N=i(),ce=p();d=N.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(si),c=N.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=Y,d.appendChild(c);let he=N.createElement("span");he.className="persona-control-tooltip__arrow",d.appendChild(he),D.appendChild(d),P(),d.dataset.state="open";let Ae=()=>{if(!t.isConnected){k();return}c&&(c.textContent=C()),P()};ce.addEventListener("scroll",Ae,!0),ce.addEventListener("resize",Ae);let Me=t.getRootNode(),ae=Bu(Me)?Me:N.documentElement,me=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||k()});me?.observe(ae,{childList:!0,subtree:!0}),u=()=>{ce.removeEventListener("scroll",Ae,!0),ce.removeEventListener("resize",Ae),me?.disconnect()}},S=()=>{b||g?W():k()},I=()=>{let Y=p();(!Y.matchMedia||!Y.matchMedia("(hover: none)").matches)&&(b=!0,S())},j=()=>{b=!1,S()},q=()=>{g=!0,S()},w=()=>{g=!1,S()},z=Y=>{Y.key==="Escape"&&(b=!1,g=!1,k())};n.addEventListener("mouseenter",I),n.addEventListener("mouseleave",j),t.addEventListener("focus",q),t.addEventListener("blur",w),t.addEventListener("keydown",z);let V={get isOpen(){return d!==null},show:W,hide:k,reposition:P,destroy:()=>{y||(y=!0,k(),n.removeEventListener("mouseenter",I),n.removeEventListener("mouseleave",j),t.removeEventListener("focus",q),t.removeEventListener("blur",w),t.removeEventListener("keydown",z),nc.delete(t))}};return nc.set(t,V),V}function Ou(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",i=t.buttonTooltipText??"Add context",p=m("div","persona-send-button-wrapper"),d=_e("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":i,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ne(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Nt({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??i}),{button:d,wrapper:p}}var{setLoader:dw,load:yy}=xr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var rc=yy;var{setLoader:gw,load:by}=xr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var Du=by;function Ps(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=_e("span",{className:$n("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ne(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=m("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(_e("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Nu(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Hu(t).filter(S=>S.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(S=>S.sources.some(I=>typeof I.matchCommand=="function")),r=S=>o.some(I=>I.trigger?I.position==="line-start"?S.split(`
25
25
  `).some(q=>q.startsWith(I.trigger)):(I.position==="anywhere"?S:S.split(`
26
- `)[0]).startsWith(I.trigger):!1),s=(S,I)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${S}`,{detail:I}))}catch{}},a=_e("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,p=null,d=e.textarea,c=null,u=null,b=null,g=null,y=()=>{if(i)return Promise.resolve(i);if(p)return p;let S=tc().then(I=>(i=I.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:W,emit:s}),i)).catch(I=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",I),p===S&&(p=null),null));return p=S,S},C=()=>{Iu().then(S=>{let I=S.mountInlineComposer({textarea:e.textarea,renderToken:q=>ks(q,{render:t.renderMentionToken}),onMentionRemoved:q=>i?.untrackMention(q)});c=I.input,u=I.destroy;let j=d;j.replaceWith(I.element),d=I.element,g={next:I.element,prev:j},b?.(I.element,j),i?i.rebindComposer(I.input):p&&p.then(q=>q?.rebindComposer(I.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};t.display==="inline"&&C();let k=[],P=new Map;for(let S of n){if(!S.showButton)continue;let I=Ru({config:{...t,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{y().then(j=>j?.openMenu(S.trigger))}});k.push(I),P.set(S.trigger,I.button)}let W=(S,I,j)=>{let q=P.get(I);q&&(q.setAttribute("aria-expanded",S?"true":"false"),S?q.setAttribute("aria-controls",j):q.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(S=>S.wrapper),contextRow:a,handleInput:S=>{if(i){i.handleInput();return}if(!ku(S))return;let I=d,j=I.selectionStart??0;Mu(I.value,j,n)&&y().then(q=>q?.handleInput())},handleKeydown:S=>{if(i?.isMenuOpen())return i.handleKeydown(S);if(S.key==="Backspace"&&i?.hasMentions()&&!g){let I=d,j=I.selectionStart===0&&I.selectionEnd===0;if((I.value.length===0||j)&&i.removeLastChip())return S.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async S=>r(S)?(i??await y())?.dispatchInlineCommand(S)??null:null,clear:()=>i?.clear(),prefetch:()=>{tc().catch(()=>{})},onComposerSwap:S=>{b=S,g&&S(g.next,g.prev)},destroy:()=>{i?.destroy(),u?.();for(let S of k)S.wrapper.remove();a.remove()}}}var Hu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ls(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Hu(s)&&Hu(r)?n[o]=Ls(s,r):n[o]=r}return n}var sn="min(440px, calc(100vw - 24px))",ei="440px",gy={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:sn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},it={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:gy,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",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 Bu(e,t){if(!(!e&&!t))return e?t?Ls(e,t):e:t}function Rr(e){return e?{...it,...e,theme:Bu(it.theme,e.theme),darkTheme:Bu(it.darkTheme,e.darkTheme),launcher:{...it.launcher,...e.launcher,dock:{...it.launcher?.dock,...e.launcher?.dock},clearChat:{...it.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...it.copy,...e.copy},sendButton:{...it.sendButton,...e.sendButton},statusIndicator:{...it.statusIndicator,...e.statusIndicator},voiceRecognition:{...it.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=it.features?.artifacts,n=e.features?.artifacts,o=it.features?.scrollToBottom,r=e.features?.scrollToBottom,s=it.features?.scrollBehavior,a=e.features?.scrollBehavior,i=it.features?.streamAnimation,p=e.features?.streamAnimation,d=it.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},g=s===void 0&&a===void 0?void 0:{...s,...a},y=i===void 0&&p===void 0?void 0:{...i,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...it.features,...e.features,...b!==void 0?{scrollToBottom:b}:{},...g!==void 0?{scrollBehavior:g}:{},...u!==void 0?{artifacts:u}:{},...y!==void 0?{streamAnimation:y}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...it.layout,...e.layout,header:{...it.layout?.header,...e.layout?.header},messages:{...it.layout?.messages,...e.layout?.messages,avatar:{...it.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...it.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...it.layout?.slots,...e.layout?.slots}},markdown:{...it.markdown,...e.markdown,options:{...it.markdown?.options,...e.markdown?.options}},messageActions:{...it.messageActions,...e.messageActions}}:it}var ti="16px",ni="transparent",nc={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},oc={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},rc={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",hoverBackground:"rgba(0, 0, 0, 0.05)"}},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:sn,maxWidth:ei,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ti,canvasBackground:ni},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:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Kt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Kt(e,o):o}function oi(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let p=Kt(e,a);p!==void 0&&(t[i]={path:i,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.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 sc(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 Ou(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Ou(s,r):n[o]=r}return n}function fy(e,t){return t?Ou(e,t):e}function Ps(e,t={}){let n={palette:nc,semantic:oc,components:rc},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:fy(n.components,e?.components)};if(t.validate!==!1){let r=sc(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function ri(e){let t=oi(e),n={};for(let[w,z]of Object.entries(t)){let V=w.replace(/\./g,"-");n[`--persona-${V}`]=z.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??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"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ti,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ni,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let i=n["--persona-components-markdown-heading-h2-fontWeight"];i&&(n["--persona-md-h2-weight"]=i);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let b=d?.toggleGroup;b&&(b.gap&&(n["--persona-toggle-group-gap"]=b.gap),b.borderRadius&&(n["--persona-toggle-group-radius"]=b.borderRadius));let g=d?.artifact;if(g?.toolbar){let w=g.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Kt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(g?.tab){let w=g.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(g?.pane){let w=g.pane;if(w.toolbarBackground){let z=Kt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=z}}if(g?.card){let w=g.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(g?.inline){let w=g.inline;w.background&&(n["--persona-artifact-inline-bg"]=Kt(e,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Kt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Kt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Kt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Kt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let y=d?.code;y&&(y.keywordColor&&(n["--persona-code-keyword-color"]=y.keywordColor),y.stringColor&&(n["--persona-code-string-color"]=y.stringColor),y.commentColor&&(n["--persona-code-comment-color"]=y.commentColor),y.numberColor&&(n["--persona-code-number-color"]=y.numberColor),y.tagColor&&(n["--persona-code-tag-color"]=y.tagColor),y.attrColor&&(n["--persona-code-attr-color"]=y.attrColor),y.propertyColor&&(n["--persona-code-property-color"]=y.propertyColor),y.lineNumberColor&&(n["--persona-code-line-number-color"]=y.lineNumberColor),y.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=y.gutterBorderColor),y.background&&(n["--persona-code-bg"]=Kt(e,y.background)??y.background));let C=n["--persona-surface"],k=n["--persona-container"],P=n["--persona-palette-colors-gray-100"]??"#f3f4f6",W=n["--persona-palette-colors-gray-200"]??"#e5e7eb",S=n["--persona-palette-colors-gray-300"]??"#d1d5db",I=!k||k===C,j=I?P:k,q=I?W:k;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??j,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??q,I&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??S),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??j,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??j,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??j,n}var Du={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","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};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"}}},Nu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Rs=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",hy=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Rs()},si=e=>hy(e),yy=e=>Ps(e),by=e=>Ps({...e,palette:{...e?.palette,colors:{...my.colors,...e?.palette?.colors}}},{validate:!1}),Co=e=>{let t=si(e),n=Nu(e?.theme),o=Nu(e?.darkTheme);return t==="dark"?by(Ls(n??{},o??{})):yy(n)},vy=e=>ri(e),Yo=(e,t)=>{let n=Co(t),o=vy(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",si(t))},Ir=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Rs())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Rs());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Rn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Fu(e){let t=Rn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function ai(e){if(typeof e!="string")return"";let t=e.indexOf(`
26
+ `)[0]).startsWith(I.trigger):!1),s=(S,I)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${S}`,{detail:I}))}catch{}},a=_e("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,p=null,d=e.textarea,c=null,u=null,b=null,g=null,y=()=>{if(i)return Promise.resolve(i);if(p)return p;let S=rc().then(I=>(i=I.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:W,emit:s}),i)).catch(I=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",I),p===S&&(p=null),null));return p=S,S},C=()=>{Du().then(S=>{let I=S.mountInlineComposer({textarea:e.textarea,renderToken:q=>Ps(q,{render:t.renderMentionToken}),onMentionRemoved:q=>i?.untrackMention(q)});c=I.input,u=I.destroy;let j=d;j.replaceWith(I.element),d=I.element,g={next:I.element,prev:j},b?.(I.element,j),i?i.rebindComposer(I.input):p&&p.then(q=>q?.rebindComposer(I.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};t.display==="inline"&&C();let k=[],P=new Map;for(let S of n){if(!S.showButton)continue;let I=Ou({config:{...t,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{y().then(j=>j?.openMenu(S.trigger))}});k.push(I),P.set(S.trigger,I.button)}let W=(S,I,j)=>{let q=P.get(I);q&&(q.setAttribute("aria-expanded",S?"true":"false"),S?q.setAttribute("aria-controls",j):q.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(S=>S.wrapper),contextRow:a,handleInput:S=>{if(i){i.handleInput();return}if(!Wu(S))return;let I=d,j=I.selectionStart??0;Iu(I.value,j,n)&&y().then(q=>q?.handleInput())},handleKeydown:S=>{if(i?.isMenuOpen())return i.handleKeydown(S);if(S.key==="Backspace"&&i?.hasMentions()&&!g){let I=d,j=I.selectionStart===0&&I.selectionEnd===0;if((I.value.length===0||j)&&i.removeLastChip())return S.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async S=>r(S)?(i??await y())?.dispatchInlineCommand(S)??null:null,clear:()=>i?.clear(),prefetch:()=>{rc().catch(()=>{})},onComposerSwap:S=>{b=S,g&&S(g.next,g.prev)},destroy:()=>{i?.destroy(),u?.();for(let S of k)S.wrapper.remove();a.remove()}}}var Fu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Rs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Fu(s)&&Fu(r)?n[o]=Rs(s,r):n[o]=r}return n}var sn="min(440px, calc(100vw - 24px))",ai="440px",vy={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:sn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},it={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:vy,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",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 _u(e,t){if(!(!e&&!t))return e?t?Rs(e,t):e:t}function Ir(e){return e?{...it,...e,theme:_u(it.theme,e.theme),darkTheme:_u(it.darkTheme,e.darkTheme),launcher:{...it.launcher,...e.launcher,dock:{...it.launcher?.dock,...e.launcher?.dock},clearChat:{...it.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...it.copy,...e.copy},sendButton:{...it.sendButton,...e.sendButton},statusIndicator:{...it.statusIndicator,...e.statusIndicator},voiceRecognition:{...it.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=it.features?.artifacts,n=e.features?.artifacts,o=it.features?.scrollToBottom,r=e.features?.scrollToBottom,s=it.features?.scrollBehavior,a=e.features?.scrollBehavior,i=it.features?.streamAnimation,p=e.features?.streamAnimation,d=it.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},g=s===void 0&&a===void 0?void 0:{...s,...a},y=i===void 0&&p===void 0?void 0:{...i,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...it.features,...e.features,...b!==void 0?{scrollToBottom:b}:{},...g!==void 0?{scrollBehavior:g}:{},...u!==void 0?{artifacts:u}:{},...y!==void 0?{streamAnimation:y}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...it.layout,...e.layout,header:{...it.layout?.header,...e.layout?.header},messages:{...it.layout?.messages,...e.layout?.messages,avatar:{...it.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...it.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...it.layout?.slots,...e.layout?.slots}},markdown:{...it.markdown,...e.markdown,options:{...it.markdown?.options,...e.markdown?.options}},messageActions:{...it.messageActions,...e.messageActions}}:it}var ii="16px",li="transparent",sc={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"}},ac={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"}},ic={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",hoverBackground:"rgba(0, 0, 0, 0.05)"}},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:sn,maxWidth:ai,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ii,canvasBackground:li},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:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Gt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Gt(e,o):o}function ci(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let p=Gt(e,a);p!==void 0&&(t[i]={path:i,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.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 lc(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 $u(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=$u(s,r):n[o]=r}return n}function xy(e,t){return t?$u(e,t):e}function Is(e,t={}){let n={palette:sc,semantic:ac,components:ic},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:xy(n.components,e?.components)};if(t.validate!==!1){let r=lc(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function di(e){let t=ci(e),n={};for(let[w,z]of Object.entries(t)){let V=w.replace(/\./g,"-");n[`--persona-${V}`]=z.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??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"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ii,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??li,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let i=n["--persona-components-markdown-heading-h2-fontWeight"];i&&(n["--persona-md-h2-weight"]=i);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let b=d?.toggleGroup;b&&(b.gap&&(n["--persona-toggle-group-gap"]=b.gap),b.borderRadius&&(n["--persona-toggle-group-radius"]=b.borderRadius));let g=d?.artifact;if(g?.toolbar){let w=g.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Gt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(g?.tab){let w=g.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(g?.pane){let w=g.pane;if(w.toolbarBackground){let z=Gt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=z}}if(g?.card){let w=g.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(g?.inline){let w=g.inline;w.background&&(n["--persona-artifact-inline-bg"]=Gt(e,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Gt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Gt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Gt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Gt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let y=d?.code;y&&(y.keywordColor&&(n["--persona-code-keyword-color"]=y.keywordColor),y.stringColor&&(n["--persona-code-string-color"]=y.stringColor),y.commentColor&&(n["--persona-code-comment-color"]=y.commentColor),y.numberColor&&(n["--persona-code-number-color"]=y.numberColor),y.tagColor&&(n["--persona-code-tag-color"]=y.tagColor),y.attrColor&&(n["--persona-code-attr-color"]=y.attrColor),y.propertyColor&&(n["--persona-code-property-color"]=y.propertyColor),y.lineNumberColor&&(n["--persona-code-line-number-color"]=y.lineNumberColor),y.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=y.gutterBorderColor),y.background&&(n["--persona-code-bg"]=Gt(e,y.background)??y.background));let C=n["--persona-surface"],k=n["--persona-container"],P=n["--persona-palette-colors-gray-100"]??"#f3f4f6",W=n["--persona-palette-colors-gray-200"]??"#e5e7eb",S=n["--persona-palette-colors-gray-300"]??"#d1d5db",I=!k||k===C,j=I?P:k,q=I?W:k;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??j,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??q,I&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??S),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??j,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??j,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??j,n}var ju={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","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var Cy={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"}}},Uu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ws=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",wy=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ws()},pi=e=>wy(e),Ay=e=>Is(e),Sy=e=>Is({...e,palette:{...e?.palette,colors:{...Cy.colors,...e?.palette?.colors}}},{validate:!1}),Co=e=>{let t=pi(e),n=Uu(e?.theme),o=Uu(e?.darkTheme);return t==="dark"?Sy(Rs(n??{},o??{})):Ay(n)},Ty=e=>di(e),Zo=(e,t)=>{let n=Co(t),o=Ty(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",pi(t))},Wr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ws())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ws());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Pn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function zu(e){let t=Pn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function ui(e){if(typeof e!="string")return"";let t=e.indexOf(`
27
27
  `);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
28
- `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Is(e){let t=Fu(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function wo(e){switch(Is(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Fu(e.path);return t?t.toUpperCase():"File"}}}function _u(e){let t=e.markdown??"";return e.file?{filename:Rn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:ai(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var ac="http://www.w3.org/2000/svg";function $u(e){let t=document.createElementNS(ac,"svg");t.setAttribute("class",jn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(ac,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(ac,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var Ao=(e,t,n)=>{let o=n;for(let r of t){let s=m("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function ju(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Ao(e,t,0)}var ic="persona-artifact-status-label",Uu="persona-artifact-status-detail",zu="data-artifact-status-label",lc=new Map,qu=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Wr(e){e&&lc.delete(e)}function xy(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?wo(t):e.artifactType==="component"?"Component":"Document"}function Hr(e,t,n){let o=xy(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=e.id,i=lc.get(a);e.status!=="complete"&&i===void 0&&(i=qu(),lc.set(a,i));let p=i===void 0?0:Math.max(0,qu()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,b=d||c===""?0:c.split(`
29
- `).length,g=e.artifactType==="markdown"?e.file:void 0,y={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:u,lines:b,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=s(y);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function Cy(e){e.className=ic,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function Zo(e,t,n){let o=e.querySelector(`:scope > .${ic}`);o||(o=m("span",ic),e.appendChild(o)),o.getAttribute(zu)!==t.label&&(Cy(o),ju(o,t.label,n),o.setAttribute(zu,t.label));let r=e.querySelector(`:scope > .${Uu}`),s=t.detail;s?(r||(r=m("span",Uu),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var wy={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},Ay=15e4,ii={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function Sy(e,t){let n=(e||"").trim().toLowerCase();if(n&&ii[n])return ii[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(ii[r])return ii[r]}}return null}function li(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,a)})};for(;o<e.length;){let a=!1;for(let i of t){i.re.lastIndex=o;let p=i.re.exec(e);if(p&&p.index===o&&p[0].length>0){s(o);let d=i.map?i.map(p[0]):i.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(e.length),n}var Ty=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),Ey=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>Ty.has(e)?"keyword":"plain"}];function Vu(e){return li(e,Ey)}var My=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function ky(e){let t=li(e,My);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var Ly=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function Ku(e){let t=li(e,Ly),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let i=t[a];i&&i.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}var Py=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function Ry(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),i=a===-1?o:a+3;n("comment",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),i=a===-1?o:a+1;n("tag",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),i=a===-1?o:a+1,p=e.slice(r,i);for(let c of li(p,Py))t.push(c);r=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),b=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),g=b?r+b.index:o,y=e.slice(r,g),C=c==="script"?Vu(y):Ku(y);for(let k of C)t.push(k);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let a=s===-1?o:s;n("plain",e.slice(r,a)),r=a}}return t}function Iy(e,t){switch(t){case"html":return Ry(e);case"css":return Ku(e);case"js":return Vu(e);case"json":return ky(e)}}function Wy(e){let t=Np(),n=m("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=wy[r];if(a){let i=m("span",a);i.textContent=s,n.appendChild(i)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
28
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Hs(e){let t=zu(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function wo(e){switch(Hs(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=zu(e.path);return t?t.toUpperCase():"File"}}}function qu(e){let t=e.markdown??"";return e.file?{filename:Pn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:ui(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var cc="http://www.w3.org/2000/svg";function Vu(e){let t=document.createElementNS(cc,"svg");t.setAttribute("class",$n("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(cc,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(cc,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var Ao=(e,t,n)=>{let o=n;for(let r of t){let s=m("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function Ku(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Ao(e,t,0)}var dc="persona-artifact-status-label",Gu="persona-artifact-status-detail",Ju="data-artifact-status-label",pc=new Map,Xu=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Hr(e){e&&pc.delete(e)}function Ey(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?wo(t):e.artifactType==="component"?"Component":"Document"}function Br(e,t,n){let o=Ey(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=e.id,i=pc.get(a);e.status!=="complete"&&i===void 0&&(i=Xu(),pc.set(a,i));let p=i===void 0?0:Math.max(0,Xu()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,b=d||c===""?0:c.split(`
29
+ `).length,g=e.artifactType==="markdown"?e.file:void 0,y={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:u,lines:b,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=s(y);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function My(e){e.className=dc,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function er(e,t,n){let o=e.querySelector(`:scope > .${dc}`);o||(o=m("span",dc),e.appendChild(o)),o.getAttribute(Ju)!==t.label&&(My(o),Ku(o,t.label,n),o.setAttribute(Ju,t.label));let r=e.querySelector(`:scope > .${Gu}`),s=t.detail;s?(r||(r=m("span",Gu),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var ky={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},Ly=15e4,gi={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function Py(e,t){let n=(e||"").trim().toLowerCase();if(n&&gi[n])return gi[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(gi[r])return gi[r]}}return null}function fi(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,a)})};for(;o<e.length;){let a=!1;for(let i of t){i.re.lastIndex=o;let p=i.re.exec(e);if(p&&p.index===o&&p[0].length>0){s(o);let d=i.map?i.map(p[0]):i.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(e.length),n}var Ry=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),Iy=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>Ry.has(e)?"keyword":"plain"}];function Qu(e){return fi(e,Iy)}var Wy=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function Hy(e){let t=fi(e,Wy);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var By=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function Yu(e){let t=fi(e,By),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let i=t[a];i&&i.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}var Oy=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function Dy(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),i=a===-1?o:a+3;n("comment",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),i=a===-1?o:a+1;n("tag",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),i=a===-1?o:a+1,p=e.slice(r,i);for(let c of fi(p,Oy))t.push(c);r=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),b=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),g=b?r+b.index:o,y=e.slice(r,g),C=c==="script"?Qu(y):Yu(y);for(let k of C)t.push(k);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let a=s===-1?o:s;n("plain",e.slice(r,a)),r=a}}return t}function Ny(e,t){switch(t){case"html":return Dy(e);case"css":return Yu(e);case"js":return Qu(e);case"json":return Hy(e)}}function Fy(e){let t=Up(),n=m("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=ky[r];if(a){let i=m("span",a);i.textContent=s,n.appendChild(i)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
30
30
  `);for(let a=0;a<s.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
31
- `)),n=m("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Gu(e,t,n){let o=e.length<=Ay?Sy(t,n):null,r=o?Iy(e,o):[{type:"plain",value:e}];return Wy(r)}function So(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Za)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let k=document.createElement("hr");a.appendChild(k)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",g.id),g.destructive&&y.setAttribute("data-destructive",""),g.icon){let k=ne(g.icon,16,"currentColor",1.5);k&&y.appendChild(k)}let C=document.createElement("span");C.textContent=g.label,y.appendChild(C),y.addEventListener("click",k=>{k.stopPropagation(),c(),n(g.id)}),a.appendChild(y)}let i=null;function p(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=y=>{!a.contains(y.target)&&!o.contains(y.target)&&c()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?d():c()}function b(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:b}}function ct(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,p=m("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ne(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),i)for(let[c,u]of Object.entries(i))p.setAttribute(c,u);return p}function Kn(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let b=ne(t,s??14,"currentColor",2);b&&c.appendChild(b)}let u=m("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),p)for(let[b,g]of Object.entries(p))c.setAttribute(b,g);return c}function Gn(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=m("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,i=[];function p(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=ct({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=m("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),i.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function ci(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:p}=e,d=m("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=m("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=ne(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let b=So({items:o,onSelect:g=>{d.setAttribute("aria-expanded","false"),r(g)},anchor:d,position:s,portal:a});return a||d.appendChild(b.element),d.addEventListener("click",g=>{g.stopPropagation();let y=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",y?"false":"true"),b.toggle()}),d.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),d.click())}),{element:d,setLabel:g=>{c.textContent=g,d.setAttribute("aria-label",g)},open:()=>{d.setAttribute("aria-expanded","true"),b.show()},close:()=>{d.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let g=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",g?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),d.remove()}}}var di="persona-artifact-custom-action-btn";function Br(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+di+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+di+(n?" persona-artifact-doc-icon-btn":"");o=m("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=m("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Kn({icon:e.icon,label:e.label,className:di+(n?" persona-artifact-doc-copy-btn":"")}):o=ct({icon:e.icon,label:e.label,className:di+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ws(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Ju(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Rn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n?wo(n):i==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let b=document.createElement("div");b.className="persona-truncate persona-text-sm persona-font-medium",b.style.color="var(--persona-text, #1f2937)",b.textContent=r;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let y=t?.config?.features?.artifacts,C={id:s,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},k=Hr(C,y,"card");Zo(g,k,y)}else s&&Wr(s),g.textContent=p;if(u.append(b,g),d.append(c,u),a==="complete"){let y=t?.config?.features?.artifacts?.cardActions;if(y&&y.length>0){let k={artifactId:s||null,title:r,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let P of y)try{if(P.visible===void 0||P.visible(k)){let W=Br(P);W.setAttribute("data-artifact-custom-action",P.id),W.className=`${W.className} persona-flex-shrink-0`,d.append(W)}}catch{}}let C=Kn({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),d.append(C)}return d}var pi=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=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",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Ju(e,t)});if(i)return i}return Ju(e,t)};var To=new WeakMap;function cc(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=To.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function eg(e){return To.has(e)}function Hy(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let s=e.componentProps,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:a}}let r=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...r?{file:r}:{}}}function Xu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Rn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?wo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function By(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var Qu=180,Oy=240,Dy=.8,Ny=300,Fy=500,_y="cubic-bezier(0.2, 0, 0, 1)",Yu=240,$y=.35;function jy(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let i of Array.from(e.children))i instanceof HTMLElement&&a.push(i.animate([{opacity:1},{opacity:0}],{duration:Qu,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let P of a)P.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){i(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(Fy,Math.max(Ny,Oy+d*Dy))),u=Math.round(c*$y),b=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=b?b.animate([{opacity:0},{opacity:1}],{duration:Yu,delay:u,easing:"ease-out",fill:"backwards"}):null,y=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:_y});e.style.height=`${p}px`;let C=!1,k=()=>{C||(C=!0,i(),r())};Promise.allSettled([y.finished,g?.finished].filter(Boolean)).then(k),window.setTimeout(k,Math.max(c,u+Yu)+120)},Qu)}function Uy(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Hs="--persona-artifact-inline-body-height";function zy(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",p=i==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):i==="clip"?(d=!1,c=!0):(d=!0,c=!0);let b=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:i,fadeTop:d,fadeBottom:c,transition:b,completeDisplay:g}}function Zu(e,t){let n=Hy(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:i}=Uy(o),p=o?.inlineActions??[],d=zy(o),c=d.completeDisplay==="card",u=null,b=n,g=m("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let y=Z=>pi(By(Z),t),C=Z=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Hs),g.replaceChildren(y(Z)),To.set(g,de=>{g.replaceChildren(y(de))})};if(c&&n.status==="complete")return C(n),g;let k=ui(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),P=m("div","persona-artifact-inline-body");P.appendChild(k.el);let W=Z=>{let de=Z.status!=="complete",ee=de?d.streamingHeight:d.completeHeight,ve=typeof ee=="number";ve?g.style.setProperty(Hs,`${ee}px`):g.style.removeProperty(Hs);let ye=!!k.el.querySelector(".persona-code-pre"),pe=!!k.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");P.classList.toggle("persona-artifact-content-flush",ye),P.classList.toggle("persona-artifact-inline-body--sized",ve&&pe),P.classList.toggle("persona-artifact-inline-body--cap",!de&&!pe&&typeof d.completeHeight=="number")},S=n.status,I=(Z,de)=>{S!=="complete"&&Z.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(Hs,`${d.completeHeight}px`):g.style.removeProperty(Hs),ng(P,de?.suppressTransition?"none":d.transition,Z.id,()=>{k.update(Z),W(Z)})):k.update(Z),W(Z),S=Z.status};W(n);let j=d.overflow==="clip"&&a&&!!n.id;if(j&&(P.setAttribute("data-expand-artifact-inline",n.id),P.setAttribute("role","button"),P.setAttribute("tabindex","0"),P.classList.add("persona-cursor-pointer"),P.setAttribute("aria-label",`Open ${Xu(n).title} in panel`)),!r)return g.appendChild(P),To.set(g,I),g;let q=m("div","persona-artifact-inline-chrome");q.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=m("div","persona-artifact-inline-chrome-lead"),z=m("span","persona-flex persona-items-center persona-flex-shrink-0"),V=ne("file-text",16,"currentColor",2);V&&z.appendChild(V);let Y=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=m("span","persona-artifact-inline-type");w.append(z,Y,D);let N=m("div","persona-artifact-inline-chrome-actions"),le=m("span","persona-flex persona-items-center persona-gap-1"),he=()=>u??d.viewMode,Ae=i?Gn({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:he(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let de=Z==="source"?"source":"rendered";de!==he()&&(u=de,k.update(b),W(b))}}):null,Me=s?ct({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Me&&n.id&&Me.setAttribute("data-copy-artifact",n.id);let ae=a?ct({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ae&&n.id&&ae.setAttribute("data-expand-artifact-inline",n.id),N.appendChild(le),Ae&&N.appendChild(Ae.element),Me&&N.appendChild(Me),ae&&N.appendChild(ae),q.append(w,N),g.append(q,P);let me=Z=>{let{title:de,typeLabel:ee}=Xu(Z);Y.textContent=de,Y.title=de,j&&P.setAttribute("aria-label",`Open ${de} in panel`);let ve=Z.status!=="complete";if(ve){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let ye=Hr(Z,o,"inline-chrome");Zo(D,ye,o)}else Wr(Z.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=ee;if(Me&&Me.classList.toggle("persona-hidden",ve),Ae){let ye=Z.artifactType==="markdown"?Z.file:void 0,pe=!1;if(!ve&&ye&&d.viewMode!=="source"){let ke=Is(ye);ke==="markdown"?pe=!0:(ke==="html"||ke==="svg")&&(pe=o?.filePreview?.enabled!==!1)}Ae.element.classList.toggle("persona-hidden",!pe),Ae.setSelected(he())}if(le.replaceChildren(),!ve&&p.length>0){let ye=Ws(Z);if(ye)for(let pe of p)try{if(pe.visible===void 0||pe.visible(ye)){let ke=Br(pe,{documentChrome:!0});ke.setAttribute("data-artifact-custom-action",pe.id),ke.classList.add("persona-flex-shrink-0"),le.appendChild(ke)}}catch{}}};return me(n),To.set(g,(Z,de)=>{if(c&&S!=="complete"&&Z.status==="complete"){let ee=g.isConnected?g.getBoundingClientRect().height:0;S="complete";let ve=Z,ye=!1,pe=ke=>{ve=ke,ye=!0};To.set(g,pe),jy(g,ee,{swap:()=>{C(ve),ye=!1,To.set(g,pe)},onSettled:()=>{ye?C(ve):To.set(g,ke=>{g.replaceChildren(y(ke))})}});return}(Z.status!=="complete"||Z.id!==b.id)&&(u=null),b=Z,I(Z,de),me(Z)}),g}var tg=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=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",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Zu(e,t)});if(i)return i}return Zu(e,t)};var dc=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Tn=new dc;Tn.register("PersonaArtifactCard",pi,{bubbleChrome:!1});Tn.register("PersonaArtifactInline",tg,{bubbleChrome:!1});function Bs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?ai(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var pc=!1;function qy(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function ng(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||pc||s){o();return}pc=!0;let a=qy(n);e.style.setProperty("view-transition-name",a);let i=()=>{pc=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var Vy="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Ky="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Gy(e){let t=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Jy(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var Xy=220;function Qy(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Yy(e){return`
32
- <script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function Zy(e,t,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=m("div","persona-artifact-frame-loading-indicator");r.appendChild($u());let s=null;return n.label!==!1&&(s=m("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function eb(e,t,n,o,r,s){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(S=>clearTimeout(S)),d.clear()},u=(S,I)=>{let j=setTimeout(()=>{d.delete(j),S()},I);d.add(j)},b=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||p)return;let S=Zy(r,s,o);a=S.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(S.revealLabel,o.labelDelayMs)},y=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(b,Xy))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",P):t.removeEventListener("load",W)},k=()=>{if(p||(p=!0,C(),c(),!a))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-i));S>0?u(y,S):y()};function P(S){if(n===null)return;let I=S.data;!I||I.persona!=="artifact-preview-ready"||I.token!==n||S.source===t.contentWindow&&k()}function W(){let S=I=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>I()):setTimeout(I,0)};S(()=>S(()=>k()))}return u(g,o.delayMs),u(k,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",P):t.addEventListener("load",W),()=>{p=!0,c(),C(),b()}}function ui(e,t){let{config:n}=t,o=t.registry??Tn,r=t.bodyLayout,s=n.markdown?qo(n.markdown):null,a=Cr(n.sanitize),i=e,p=!1,d=ae=>{let me=$n()!==null;s&&!me&&!p&&(p=!0,xr(()=>Me(i)));let Z=s?s(ae):Pn(ae);return s&&me&&a?a(Z):Z},c=m("div","persona-artifact-preview-body"),u=null,b=null,g=null,y=()=>{g&&(g(),g=null),u=null,b=null},C=null,k=null,P=null,W=!1,S=()=>{C=null,k=null,P=null,W=!1},I=null,j=null,q=()=>{I=null,j=null},w=40,z=0,V=ae=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ae()):setTimeout(ae,0),Y=ae=>ae.scrollHeight-ae.clientHeight-ae.scrollTop<=w,D=ae=>{if(!r)return;let me=ae.scrollHeight-ae.clientHeight>1,Z=ae.scrollHeight-ae.clientHeight-ae.scrollTop;ae.classList.toggle("persona-artifact-fade-top",r.fadeTop&&me&&ae.scrollTop>1),ae.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&me&&Z>1)},N=ae=>{z||(z=V(()=>{z=0,ae.scrollTop=ae.scrollHeight,D(ae)}))},le=(ae,me,Z,de)=>{let ee=!!r,ve=Z.id+"|"+(ee?"w":"p");if(!C||P!==ve||C.parentElement!==c){y(),q(),c.replaceChildren();let ke=m("pre",Vy+" persona-code-pre"),Ne=m("code","persona-code");if(ke.appendChild(Ne),ee){let $e=m("div","persona-artifact-source-window");if($e.appendChild(ke),c.appendChild($e),!(r?.overflow==="clip")&&typeof $e.addEventListener=="function"){let ze=()=>$e.scrollHeight-$e.clientHeight>1;$e.addEventListener("scroll",()=>{Y($e)&&(W=!1),D($e)},{passive:!0}),$e.addEventListener("wheel",Ke=>{ze()&&Ke.deltaY<0&&(W=!0)},{passive:!0}),$e.addEventListener("touchmove",()=>{ze()&&(W=!0)},{passive:!0})}C=$e}else c.appendChild(ke),C=ke;k=Ne,P=ve}let ye=ee?C:null;ye&&(ye.classList.toggle("persona-artifact-source-window--fixed",de),ye.classList.toggle("persona-artifact-source-window--clip",de&&r?.overflow==="clip"));let pe=ye?Y(ye):!0;if(k.replaceChildren(Gu(ae,me?.language,me?.path)),ye){let ke=Z.status!=="complete";de&&ke&&r?.followOutput&&!W&&pe?N(ye):ke||(W=!1),D(ye)}},he=ae=>{y(),S(),q(),c.replaceChildren();let me=m("div",Ky);me.innerHTML=d(ae),c.appendChild(me)},Ae=ae=>{let me=ae.id,Z=n.features?.artifacts,de=Hr(ae,Z,"status-body");if(I&&j===me&&I.parentElement===c){let ye=I.querySelector(".persona-artifact-status-view-text");ye&&Zo(ye,de,Z);return}y(),S(),c.replaceChildren();let ee=m("div","persona-artifact-status-view"),ve=m("div","persona-artifact-status-view-text");Zo(ve,de,Z),ee.appendChild(ve),c.appendChild(ee),I=ee,j=me},Me=ae=>{i=ae;let me=t.resolveViewMode?.(ae)??r?.viewMode??"rendered",Z=ae.artifactType==="markdown"?ae.file:void 0,de=ae.status!=="complete";de||Wr(ae.id);let ee=de?r?.streamingHeight:r?.completeHeight,ve=!!r&&typeof ee=="number";if(r?.streamingView==="status"&&de){Ae(ae);return}if(Z){let pe=ai(ae.markdown??""),ke=Is(Z),Ne=n.features?.artifacts?.filePreview?.enabled!==!1;if(!de&&me==="rendered"&&Ne&&(ke==="html"||ke==="svg")){let Be=ae.id+"\0"+pe;if(u&&b===Be&&u.parentElement===c)return;S(),q(),y(),c.replaceChildren();let ze=n.features?.artifacts?.filePreview,Ke=ze?.iframeSandbox??"allow-scripts";!ze?.dangerouslyAllowSameOrigin&&Ke.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ke=Ke.split(/\s+/).filter(ht=>ht&&ht!=="allow-same-origin").join(" "));let Le=Jy(ze?.loading),oe=m("div","persona-artifact-frame"),Oe=m("iframe","persona-artifact-iframe");Oe.setAttribute("sandbox",Ke),Oe.setAttribute("data-artifact-id",ae.id);let xt=null;Le.enabled&&Le.injectReadySignal?(xt=Qy(),Oe.srcdoc=pe+Yy(xt)):Oe.srcdoc=pe,oe.appendChild(Oe),c.appendChild(oe),Le.enabled&&(g=eb(oe,Oe,xt,Le,ae.id,n)),u=oe,b=Be;return}if(y(),!de&&ke==="markdown"&&me==="rendered"){he(pe);return}le(pe,{language:Z.language,path:Z.path},ae,ve);return}if(ae.artifactType==="markdown"){if(me==="source"){y(),le(ae.markdown??"",void 0,ae,ve);return}he(ae.markdown??"");return}y(),S(),q(),c.replaceChildren();let ye=ae.component?o.get(ae.component):void 0;if(ye){let ke={message:{id:ae.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ne=ye(ae.props??{},ke);if(Ne){c.appendChild(Ne);return}}catch{}}c.appendChild(Gy(ae))};return Me(e),{el:c,update(ae){Me(ae)}}}var og=require("idiomorph"),gi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;og.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",i=s.textContent??"";if(a!==i)return}return!1}}}}})};var rg=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var uc={index:-1,draft:""};function sg(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function ag(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function ig(){return new Map}function lg(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function cg(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function dg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function fi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function In(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Eo(e,t){return In(e)-e.scrollTop<=t}function mi(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function hi(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function pg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ug(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 gg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Os={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},tb=["pre","code","a","script","style"],yi=e=>({type:e?.type??Os.type,placeholder:e?.placeholder??Os.placeholder,speed:e?.speed??Os.speed,duration:e?.duration??Os.duration,buffer:e?.buffer??Os.buffer}),mg=[{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"}],Ds=new Map;for(let e of mg)Ds.set(e.name,e);var hg=e=>{Ds.set(e.name,e)},yg=e=>{mg.some(t=>t.name===e)||Ds.delete(e)},bg=()=>Array.from(Ds.keys()),Or=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Ds.get(e)??null,bi=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
33
- `);return s<0?"":e.slice(0,s)}return e},nb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},ob=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},gc=/\s/,rb=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},sb=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(gc.test(s[i])){let p=i;for(;p<s.length&&gc.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(i,p))),i=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=i;for(;d<s.length&&!gc.test(s[d]);)p.appendChild(nb(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}r.replaceChild(a,e)},ab=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let p of i)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(ob(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},Ns=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??tb).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)rb(p,s)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?sb:ab;for(let u of i)c(u,n,d);return r.innerHTML},vi=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Fs=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},fg=new WeakMap,ib=(e,t)=>{if(!e.styles)return;let n=fg.get(t);if(n||(n=new Set,fg.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},fc=new WeakMap,lb=(e,t)=>{if(!e.onAttach)return;let n=fc.get(t);if(n||(n=new Map,fc.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},vg=e=>{let t=fc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},xi=(e,t)=>{ib(e,t),lb(e,t)};function mc(e,t=zt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var _s=0,Mo=null;function hc(e=document){if(_s++,_s===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Mo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,_s=Math.max(0,_s-1),_s===0&&Mo)){let n=e.body,o=e.defaultView??window;n.style.overflow=Mo.originalOverflow,n.style.position=Mo.originalPosition,n.style.top=Mo.originalTop,n.style.width=Mo.originalWidth,o.scrollTo(0,Mo.scrollY),Mo=null}}}var $s={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=e=>(e?.launcher?.mountMode??"floating")==="docked",ko=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Zt=e=>{let t=e?.launcher?.dock;return{side:t?.side??$s.side,width:t?.width??$s.width,animate:t?.animate??$s.animate,reveal:t?.reveal??$s.reveal,maxHeight:t?.maxHeight??$s.maxHeight}};var En={"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 cb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ci=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=cb,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},i=r??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",b=a.closeButtonIconText??"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),y=_e("button",{className:jn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Gt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${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}}),C=ne(u,s,"currentColor",1);return C?(C.style.display="block",y.appendChild(C)):y.textContent=b,p.appendChild(y),Nt({anchor:y,trigger:p,text:()=>y.getAttribute("aria-label")??d,enabled:c}),{button:y,wrapper:p}},db="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wi=(e,t={})=>{let{wrapperClassName:n=db,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",b=a.borderColor??"",g=a.borderRadius??"",y=a.paddingX??"",C=a.paddingY??"",k=a.tooltipText??"Clear chat",P=a.showTooltip??!0,W=m("div",n),S=!!(u||b),I=_e("button",{className:jn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":k},style:{height:i,width:i,color:d||Gt.actionIconColor,backgroundColor:c||void 0,border:S?`${u||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),j=ne(p,r,"currentColor",1);return j&&(j.style.display="block",I.appendChild(j)),W.appendChild(I),Nt({anchor:I,trigger:W,text:()=>I.getAttribute("aria-label")??k,enabled:P}),{button:I,wrapper:W}};var Gt={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))"},Jn=e=>{let{config:t,showClose:n=!0}=e,o=_e("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)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",i=r.headerIconHidden??!1,p=r.headerIconName,d=_e("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(p){let j=parseFloat(s)||24,q=ne(p,j*.6,"currentColor",1);q?d.replaceChildren(q):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let j=m("img");j.src=t.launcher.iconUrl,j.alt="",j.className="persona-rounded-xl persona-object-cover",j.style.height=s,j.style.width=s,d.replaceChildren(j)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=_e("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Gt.titleColor}}),b=_e("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Gt.subtitleColor}});c.append(u,b),i?o.append(c):o.append(d,c);let g=r.clearChat??{},y=g.enabled??!0,C=g.placement??"inline",k=null,P=null;if(y){let q=wi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=q.button,P=q.wrapper,C==="top-right"&&(P.style.right="48px"),C==="inline"&&o.appendChild(P)}let W=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:S,wrapper:I}=Ci(t,{showClose:n,wrapperClassName:W});return a!=="top-right"&&o.appendChild(I),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:b,closeButton:S,closeButtonWrapper:I,clearChatButton:k,clearChatButtonWrapper:P}},er=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var yc=e=>{let t=Jn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function pb(e,t,n){if(t?.length)for(let o of t){let r=m("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(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ne(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=m("div","persona-relative");s.appendChild(r);let a=So({items:o.menuItems,onSelect:i=>n?.(i),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var bc=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},i=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=ci({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Gt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Gt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),pb(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let S=r.onTitleClick;d.addEventListener("click",I=>{I.target.closest("button")||S()}),d.addEventListener("keydown",I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),S())})}let W=r?.titleRowHover;W&&(d.style.borderRadius=W.borderRadius??"10px",d.style.padding=W.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=W.background??"",d.style.borderColor=W.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=a.closeButtonSize??"32px",b=m("div",""),g=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Gt.actionIconColor;let y=a.closeButtonIconName??"x",C=ne(y,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),b.appendChild(g),i.appendChild(b);let k=m("div");k.style.display="none";let P=m("span");return P.style.display="none",{header:i,iconHolder:k,headerTitle:c,headerSubtitle:P,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},Ai={default:yc,minimal:bc},vc=e=>Ai[e]??Ai.default,Dr=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=m("div");i.style.display="none";let p=m("span"),d=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:i,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=vc(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Si=e=>{let t=m("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"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,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,r());t.style.height=`${a}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:s}},Ti=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",b=t.backgroundColor,g=t.textColor,y=m("div","persona-send-button-wrapper"),C=_e("button",{className:jn("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&&!b&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&b||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}}),k=null,P=null;if(n){let I=parseFloat(u)||24,j=g?.trim()||"currentColor";r?(k=ne(r,I,j,2),k?C.appendChild(k):C.textContent=o):C.textContent=o,P=ne(s,I,j,2)}else C.textContent=p;C.setAttribute("aria-label",a),y.appendChild(C),Nt({anchor:C,trigger:y,text:()=>C.getAttribute("aria-label")??"",enabled:c});let W="send";return{button:C,wrapper:y,setMode:I=>{if(I===W)return;W=I;let j=I==="stop"?i:a;if(C.setAttribute("aria-label",j),n){if(k&&P){let q=I==="stop"?P:k;C.replaceChildren(q)}}else C.textContent=I==="stop"?d:p}}},Ei=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,b=m("div","persona-send-button-wrapper"),g=_e("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":t.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ne(i,d,u||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",b.appendChild(g);let k=t.tooltipText??"Start voice recognition",P=t.showTooltip??!1;return Nt({anchor:g,trigger:b,text:()=>g.getAttribute("aria-label")??k,enabled:P}),{button:g,wrapper:b}},Mi=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=m("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Vn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,p=Math.round(i*.6),d=m("div","persona-send-button-wrapper"),c=_e("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":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=ne(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",g=>{g.preventDefault(),r.click()}),d.appendChild(c);let b=t.buttonTooltipText??"Attach file";return Nt({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??b}),{button:c,wrapper:d,input:r,previewsContainer:o}},ki=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=m("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Li=()=>_e("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Nr=e=>{let{config:t}=e,n=_e("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Li(),r=_e("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:s,attachAutoResize:a}=Si(t);a();let i=Ti(t),p=Ei(t),d=Mi(t),c=ki(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=_e("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&b.append(d.wrapper),p&&g.append(p.wrapper),g.append(i.wrapper),u.append(b,g),r.append(u),r.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:b,rightActions:g,setSendButtonMode:i.setMode}};var xg=()=>{let e=_e("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=m("span","persona-pill-peek__icon"),n=ne("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=m("span","persona-pill-peek__text"),r=m("span","persona-pill-peek__caret"),s=ne("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Cg=e=>{let{config:t}=e,n=_e("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Li(),r=ki(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Si(t);s.style.maxHeight="100px",a();let i=Ti(t),p=Ei(t),d=Mi(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=_e("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let b=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.append(i.wrapper),c.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,b),d&&n.append(d.previewsContainer),n.append(o,c,r);let g=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:u,rightActions:b,setSendButtonMode:i.setMode}};var wg=e=>{let t=e?.launcher?.enabled??!0,n=Lt(e);if(ko(e)){let c=e?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??zt);let b=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",u.appendChild(b);let g=m("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??zt),{wrapper:u,panel:b,pillRoot:g}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=e?.launcher?.width??"100%";return c.style.width=b,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&En[r.position]?En[r.position]:En["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??zt);let i=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??sn;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},ub=(e,t)=>{let n=m("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:o,wrapper:r}=Ci(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(s){let I=wi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=I.button,i=I.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=_e("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=_e("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let c=_e("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=_e("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),b=_e("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u),g=m("div","persona-flex persona-flex-col persona-gap-3"),y=e?.layout?.contentMaxWidth;y&&(g.style.maxWidth=y,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(b.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(b,g);let k=_e("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"}}),P=Cg({config:e}),{root:W,textNode:S}=xg();return n.append(p,r,d,k),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:g,composerOverlay:k,suggestions:P.suggestions,textarea:P.textarea,sendButton:P.sendButton,sendButtonWrapper:P.sendButtonWrapper,micButton:P.micButton,micButtonWrapper:P.micButtonWrapper,composerForm:P.composerForm,statusText:P.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:P.footer,attachmentButton:P.attachmentButton,attachmentButtonWrapper:P.attachmentButtonWrapper,attachmentInput:P.attachmentInput,attachmentPreviewsContainer:P.attachmentPreviewsContainer,actionsRow:P.actionsRow,leftActions:P.leftActions,rightActions:P.rightActions,setSendButtonMode:P.setSendButtonMode,peekBanner:W,peekTextNode:S}},Ag=(e,t=!0)=>{if(ko(e))return ub(e,t);let n=_e("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Dr(e,o,{showClose:t}):Jn({config:e,showClose:t}),a=_e("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=_e("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=_e("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=_e("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Lt(e)?"none":"var(--persona-intro-card-shadow, none)"}},i,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let g=Nr({config:e}),y=e?.layout?.showFooter!==!1;r?er(n,s,e):(s.header.style.display="none",er(n,s,e)),n.append(a);let C=_e("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 y||(g.footer.style.display="none"),n.append(g.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:p,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var xc=(e,t)=>{let n=m("button");n.type="button",n.innerHTML=`
31
+ `)),n=m("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Zu(e,t,n){let o=e.length<=Ly?Py(t,n):null,r=o?Ny(e,o):[{type:"plain",value:e}];return Fy(r)}function So(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(si)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let k=document.createElement("hr");a.appendChild(k)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",g.id),g.destructive&&y.setAttribute("data-destructive",""),g.icon){let k=ne(g.icon,16,"currentColor",1.5);k&&y.appendChild(k)}let C=document.createElement("span");C.textContent=g.label,y.appendChild(C),y.addEventListener("click",k=>{k.stopPropagation(),c(),n(g.id)}),a.appendChild(y)}let i=null;function p(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=y=>{!a.contains(y.target)&&!o.contains(y.target)&&c()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?d():c()}function b(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:b}}function ct(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,p=m("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ne(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),i)for(let[c,u]of Object.entries(i))p.setAttribute(c,u);return p}function Kn(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let b=ne(t,s??14,"currentColor",2);b&&c.appendChild(b)}let u=m("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),p)for(let[b,g]of Object.entries(p))c.setAttribute(b,g);return c}function Gn(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=m("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,i=[];function p(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=ct({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=m("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),i.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function mi(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:p}=e,d=m("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=m("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=ne(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let b=So({items:o,onSelect:g=>{d.setAttribute("aria-expanded","false"),r(g)},anchor:d,position:s,portal:a});return a||d.appendChild(b.element),d.addEventListener("click",g=>{g.stopPropagation();let y=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",y?"false":"true"),b.toggle()}),d.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),d.click())}),{element:d,setLabel:g=>{c.textContent=g,d.setAttribute("aria-label",g)},open:()=>{d.setAttribute("aria-expanded","true"),b.show()},close:()=>{d.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let g=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",g?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),d.remove()}}}var hi="persona-artifact-custom-action-btn";function Or(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+hi+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+hi+(n?" persona-artifact-doc-icon-btn":"");o=m("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=m("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Kn({icon:e.icon,label:e.label,className:hi+(n?" persona-artifact-doc-copy-btn":"")}):o=ct({icon:e.icon,label:e.label,className:hi+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Bs(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function eg(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Pn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n?wo(n):i==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let b=document.createElement("div");b.className="persona-truncate persona-text-sm persona-font-medium",b.style.color="var(--persona-text, #1f2937)",b.textContent=r;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let y=t?.config?.features?.artifacts,C={id:s,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},k=Br(C,y,"card");er(g,k,y)}else s&&Hr(s),g.textContent=p;if(u.append(b,g),d.append(c,u),a==="complete"){let y=t?.config?.features?.artifacts?.cardActions;if(y&&y.length>0){let k={artifactId:s||null,title:r,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let P of y)try{if(P.visible===void 0||P.visible(k)){let W=Or(P);W.setAttribute("data-artifact-custom-action",P.id),W.className=`${W.className} persona-flex-shrink-0`,d.append(W)}}catch{}}let C=Kn({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),d.append(C)}return d}var yi=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=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",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>eg(e,t)});if(i)return i}return eg(e,t)};var To=new WeakMap;function uc(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=To.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function sg(e){return To.has(e)}function _y(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let s=e.componentProps,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:a}}let r=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...r?{file:r}:{}}}function tg(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Pn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?wo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function $y(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var ng=180,jy=240,Uy=.8,zy=300,qy=500,Vy="cubic-bezier(0.2, 0, 0, 1)",og=240,Ky=.35;function Gy(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let i of Array.from(e.children))i instanceof HTMLElement&&a.push(i.animate([{opacity:1},{opacity:0}],{duration:ng,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let P of a)P.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){i(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(qy,Math.max(zy,jy+d*Uy))),u=Math.round(c*Ky),b=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=b?b.animate([{opacity:0},{opacity:1}],{duration:og,delay:u,easing:"ease-out",fill:"backwards"}):null,y=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:Vy});e.style.height=`${p}px`;let C=!1,k=()=>{C||(C=!0,i(),r())};Promise.allSettled([y.finished,g?.finished].filter(Boolean)).then(k),window.setTimeout(k,Math.max(c,u+og)+120)},ng)}function Jy(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Os="--persona-artifact-inline-body-height";function Xy(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",p=i==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):i==="clip"?(d=!1,c=!0):(d=!0,c=!0);let b=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:i,fadeTop:d,fadeBottom:c,transition:b,completeDisplay:g}}function rg(e,t){let n=_y(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:i}=Jy(o),p=o?.inlineActions??[],d=Xy(o),c=d.completeDisplay==="card",u=null,b=n,g=m("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let y=Z=>yi($y(Z),t),C=Z=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Os),g.replaceChildren(y(Z)),To.set(g,de=>{g.replaceChildren(y(de))})};if(c&&n.status==="complete")return C(n),g;let k=bi(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),P=m("div","persona-artifact-inline-body");P.appendChild(k.el);let W=Z=>{let de=Z.status!=="complete",ee=de?d.streamingHeight:d.completeHeight,ve=typeof ee=="number";ve?g.style.setProperty(Os,`${ee}px`):g.style.removeProperty(Os);let ye=!!k.el.querySelector(".persona-code-pre"),pe=!!k.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");P.classList.toggle("persona-artifact-content-flush",ye),P.classList.toggle("persona-artifact-inline-body--sized",ve&&pe),P.classList.toggle("persona-artifact-inline-body--cap",!de&&!pe&&typeof d.completeHeight=="number")},S=n.status,I=(Z,de)=>{S!=="complete"&&Z.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(Os,`${d.completeHeight}px`):g.style.removeProperty(Os),ig(P,de?.suppressTransition?"none":d.transition,Z.id,()=>{k.update(Z),W(Z)})):k.update(Z),W(Z),S=Z.status};W(n);let j=d.overflow==="clip"&&a&&!!n.id;if(j&&(P.setAttribute("data-expand-artifact-inline",n.id),P.setAttribute("role","button"),P.setAttribute("tabindex","0"),P.classList.add("persona-cursor-pointer"),P.setAttribute("aria-label",`Open ${tg(n).title} in panel`)),!r)return g.appendChild(P),To.set(g,I),g;let q=m("div","persona-artifact-inline-chrome");q.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=m("div","persona-artifact-inline-chrome-lead"),z=m("span","persona-flex persona-items-center persona-flex-shrink-0"),V=ne("file-text",16,"currentColor",2);V&&z.appendChild(V);let Y=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=m("span","persona-artifact-inline-type");w.append(z,Y,D);let N=m("div","persona-artifact-inline-chrome-actions"),ce=m("span","persona-flex persona-items-center persona-gap-1"),he=()=>u??d.viewMode,Ae=i?Gn({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:he(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let de=Z==="source"?"source":"rendered";de!==he()&&(u=de,k.update(b),W(b))}}):null,Me=s?ct({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Me&&n.id&&Me.setAttribute("data-copy-artifact",n.id);let ae=a?ct({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ae&&n.id&&ae.setAttribute("data-expand-artifact-inline",n.id),N.appendChild(ce),Ae&&N.appendChild(Ae.element),Me&&N.appendChild(Me),ae&&N.appendChild(ae),q.append(w,N),g.append(q,P);let me=Z=>{let{title:de,typeLabel:ee}=tg(Z);Y.textContent=de,Y.title=de,j&&P.setAttribute("aria-label",`Open ${de} in panel`);let ve=Z.status!=="complete";if(ve){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let ye=Br(Z,o,"inline-chrome");er(D,ye,o)}else Hr(Z.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=ee;if(Me&&Me.classList.toggle("persona-hidden",ve),Ae){let ye=Z.artifactType==="markdown"?Z.file:void 0,pe=!1;if(!ve&&ye&&d.viewMode!=="source"){let ke=Hs(ye);ke==="markdown"?pe=!0:(ke==="html"||ke==="svg")&&(pe=o?.filePreview?.enabled!==!1)}Ae.element.classList.toggle("persona-hidden",!pe),Ae.setSelected(he())}if(ce.replaceChildren(),!ve&&p.length>0){let ye=Bs(Z);if(ye)for(let pe of p)try{if(pe.visible===void 0||pe.visible(ye)){let ke=Or(pe,{documentChrome:!0});ke.setAttribute("data-artifact-custom-action",pe.id),ke.classList.add("persona-flex-shrink-0"),ce.appendChild(ke)}}catch{}}};return me(n),To.set(g,(Z,de)=>{if(c&&S!=="complete"&&Z.status==="complete"){let ee=g.isConnected?g.getBoundingClientRect().height:0;S="complete";let ve=Z,ye=!1,pe=ke=>{ve=ke,ye=!0};To.set(g,pe),Gy(g,ee,{swap:()=>{C(ve),ye=!1,To.set(g,pe)},onSettled:()=>{ye?C(ve):To.set(g,ke=>{g.replaceChildren(y(ke))})}});return}(Z.status!=="complete"||Z.id!==b.id)&&(u=null),b=Z,I(Z,de),me(Z)}),g}var ag=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=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",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>rg(e,t)});if(i)return i}return rg(e,t)};var gc=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Sn=new gc;Sn.register("PersonaArtifactCard",yi,{bubbleChrome:!1});Sn.register("PersonaArtifactInline",ag,{bubbleChrome:!1});function Ds(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?ui(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var fc=!1;function Qy(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function ig(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||fc||s){o();return}fc=!0;let a=Qy(n);e.style.setProperty("view-transition-name",a);let i=()=>{fc=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var Yy="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Zy="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function eb(e){let t=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function tb(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var nb=220;function ob(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function rb(e){return`
32
+ <script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function sb(e,t,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=m("div","persona-artifact-frame-loading-indicator");r.appendChild(Vu());let s=null;return n.label!==!1&&(s=m("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function ab(e,t,n,o,r,s){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(S=>clearTimeout(S)),d.clear()},u=(S,I)=>{let j=setTimeout(()=>{d.delete(j),S()},I);d.add(j)},b=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||p)return;let S=sb(r,s,o);a=S.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(S.revealLabel,o.labelDelayMs)},y=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(b,nb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",P):t.removeEventListener("load",W)},k=()=>{if(p||(p=!0,C(),c(),!a))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-i));S>0?u(y,S):y()};function P(S){if(n===null)return;let I=S.data;!I||I.persona!=="artifact-preview-ready"||I.token!==n||S.source===t.contentWindow&&k()}function W(){let S=I=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>I()):setTimeout(I,0)};S(()=>S(()=>k()))}return u(g,o.delayMs),u(k,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",P):t.addEventListener("load",W),()=>{p=!0,c(),C(),b()}}function bi(e,t){let{config:n}=t,o=t.registry??Sn,r=t.bodyLayout,s=n.markdown?Vo(n.markdown):null,a=wr(n.sanitize),i=e,p=!1,d=ae=>{let me=_n()!==null;s&&!me&&!p&&(p=!0,Cr(()=>Me(i)));let Z=s?s(ae):Ln(ae);return s&&me&&a?a(Z):Z},c=m("div","persona-artifact-preview-body"),u=null,b=null,g=null,y=()=>{g&&(g(),g=null),u=null,b=null},C=null,k=null,P=null,W=!1,S=()=>{C=null,k=null,P=null,W=!1},I=null,j=null,q=()=>{I=null,j=null},w=40,z=0,V=ae=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ae()):setTimeout(ae,0),Y=ae=>ae.scrollHeight-ae.clientHeight-ae.scrollTop<=w,D=ae=>{if(!r)return;let me=ae.scrollHeight-ae.clientHeight>1,Z=ae.scrollHeight-ae.clientHeight-ae.scrollTop;ae.classList.toggle("persona-artifact-fade-top",r.fadeTop&&me&&ae.scrollTop>1),ae.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&me&&Z>1)},N=ae=>{z||(z=V(()=>{z=0,ae.scrollTop=ae.scrollHeight,D(ae)}))},ce=(ae,me,Z,de)=>{let ee=!!r,ve=Z.id+"|"+(ee?"w":"p");if(!C||P!==ve||C.parentElement!==c){y(),q(),c.replaceChildren();let ke=m("pre",Yy+" persona-code-pre"),Ne=m("code","persona-code");if(ke.appendChild(Ne),ee){let $e=m("div","persona-artifact-source-window");if($e.appendChild(ke),c.appendChild($e),!(r?.overflow==="clip")&&typeof $e.addEventListener=="function"){let ze=()=>$e.scrollHeight-$e.clientHeight>1;$e.addEventListener("scroll",()=>{Y($e)&&(W=!1),D($e)},{passive:!0}),$e.addEventListener("wheel",Ke=>{ze()&&Ke.deltaY<0&&(W=!0)},{passive:!0}),$e.addEventListener("touchmove",()=>{ze()&&(W=!0)},{passive:!0})}C=$e}else c.appendChild(ke),C=ke;k=Ne,P=ve}let ye=ee?C:null;ye&&(ye.classList.toggle("persona-artifact-source-window--fixed",de),ye.classList.toggle("persona-artifact-source-window--clip",de&&r?.overflow==="clip"));let pe=ye?Y(ye):!0;if(k.replaceChildren(Zu(ae,me?.language,me?.path)),ye){let ke=Z.status!=="complete";de&&ke&&r?.followOutput&&!W&&pe?N(ye):ke||(W=!1),D(ye)}},he=ae=>{y(),S(),q(),c.replaceChildren();let me=m("div",Zy);me.innerHTML=d(ae),c.appendChild(me)},Ae=ae=>{let me=ae.id,Z=n.features?.artifacts,de=Br(ae,Z,"status-body");if(I&&j===me&&I.parentElement===c){let ye=I.querySelector(".persona-artifact-status-view-text");ye&&er(ye,de,Z);return}y(),S(),c.replaceChildren();let ee=m("div","persona-artifact-status-view"),ve=m("div","persona-artifact-status-view-text");er(ve,de,Z),ee.appendChild(ve),c.appendChild(ee),I=ee,j=me},Me=ae=>{i=ae;let me=t.resolveViewMode?.(ae)??r?.viewMode??"rendered",Z=ae.artifactType==="markdown"?ae.file:void 0,de=ae.status!=="complete";de||Hr(ae.id);let ee=de?r?.streamingHeight:r?.completeHeight,ve=!!r&&typeof ee=="number";if(r?.streamingView==="status"&&de){Ae(ae);return}if(Z){let pe=ui(ae.markdown??""),ke=Hs(Z),Ne=n.features?.artifacts?.filePreview?.enabled!==!1;if(!de&&me==="rendered"&&Ne&&(ke==="html"||ke==="svg")){let Be=ae.id+"\0"+pe;if(u&&b===Be&&u.parentElement===c)return;S(),q(),y(),c.replaceChildren();let ze=n.features?.artifacts?.filePreview,Ke=ze?.iframeSandbox??"allow-scripts";!ze?.dangerouslyAllowSameOrigin&&Ke.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ke=Ke.split(/\s+/).filter(ht=>ht&&ht!=="allow-same-origin").join(" "));let Le=tb(ze?.loading),oe=m("div","persona-artifact-frame"),Oe=m("iframe","persona-artifact-iframe");Oe.setAttribute("sandbox",Ke),Oe.setAttribute("data-artifact-id",ae.id);let xt=null;Le.enabled&&Le.injectReadySignal?(xt=ob(),Oe.srcdoc=pe+rb(xt)):Oe.srcdoc=pe,oe.appendChild(Oe),c.appendChild(oe),Le.enabled&&(g=ab(oe,Oe,xt,Le,ae.id,n)),u=oe,b=Be;return}if(y(),!de&&ke==="markdown"&&me==="rendered"){he(pe);return}ce(pe,{language:Z.language,path:Z.path},ae,ve);return}if(ae.artifactType==="markdown"){if(me==="source"){y(),ce(ae.markdown??"",void 0,ae,ve);return}he(ae.markdown??"");return}y(),S(),q(),c.replaceChildren();let ye=ae.component?o.get(ae.component):void 0;if(ye){let ke={message:{id:ae.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ne=ye(ae.props??{},ke);if(Ne){c.appendChild(Ne);return}}catch{}}c.appendChild(eb(ae))};return Me(e),{el:c,update(ae){Me(ae)}}}var lg=require("idiomorph"),vi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;lg.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",i=s.textContent??"";if(a!==i)return}return!1}}}}})};var cg=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var mc={index:-1,draft:""};function dg(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function pg(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function ug(){return new Map}function gg(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function fg(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function mg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function hg(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function xi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Rn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Eo(e,t){return Rn(e)-e.scrollTop<=t}function Ci(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function wi(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function yg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function bg(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 Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ib=["pre","code","a","script","style"],Ai=e=>({type:e?.type??Ns.type,placeholder:e?.placeholder??Ns.placeholder,speed:e?.speed??Ns.speed,duration:e?.duration??Ns.duration,buffer:e?.buffer??Ns.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"}],Fs=new Map;for(let e of Cg)Fs.set(e.name,e);var wg=e=>{Fs.set(e.name,e)},Ag=e=>{Cg.some(t=>t.name===e)||Fs.delete(e)},Sg=()=>Array.from(Fs.keys()),Dr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Fs.get(e)??null,Si=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
33
+ `);return s<0?"":e.slice(0,s)}return e},lb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},cb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},hc=/\s/,db=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},pb=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(hc.test(s[i])){let p=i;for(;p<s.length&&hc.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(i,p))),i=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=i;for(;d<s.length&&!hc.test(s[d]);)p.appendChild(lb(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}r.replaceChild(a,e)},ub=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let p of i)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(cb(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},_s=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??ib).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)db(p,s)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?pb:ub;for(let u of i)c(u,n,d);return r.innerHTML},Ti=(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},$s=(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},xg=new WeakMap,gb=(e,t)=>{if(!e.styles)return;let n=xg.get(t);if(n||(n=new Set,xg.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},yc=new WeakMap,fb=(e,t)=>{if(!e.onAttach)return;let n=yc.get(t);if(n||(n=new Map,yc.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Tg=e=>{let t=yc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ei=(e,t)=>{gb(e,t),fb(e,t)};function bc(e,t=zt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var js=0,Mo=null;function vc(e=document){if(js++,js===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Mo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,js=Math.max(0,js-1),js===0&&Mo)){let n=e.body,o=e.defaultView??window;n.style.overflow=Mo.originalOverflow,n.style.position=Mo.originalPosition,n.style.top=Mo.originalTop,n.style.width=Mo.originalWidth,o.scrollTo(0,Mo.scrollY),Mo=null}}}var Us={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=e=>(e?.launcher?.mountMode??"floating")==="docked",ko=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Zt=e=>{let t=e?.launcher?.dock;return{side:t?.side??Us.side,width:t?.width??Us.width,animate:t?.animate??Us.animate,reveal:t?.reveal??Us.reveal,maxHeight:t?.maxHeight??Us.maxHeight}};var Tn={"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 mb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Mi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=mb,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},i=r??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",b=a.closeButtonIconText??"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),y=_e("button",{className:$n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Jt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${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}}),C=ne(u,s,"currentColor",1);return C?(C.style.display="block",y.appendChild(C)):y.textContent=b,p.appendChild(y),Nt({anchor:y,trigger:p,text:()=>y.getAttribute("aria-label")??d,enabled:c}),{button:y,wrapper:p}},hb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ki=(e,t={})=>{let{wrapperClassName:n=hb,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",b=a.borderColor??"",g=a.borderRadius??"",y=a.paddingX??"",C=a.paddingY??"",k=a.tooltipText??"Clear chat",P=a.showTooltip??!0,W=m("div",n),S=!!(u||b),I=_e("button",{className:$n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":k},style:{height:i,width:i,color:d||Jt.actionIconColor,backgroundColor:c||void 0,border:S?`${u||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),j=ne(p,r,"currentColor",1);return j&&(j.style.display="block",I.appendChild(j)),W.appendChild(I),Nt({anchor:I,trigger:W,text:()=>I.getAttribute("aria-label")??k,enabled:P}),{button:I,wrapper:W}};var Jt={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))"},Jn=e=>{let{config:t,showClose:n=!0}=e,o=_e("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)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",i=r.headerIconHidden??!1,p=r.headerIconName,d=_e("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(p){let j=parseFloat(s)||24,q=ne(p,j*.6,"currentColor",1);q?d.replaceChildren(q):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let j=m("img");j.src=t.launcher.iconUrl,j.alt="",j.className="persona-rounded-xl persona-object-cover",j.style.height=s,j.style.width=s,d.replaceChildren(j)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=_e("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Jt.titleColor}}),b=_e("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.subtitleColor}});c.append(u,b),i?o.append(c):o.append(d,c);let g=r.clearChat??{},y=g.enabled??!0,C=g.placement??"inline",k=null,P=null;if(y){let q=ki(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=q.button,P=q.wrapper,C==="top-right"&&(P.style.right="48px"),C==="inline"&&o.appendChild(P)}let W=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:S,wrapper:I}=Mi(t,{showClose:n,wrapperClassName:W});return a!=="top-right"&&o.appendChild(I),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:b,closeButton:S,closeButtonWrapper:I,clearChatButton:k,clearChatButtonWrapper:P}},tr=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var xc=e=>{let t=Jn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function yb(e,t,n){if(t?.length)for(let o of t){let r=m("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(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ne(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=m("div","persona-relative");s.appendChild(r);let a=So({items:o.menuItems,onSelect:i=>n?.(i),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Cc=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},i=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=mi({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Jt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Jt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),yb(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let S=r.onTitleClick;d.addEventListener("click",I=>{I.target.closest("button")||S()}),d.addEventListener("keydown",I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),S())})}let W=r?.titleRowHover;W&&(d.style.borderRadius=W.borderRadius??"10px",d.style.padding=W.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=W.background??"",d.style.borderColor=W.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=a.closeButtonSize??"32px",b=m("div",""),g=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Jt.actionIconColor;let y=a.closeButtonIconName??"x",C=ne(y,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),b.appendChild(g),i.appendChild(b);let k=m("div");k.style.display="none";let P=m("span");return P.style.display="none",{header:i,iconHolder:k,headerTitle:c,headerSubtitle:P,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},Li={default:xc,minimal:Cc},wc=e=>Li[e]??Li.default,Nr=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=m("div");i.style.display="none";let p=m("span"),d=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:i,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=wc(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Pi=e=>{let t=m("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"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,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,r());t.style.height=`${a}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:s}},Ri=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",b=t.backgroundColor,g=t.textColor,y=m("div","persona-send-button-wrapper"),C=_e("button",{className:$n("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&&!b&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&b||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}}),k=null,P=null;if(n){let I=parseFloat(u)||24,j=g?.trim()||"currentColor";r?(k=ne(r,I,j,2),k?C.appendChild(k):C.textContent=o):C.textContent=o,P=ne(s,I,j,2)}else C.textContent=p;C.setAttribute("aria-label",a),y.appendChild(C),Nt({anchor:C,trigger:y,text:()=>C.getAttribute("aria-label")??"",enabled:c});let W="send";return{button:C,wrapper:y,setMode:I=>{if(I===W)return;W=I;let j=I==="stop"?i:a;if(C.setAttribute("aria-label",j),n){if(k&&P){let q=I==="stop"?P:k;C.replaceChildren(q)}}else C.textContent=I==="stop"?d:p}}},Ii=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,b=m("div","persona-send-button-wrapper"),g=_e("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":t.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ne(i,d,u||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",b.appendChild(g);let k=t.tooltipText??"Start voice recognition",P=t.showTooltip??!1;return Nt({anchor:g,trigger:b,text:()=>g.getAttribute("aria-label")??k,enabled:P}),{button:g,wrapper:b}},Wi=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=m("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Vn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,p=Math.round(i*.6),d=m("div","persona-send-button-wrapper"),c=_e("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":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=ne(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",g=>{g.preventDefault(),r.click()}),d.appendChild(c);let b=t.buttonTooltipText??"Attach file";return Nt({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??b}),{button:c,wrapper:d,input:r,previewsContainer:o}},Hi=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=m("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Bi=()=>_e("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Fr=e=>{let{config:t}=e,n=_e("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Bi(),r=_e("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:s,attachAutoResize:a}=Pi(t);a();let i=Ri(t),p=Ii(t),d=Wi(t),c=Hi(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=_e("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&b.append(d.wrapper),p&&g.append(p.wrapper),g.append(i.wrapper),u.append(b,g),r.append(u),r.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:b,rightActions:g,setSendButtonMode:i.setMode}};var Eg=()=>{let e=_e("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=m("span","persona-pill-peek__icon"),n=ne("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=m("span","persona-pill-peek__text"),r=m("span","persona-pill-peek__caret"),s=ne("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Mg=e=>{let{config:t}=e,n=_e("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Bi(),r=Hi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Pi(t);s.style.maxHeight="100px",a();let i=Ri(t),p=Ii(t),d=Wi(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=_e("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let b=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.append(i.wrapper),c.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,b),d&&n.append(d.previewsContainer),n.append(o,c,r);let g=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:u,rightActions:b,setSendButtonMode:i.setMode}};var kg=e=>{let t=e?.launcher?.enabled??!0,n=Lt(e);if(ko(e)){let c=e?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??zt);let b=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",u.appendChild(b);let g=m("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??zt),{wrapper:u,panel:b,pillRoot:g}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=e?.launcher?.width??"100%";return c.style.width=b,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&Tn[r.position]?Tn[r.position]:Tn["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??zt);let i=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??sn;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},bb=(e,t)=>{let n=m("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:o,wrapper:r}=Mi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(s){let I=ki(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=I.button,i=I.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=_e("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=_e("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let c=_e("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=_e("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),b=_e("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u),g=m("div","persona-flex persona-flex-col persona-gap-3"),y=e?.layout?.contentMaxWidth;y&&(g.style.maxWidth=y,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(b.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(b,g);let k=_e("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"}}),P=Mg({config:e}),{root:W,textNode:S}=Eg();return n.append(p,r,d,k),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:g,composerOverlay:k,suggestions:P.suggestions,textarea:P.textarea,sendButton:P.sendButton,sendButtonWrapper:P.sendButtonWrapper,micButton:P.micButton,micButtonWrapper:P.micButtonWrapper,composerForm:P.composerForm,statusText:P.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:P.footer,attachmentButton:P.attachmentButton,attachmentButtonWrapper:P.attachmentButtonWrapper,attachmentInput:P.attachmentInput,attachmentPreviewsContainer:P.attachmentPreviewsContainer,actionsRow:P.actionsRow,leftActions:P.leftActions,rightActions:P.rightActions,setSendButtonMode:P.setSendButtonMode,peekBanner:W,peekTextNode:S}},Lg=(e,t=!0)=>{if(ko(e))return bb(e,t);let n=_e("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Nr(e,o,{showClose:t}):Jn({config:e,showClose:t}),a=_e("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=_e("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=_e("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=_e("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Lt(e)?"none":"var(--persona-intro-card-shadow, none)"}},i,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let g=Fr({config:e}),y=e?.layout?.showFooter!==!1;r?tr(n,s,e):(s.header.style.display="none",tr(n,s,e)),n.append(a);let C=_e("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 y||(g.footer.style.display="none"),n.append(g.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:p,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var Ac=(e,t)=>{let n=m("button");n.type="button",n.innerHTML=`
34
34
  <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>
35
35
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
36
36
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -38,14 +38,14 @@ _Details: ${n.message}_`:o}var Ms=e=>({isError:!0,content:[{type:"text",text:e}]
38
38
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
39
39
  </span>
40
40
  <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>
41
- `,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},i=Lt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let S=a.title??"Chat Assistant";p.textContent=S,p.setAttribute("title",S)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let S=a.subtitle??"Here to help you get answers fast";d.textContent=S,d.setAttribute("title",S)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||i?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let S=a.agentIconSize??"40px";if(u.style.height=S,u.style.width=S,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let I=parseFloat(S)||24,j=ne(a.agentIconName,I*.6,"var(--persona-text-inverse, #ffffff)",2);j?(u.appendChild(j),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let S=a.agentIconSize??"40px";b.style.height=S,b.style.width=S,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(b.src=a.iconUrl,b.style.display="block"):b.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let S=a.callToActionIconSize??"32px";g.style.height=S,g.style.width=S,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let I=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,I=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let j=parseFloat(S)||24,q=Math.max(j-I,8),w=ne(a.callToActionIconName,q,"currentColor",2);w?g.appendChild(w):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let y=a.position&&En[a.position]?En[a.position]:En["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",k="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?k:`${C} ${y}`,i||(n.style.zIndex=String(a.zIndex??zt));let P="1px solid var(--persona-border, #e5e7eb)",W="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??P,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:W,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=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var Sg=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=wg(e),s=Ag(e,t),a={wrapper:n,panel:o,pillRoot:r},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:p,composer:d,replaceHeader:b=>(p.element.replaceWith(b.header),p.element=b.header,p.iconHolder=b.iconHolder,p.headerTitle=b.headerTitle,p.headerSubtitle=b.headerSubtitle,p.closeButton=b.closeButton,p.closeButtonWrapper=b.closeButtonWrapper,p.clearChatButton=b.clearChatButton,p.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{d.footer.replaceWith(b),d.footer=b}}},Cc=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>xc(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=xc(e,n);return{instance:r,element:r.element}};var gb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},fb=(e,t)=>{if(!e)return null;let n=gb(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},mb=(e,t)=>{let n=m("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},hb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},wc=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(":"))},Ac=320,kg=320,yb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),bb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),vb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),xb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Cb=e=>{if(!e||e.length===0)return null;let t=_e("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=_e("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=m("span","persona-mention-chip-icon"),s=ne(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(_e("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},wb=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ks(o.ref,{readonly:!0,render:t}))}return n},Tg="\uE000",Eg="\uE001",Ab=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${Tg}${r}:${b}${Eg}`,a=t.map((b,g)=>b.kind==="text"?b.text:s(g)).join(""),i=n(a);if(!t.every((b,g)=>b.kind==="text"||i.includes(s(g)))){e.replaceChildren(wb(t,o));return}e.innerHTML=i;let d=new RegExp(`${Tg}${r}:(\\d+)${Eg}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let b=c.nextNode();b;b=c.nextNode())u.push(b);for(let b of u){let g=b;for(let y=d.exec(g.data);y;y=d.exec(g.data)){let C=t[Number(y[1])],k=g.splitText(y.index);k.data=k.data.slice(y[0].length),C?.kind==="mention"&&k.parentNode?.insertBefore(ks(C.ref,{readonly:!0,render:o}),k),g=k}}},Sb=(e,t,n)=>{if(e.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((i,p)=>{let d=m("img");d.alt=i.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Ac}px`,d.style.maxHeight=`${kg}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),hb(i.image)?(d.src=i.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},Tb=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!wc(o.audio))return;let r=m("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ac}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Eb=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!wc(o.video))return;let r=m("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ac}px`,r.style.maxHeight=`${kg}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Mb=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!wc(o.data))return;let r=m("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},tr=()=>{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 o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Sc=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:tr};if(t){let r=t(o);if(r!==null)return r}return tr()},kb=(e,t)=>{let n=m("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=m("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,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},Mg=(e,t,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Lb=(e,t="bubble")=>{let n=["persona-message-bubble"];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},Tc=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let y=m("div");return y.style.display="none",y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id),y}let i=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],b=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id);let g=(y,C,k)=>{let P=ct({icon:y,label:C,size:14,className:"persona-message-action-btn"});return P.setAttribute("data-action",k),P};return o&&b.appendChild(g("copy","Copy message","copy")),a&&b.appendChild(g("volume-2","Read aloud","read-aloud")),r&&b.appendChild(g("thumbs-up","Upvote","upvote")),s&&b.appendChild(g("thumbs-down","Downvote","downvote")),b},Fr=(e,t,n,o,r,s)=>{let a=n??{},i=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,b=p?.position??"left",g=d?.position??"below",y=Lb(e.role,i),C=m("div",y.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),i==="flat"?(C.style.backgroundColor="transparent",C.style.color="var(--persona-primary, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=yb(e),P=e.content?.trim()??"",S=k.length>0&&P===Va,I=yi(s?.widgetConfig?.features?.streamAnimation),j=s?.widgetConfig?.features?.streamAnimation?.plugins,q=e.role==="assistant"&&I.type!=="none"?Or(I.type,j):null,w=e.role==="assistant"&&q?.isAnimating?.(e)===!0,z=e.role==="assistant"&&q!==null&&(!!e.streaming||w);z&&q?.bubbleClass&&C.classList.add(q.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),e.streaming&&V.classList.add("persona-content-streaming"),z&&q&&(q.containerClass&&V.classList.add(q.containerClass),V.style.setProperty("--persona-stream-step",`${I.speed}ms`),V.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let Y=z?bi(e.content??"",I.buffer,q,e,!!e.streaming):e.content??"",D=()=>{let ee=t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent});return z&&q?.wrap==="char"?Ns(ee,"char",e.id,{skipTags:q.skipTags}):z&&q?.wrap==="word"?Ns(ee,"word",e.id,{skipTags:q.skipTags}):ee},N=null;if(S?(N=document.createElement("div"),N.innerHTML=D(),N.style.display="none",V.appendChild(N)):e.contentSegments?.length?Ab(V,e.contentSegments,ee=>t({text:ee,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=D(),z&&q?.useCaret&&!S&&P){let ee=vi(),ve=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),ye=ve[ve.length-1];if(ye?.parentNode)ye.parentNode.insertBefore(ee,ye.nextSibling);else{let pe=V.lastElementChild;pe?pe.appendChild(ee):V.appendChild(ee)}}if(u&&g==="inline"&&e.createdAt){let ee=Mg(e,d,"span");ee.classList.add("persona-timestamp-inline");let ve=V.lastElementChild;ve?ve.appendChild(ee):V.appendChild(ee)}if(k.length>0){let ee=Sb(k,!S&&!!P,()=>{S&&N&&(N.style.display="")});ee?C.appendChild(ee):S&&N&&(N.style.display="")}let le=bb(e);if(le.length>0){let ee=Tb(le);ee&&C.appendChild(ee)}let he=vb(e);if(he.length>0){let ee=Eb(he);ee&&C.appendChild(ee)}let Ae=xb(e);if(Ae.length>0){let ee=Mb(Ae);ee&&C.appendChild(ee)}let Me=e.contentSegments?.length?null:Cb(e.contextMentions);if(Me&&C.appendChild(Me),C.appendChild(V),u&&g==="below"&&e.createdAt){let ee=Mg(e,d);ee.classList.add("persona-mt-1"),C.appendChild(ee)}let ae=e.role==="assistant"?fb(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ee=!!(Y&&Y.trim()),ve=I.placeholder==="skeleton",ye=ve&&I.buffer==="line"&&ee;if(ee)ye&&C.appendChild(Fs());else if(ve)C.appendChild(Fs());else{let pe=Sc("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);pe&&C.appendChild(pe)}}if(ae&&e.stopReason&&!e.streaming&&(P||(V.style.display="none"),C.appendChild(mb(e.stopReason,ae))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let ee=Tc(e,o,r);C.appendChild(ee)}if(!c||e.role==="system")return C;let Z=m("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),de=kb(p,e.role);return b==="right"||b==="left"&&e.role==="user"?Z.append(C,de):Z.append(de,C),Z},Lg=(e,t,n,o,r,s)=>{let a=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}):Fr(e,t,n,o,r,s)};var _r=new Set,Pb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Rb=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
42
- `):""},Pg=(e,t)=>{let n=_r.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=ne(n?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Ec=(e,t)=>{let n=e.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&_r.has(e.id),i=n.status!=="complete",p=Rb(e,r.previewMaxLines??3),d=m("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=m("div","persona-flex persona-flex-col persona-text-left"),u=m("span","persona-text-xs persona-text-persona-primary"),b="Thinking...",g=t?.reasoning??{},y=String(n.startedAt??Date.now()),C=()=>{let he=m("span","");return he.setAttribute("data-tool-elapsed",y),he.textContent=Fa(n),he},k=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:b,previewText:p,isActive:i,config:t??{},elapsed:Fa(n),createElapsedElement:C});typeof k=="string"&&k.trim()?(u.textContent=k,c.appendChild(u)):k instanceof HTMLElement?c.appendChild(k):(u.textContent=b,c.appendChild(u));let P=m("span","persona-text-xs persona-text-persona-primary");P.textContent=Zp(n),c.appendChild(P);let W=r.loadingAnimation??"none",S=g.activeTextTemplate,I=g.completeTextTemplate,j=i?S:I,q=k instanceof HTMLElement,w=(he,Ae)=>{u.textContent="";let Me=_a(he,""),ae=0;for(let me of Me){let Z=me.styles.length>0?(()=>{let de=m("span",me.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return u.appendChild(de),de})():u;if(me.isDuration&&i)Z.appendChild(C());else{let de=me.isDuration?Fa(n):me.text;Ae?ae=Ao(Z,de,ae):Z.appendChild(document.createTextNode(de))}}};if(!q&&j)if(P.style.display="none",u.style.display="",i&&W!=="none"){let he=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),W==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),w(j,!1)):(u.classList.add(`persona-tool-loading-${W}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),W==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),w(j,!0))}else w(j,!1);else if(!q&&i&&W!=="none"){u.style.display="";let he=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),W==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`);else{u.classList.add(`persona-tool-loading-${W}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),W==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Ae=u.textContent||b;u.textContent="",Ao(u,Ae,0)}n.status==="complete"&&(u.style.display="none")}else q||(n.status==="complete"?u.style.display="none":u.style.display="");let z=null;if(s){z=m("div","persona-flex persona-items-center");let Ae=ne(a?"chevron-up":"chevron-down",16,"currentColor",2);Ae?z.appendChild(Ae):z.textContent=a?"Hide":"Show";let Me=m("div","persona-flex persona-items-center persona-ml-auto");Me.append(z),d.append(c,Me)}else d.append(c);let V=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(V.setAttribute("data-persona-collapsed-preview","reasoning"),V.style.display="none",V.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&p){let he=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});Pb(V,he)||(V.textContent=p),V.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,V),o;let Y=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Y.style.display=a?"":"none";let D=n.chunks.join(""),N=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return N.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Y.appendChild(N),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),z){z.innerHTML="";let Ae=ne(a?"chevron-up":"chevron-down",16,"currentColor",2);Ae?z.appendChild(Ae):z.textContent=a?"Hide":"Show"}Y.style.display=a?"":"none",V.style.display=a?"none":V.textContent||V.childNodes.length?"":"none"})(),o.append(d,V,Y),o};var $r=new Set,Ib=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Wb=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
41
+ `,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},i=Lt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let S=a.title??"Chat Assistant";p.textContent=S,p.setAttribute("title",S)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let S=a.subtitle??"Here to help you get answers fast";d.textContent=S,d.setAttribute("title",S)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||i?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let S=a.agentIconSize??"40px";if(u.style.height=S,u.style.width=S,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let I=parseFloat(S)||24,j=ne(a.agentIconName,I*.6,"var(--persona-text-inverse, #ffffff)",2);j?(u.appendChild(j),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let S=a.agentIconSize??"40px";b.style.height=S,b.style.width=S,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(b.src=a.iconUrl,b.style.display="block"):b.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let S=a.callToActionIconSize??"32px";g.style.height=S,g.style.width=S,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let I=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,I=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let j=parseFloat(S)||24,q=Math.max(j-I,8),w=ne(a.callToActionIconName,q,"currentColor",2);w?g.appendChild(w):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let y=a.position&&Tn[a.position]?Tn[a.position]:Tn["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",k="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?k:`${C} ${y}`,i||(n.style.zIndex=String(a.zIndex??zt));let P="1px solid var(--persona-border, #e5e7eb)",W="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??P,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:W,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=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var Pg=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=kg(e),s=Lg(e,t),a={wrapper:n,panel:o,pillRoot:r},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:p,composer:d,replaceHeader:b=>(p.element.replaceWith(b.header),p.element=b.header,p.iconHolder=b.iconHolder,p.headerTitle=b.headerTitle,p.headerSubtitle=b.headerSubtitle,p.closeButton=b.closeButton,p.closeButtonWrapper=b.closeButtonWrapper,p.clearChatButton=b.clearChatButton,p.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{d.footer.replaceWith(b),d.footer=b}}},Sc=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>Ac(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Ac(e,n);return{instance:r,element:r.element}};var vb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},xb=(e,t)=>{if(!e)return null;let n=vb(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Cb=(e,t)=>{let n=m("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},wb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Tc=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Ec=320,Hg=320,Ab=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Sb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Tb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Eb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Mb=e=>{if(!e||e.length===0)return null;let t=_e("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=_e("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=m("span","persona-mention-chip-icon"),s=ne(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(_e("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},kb=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Ps(o.ref,{readonly:!0,render:t}))}return n},Rg="\uE000",Ig="\uE001",Lb=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${Rg}${r}:${b}${Ig}`,a=t.map((b,g)=>b.kind==="text"?b.text:s(g)).join(""),i=n(a);if(!t.every((b,g)=>b.kind==="text"||i.includes(s(g)))){e.replaceChildren(kb(t,o));return}e.innerHTML=i;let d=new RegExp(`${Rg}${r}:(\\d+)${Ig}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let b=c.nextNode();b;b=c.nextNode())u.push(b);for(let b of u){let g=b;for(let y=d.exec(g.data);y;y=d.exec(g.data)){let C=t[Number(y[1])],k=g.splitText(y.index);k.data=k.data.slice(y[0].length),C?.kind==="mention"&&k.parentNode?.insertBefore(Ps(C.ref,{readonly:!0,render:o}),k),g=k}}},Pb=(e,t,n)=>{if(e.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((i,p)=>{let d=m("img");d.alt=i.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Ec}px`,d.style.maxHeight=`${Hg}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),wb(i.image)?(d.src=i.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},Rb=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Tc(o.audio))return;let r=m("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ec}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ib=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Tc(o.video))return;let r=m("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ec}px`,r.style.maxHeight=`${Hg}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Wb=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Tc(o.data))return;let r=m("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},nr=()=>{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 o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Mc=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:nr};if(t){let r=t(o);if(r!==null)return r}return nr()},Hb=(e,t)=>{let n=m("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=m("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,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 o=m(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Bb=(e,t="bubble")=>{let n=["persona-message-bubble"];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},kc=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let y=m("div");return y.style.display="none",y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id),y}let i=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],b=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id);let g=(y,C,k)=>{let P=ct({icon:y,label:C,size:14,className:"persona-message-action-btn"});return P.setAttribute("data-action",k),P};return o&&b.appendChild(g("copy","Copy message","copy")),a&&b.appendChild(g("volume-2","Read aloud","read-aloud")),r&&b.appendChild(g("thumbs-up","Upvote","upvote")),s&&b.appendChild(g("thumbs-down","Downvote","downvote")),b},_r=(e,t,n,o,r,s)=>{let a=n??{},i=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,b=p?.position??"left",g=d?.position??"below",y=Bb(e.role,i),C=m("div",y.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),i==="flat"?(C.style.backgroundColor="transparent",C.style.color="var(--persona-primary, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=Ab(e),P=e.content?.trim()??"",S=k.length>0&&P===Ya,I=Ai(s?.widgetConfig?.features?.streamAnimation),j=s?.widgetConfig?.features?.streamAnimation?.plugins,q=e.role==="assistant"&&I.type!=="none"?Dr(I.type,j):null,w=e.role==="assistant"&&q?.isAnimating?.(e)===!0,z=e.role==="assistant"&&q!==null&&(!!e.streaming||w);z&&q?.bubbleClass&&C.classList.add(q.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),e.streaming&&V.classList.add("persona-content-streaming"),z&&q&&(q.containerClass&&V.classList.add(q.containerClass),V.style.setProperty("--persona-stream-step",`${I.speed}ms`),V.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let Y=z?Si(e.content??"",I.buffer,q,e,!!e.streaming):e.content??"",D=()=>{let ee=t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent});return z&&q?.wrap==="char"?_s(ee,"char",e.id,{skipTags:q.skipTags}):z&&q?.wrap==="word"?_s(ee,"word",e.id,{skipTags:q.skipTags}):ee},N=null;if(S?(N=document.createElement("div"),N.innerHTML=D(),N.style.display="none",V.appendChild(N)):e.contentSegments?.length?Lb(V,e.contentSegments,ee=>t({text:ee,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=D(),z&&q?.useCaret&&!S&&P){let ee=Ti(),ve=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),ye=ve[ve.length-1];if(ye?.parentNode)ye.parentNode.insertBefore(ee,ye.nextSibling);else{let pe=V.lastElementChild;pe?pe.appendChild(ee):V.appendChild(ee)}}if(u&&g==="inline"&&e.createdAt){let ee=Wg(e,d,"span");ee.classList.add("persona-timestamp-inline");let ve=V.lastElementChild;ve?ve.appendChild(ee):V.appendChild(ee)}if(k.length>0){let ee=Pb(k,!S&&!!P,()=>{S&&N&&(N.style.display="")});ee?C.appendChild(ee):S&&N&&(N.style.display="")}let ce=Sb(e);if(ce.length>0){let ee=Rb(ce);ee&&C.appendChild(ee)}let he=Tb(e);if(he.length>0){let ee=Ib(he);ee&&C.appendChild(ee)}let Ae=Eb(e);if(Ae.length>0){let ee=Wb(Ae);ee&&C.appendChild(ee)}let Me=e.contentSegments?.length?null:Mb(e.contextMentions);if(Me&&C.appendChild(Me),C.appendChild(V),u&&g==="below"&&e.createdAt){let ee=Wg(e,d);ee.classList.add("persona-mt-1"),C.appendChild(ee)}let ae=e.role==="assistant"?xb(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ee=!!(Y&&Y.trim()),ve=I.placeholder==="skeleton",ye=ve&&I.buffer==="line"&&ee;if(ee)ye&&C.appendChild($s());else if(ve)C.appendChild($s());else{let pe=Mc("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);pe&&C.appendChild(pe)}}if(ae&&e.stopReason&&!e.streaming&&(P||(V.style.display="none"),C.appendChild(Cb(e.stopReason,ae))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let ee=kc(e,o,r);C.appendChild(ee)}if(!c||e.role==="system")return C;let Z=m("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),de=Hb(p,e.role);return b==="right"||b==="left"&&e.role==="user"?Z.append(C,de):Z.append(de,C),Z},Bg=(e,t,n,o,r,s)=>{let a=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}):_r(e,t,n,o,r,s)};var $r=new Set,Ob=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Db=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
42
+ `):""},Og=(e,t)=>{let n=$r.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=ne(n?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Lc=(e,t)=>{let n=e.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&$r.has(e.id),i=n.status!=="complete",p=Db(e,r.previewMaxLines??3),d=m("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=m("div","persona-flex persona-flex-col persona-text-left"),u=m("span","persona-text-xs persona-text-persona-primary"),b="Thinking...",g=t?.reasoning??{},y=String(n.startedAt??Date.now()),C=()=>{let he=m("span","");return he.setAttribute("data-tool-elapsed",y),he.textContent=qa(n),he},k=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:b,previewText:p,isActive:i,config:t??{},elapsed:qa(n),createElapsedElement:C});typeof k=="string"&&k.trim()?(u.textContent=k,c.appendChild(u)):k instanceof HTMLElement?c.appendChild(k):(u.textContent=b,c.appendChild(u));let P=m("span","persona-text-xs persona-text-persona-primary");P.textContent=ru(n),c.appendChild(P);let W=r.loadingAnimation??"none",S=g.activeTextTemplate,I=g.completeTextTemplate,j=i?S:I,q=k instanceof HTMLElement,w=(he,Ae)=>{u.textContent="";let Me=Va(he,""),ae=0;for(let me of Me){let Z=me.styles.length>0?(()=>{let de=m("span",me.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return u.appendChild(de),de})():u;if(me.isDuration&&i)Z.appendChild(C());else{let de=me.isDuration?qa(n):me.text;Ae?ae=Ao(Z,de,ae):Z.appendChild(document.createTextNode(de))}}};if(!q&&j)if(P.style.display="none",u.style.display="",i&&W!=="none"){let he=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),W==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),w(j,!1)):(u.classList.add(`persona-tool-loading-${W}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),W==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),w(j,!0))}else w(j,!1);else if(!q&&i&&W!=="none"){u.style.display="";let he=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),W==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`);else{u.classList.add(`persona-tool-loading-${W}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),W==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Ae=u.textContent||b;u.textContent="",Ao(u,Ae,0)}n.status==="complete"&&(u.style.display="none")}else q||(n.status==="complete"?u.style.display="none":u.style.display="");let z=null;if(s){z=m("div","persona-flex persona-items-center");let Ae=ne(a?"chevron-up":"chevron-down",16,"currentColor",2);Ae?z.appendChild(Ae):z.textContent=a?"Hide":"Show";let Me=m("div","persona-flex persona-items-center persona-ml-auto");Me.append(z),d.append(c,Me)}else d.append(c);let V=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(V.setAttribute("data-persona-collapsed-preview","reasoning"),V.style.display="none",V.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&p){let he=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});Ob(V,he)||(V.textContent=p),V.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,V),o;let Y=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Y.style.display=a?"":"none";let D=n.chunks.join(""),N=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return N.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Y.appendChild(N),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),z){z.innerHTML="";let Ae=ne(a?"chevron-up":"chevron-down",16,"currentColor",2);Ae?z.appendChild(Ae):z.textContent=a?"Hide":"Show"}Y.style.display=a?"":"none",V.style.display=a?"none":V.textContent||V.childNodes.length?"":"none"})(),o.append(d,V,Y),o};var jr=new Set,Nb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Fb=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
43
43
  `);let r=ho(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
44
- `):""},Mc=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},Hb=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Wb(e,o?.previewMaxLines??3),a=n?eu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),i&&p.activeTextTemplate?d=Vl(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=Vl(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:i}},Rg=(e,t,n)=>{let o=$r.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=ne(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},kc=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","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),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,i=a&&$r.has(e.id),{summary:p,previewText:d,isActive:c}=Hb(e,t),u=m("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");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let b=m("div","persona-flex persona-flex-col persona-text-left"),g=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let y=String(n.startedAt??Date.now()),C=()=>{let D=m("span","");return D.setAttribute("data-tool-elapsed",y),D.textContent=As(n),D},k=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:As(n),createElapsedElement:C});typeof k=="string"&&k.trim()?(g.textContent=k,b.appendChild(g)):k instanceof HTMLElement?b.appendChild(k):(g.textContent=p,b.appendChild(g));let P=s.loadingAnimation??"none",W=o.activeTextTemplate,S=o.completeTextTemplate,I=c?W:S,j=k instanceof HTMLElement,q=(D,N)=>{g.textContent="";let le=n.name?.trim()||"tool",he=_a(D,le),Ae=0;for(let Me of he){let ae=Me.styles.length>0?(()=>{let me=m("span",Me.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return g.appendChild(me),me})():g;if(Me.isDuration&&c)ae.appendChild(C());else{let me=Me.isDuration?As(n):Me.text;N?Ae=Ao(ae,me,Ae):ae.appendChild(document.createTextNode(me))}}};if(!j)if(c&&P!=="none"){let D=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),P==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${D}ms`),I&&q(I,!1);else if(g.classList.add(`persona-tool-loading-${P}`),g.style.setProperty("--persona-tool-anim-duration",`${D}ms`),P==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),I)q(I,!0);else{let N=g.textContent||p;g.textContent="",Ao(g,N,0)}}else I&&q(I,!1);let w=null;if(a){w=m("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",N=ne(i?"chevron-up":"chevron-down",16,D,2);N?w.appendChild(N):w.textContent=i?"Hide":"Show";let le=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");le.append(w),u.append(b,le)}else u.append(b);let z=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","tool"),z.style.display="none",z.style.whiteSpace="pre-wrap",!i&&c&&s.activePreview&&d){let D=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});Ib(z,D)||(z.textContent=d),z.style.display=""}if(!i&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,z),r;let V=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(V.style.display=i?"":"none",o.contentBackgroundColor&&(V.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(V.style.color=o.contentTextColor),o.contentPaddingX&&(V.style.paddingLeft=o.contentPaddingX,V.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(V.style.paddingTop=o.contentPaddingY,V.style.paddingBottom=o.contentPaddingY),n.name){let D=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?D.style.color=o.contentTextColor:o.headerTextColor&&(D.style.color=o.headerTextColor),D.textContent=n.name,V.appendChild(D)}if(n.args!==void 0){let D=m("div","persona-space-y-1"),N=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(N.style.color=o.labelTextColor),N.textContent="Arguments";let le=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",Mc(le,o),le.textContent=ho(n.args),D.append(N,le),V.appendChild(D)}if(n.chunks&&n.chunks.length){let D=m("div","persona-space-y-1"),N=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(N.style.color=o.labelTextColor),N.textContent="Activity";let le=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",Mc(le,o),le.textContent=n.chunks.join(""),D.append(N,le),V.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=m("div","persona-space-y-1"),N=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(N.style.color=o.labelTextColor),N.textContent="Result";let le=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",Mc(le,o),le.textContent=ho(n.result),D.append(N,le),V.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,V.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),w){w.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",N=ne(i?"chevron-up":"chevron-down",16,D,2);N?w.appendChild(N):w.textContent=i?"Hide":"Show"}V.style.display=i?"":"none",z.style.display=i?"none":z.textContent||z.childNodes.length?"":"none"})(),r.append(u,z,V),r};var nr=new Map,Pi=e=>{let n=(e.startsWith(An)?e.slice(An.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Ig=e=>e?.approval!==!1?e?.approval:void 0,Wg=(e,t)=>{let n=Ig(t)?.detailsDisplay??"collapsed";return nr.get(e)??n==="expanded"},Hg=(e,t,n)=>{let o=Ig(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ne(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Bg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Wg(e,n);Hg(o,s,n),r.style.display=s?"":"none"};var Ri=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=m("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=m("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=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?.titleColor??"currentColor",c=ne(p,20,d,2);c&&i.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),b=m("div","persona-flex persona-items-center persona-gap-2"),g=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",b.appendChild(g),!r){let w=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");w.setAttribute("data-approval-status",n.status),n.status==="approved"?(w.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",w.style.color="var(--persona-palette-colors-success-700, #15803d)",w.textContent="Approved"):n.status==="denied"?(w.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",w.style.color="var(--persona-palette-colors-error-700, #b91c1c)",w.textContent="Denied"):n.status==="timeout"&&(w.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",w.style.color="var(--persona-palette-colors-warning-700, #b45309)",w.textContent="Timeout"),b.appendChild(w)}u.appendChild(b);let C=n.toolType==="webmcp"||n.toolName.startsWith(An)?ys(n.toolName):void 0,k=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),P=!n.toolName,W=k||(P?n.description:`The assistant wants to use \u201C${C??Pi(n.toolName)}\u201D.`),S=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(S.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(S.style.color=o.descriptionColor),S.textContent=W,u.appendChild(S),n.reason){let w=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");w.setAttribute("data-approval-reason","true"),o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let z=m("span","persona-font-medium");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(z),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let I=o?.detailsDisplay??"collapsed",j=!!n.description&&!P,q=j||!!n.parameters;if(I!=="hidden"&&q){let w=Wg(e.id,t),z=m("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");z.type="button",z.setAttribute("data-expand-header","true"),z.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(z.style.color=o.descriptionColor);let V=m("span");V.setAttribute("data-approval-details-label","true");let Y=m("span","persona-inline-flex persona-items-center");Y.setAttribute("data-approval-details-chevron","true"),z.append(V,Y),Hg(z,w,t),u.appendChild(z);let D=m("div");if(D.setAttribute("data-approval-details","true"),D.style.display=w?"":"none",j){let N=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(N.style.color=o.descriptionColor),N.textContent=n.description,D.appendChild(N)}if(n.parameters){let N=m("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(N.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(N.style.color=o.parameterTextColor),N.style.fontSize="0.75rem",N.style.lineHeight="1rem",N.textContent=ho(n.parameters),D.appendChild(N)}u.appendChild(D)}if(r){let w=m("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let z=m("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");z.type="button",z.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",z.style.color=o?.approveButtonTextColor??"#ffffff",z.setAttribute("data-approval-action","approve");let V=ne("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",z.appendChild(V));let Y=document.createTextNode(o?.approveLabel??"Approve");z.appendChild(Y);let D=m("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");D.type="button",D.style.backgroundColor=o?.denyButtonColor??"transparent",D.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",D.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,D.setAttribute("data-approval-action","deny");let N=ne("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);N&&(N.style.marginRight="4px",D.appendChild(N));let le=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(le),w.append(z,D),u.appendChild(w)}return a.append(i,u),s.appendChild(a),s};function Bb(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Og(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:i,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,u=e.container??Bb(t),b=!1,g=null,y=()=>{if(!b)return;let P=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${P.width}px`),a&&(n.style.maxWidth=`${P.width}px`);let W=n.getBoundingClientRect(),S=i?.()??null,I=S!=null?P.top+S:P.top,j=o==="top-start"||o==="top-end"?I-r-W.height:P.bottom+r,w=o==="bottom-end"||o==="top-end"?P.right-W.width:P.left,z=a?.()??null;if(z!=null){let V=Math.max(P.left,P.right-W.width);w=Math.min(Math.max(P.left+z,P.left),V)}n.style.top=`${j}px`,n.style.left=`${w}px`},C=()=>{b&&(b=!1,g&&(g(),g=null),n.remove())},k=()=>{if(b)return;b=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),y();let P=(t.ownerDocument??document).defaultView??window,W=t.ownerDocument??document,S=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}y()},I=q=>{let w=typeof q.composedPath=="function"?q.composedPath():[];w.includes(n)||w.includes(t)||(C(),c?.("outside"))},j=P.setTimeout(()=>{W.addEventListener("pointerdown",I,!0)},0);P.addEventListener("scroll",S,!0),P.addEventListener("resize",S),g=()=>{P.clearTimeout(j),W.removeEventListener("pointerdown",I,!0),P.removeEventListener("scroll",S,!0),P.removeEventListener("resize",S)},d?.()};return{get isOpen(){return b},open:k,close:C,toggle:()=>b?C():k(),reposition:y,destroy:C}}function Dg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Ob=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Ng=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},or=(e,t)=>{Ng(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Db=e=>e?.approval!==!1?e?.approval:void 0,Nb=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return nr.get(e)??n==="expanded"},Lc=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},Fb=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(An)?ys(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??Pi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),i){n.append(" from ");let d=document.createElement("strong");d.textContent=i,n.appendChild(d)}return n},_b=e=>{let t=m("div","persona-approval-resolved"),n=ne("ban",15,"currentColor",2);n&&t.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=e.toolName?Pi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},$b=(e,t,n,o,r,s,a)=>{let i=m("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,b=u&&Nb(t.id,o),g=o?.showDetailsLabel??"Show details",y=o?.hideDetailsLabel??"Hide details",C=m("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",b?"true":"false"),C.setAttribute("aria-label",b?y:g)):C.setAttribute("data-static","true");let k=m("span","persona-approval-logo"),P=ne("shield-check",16,"currentColor",2);P&&k.appendChild(P),C.appendChild(k);let W=Fb(n,o);if(u){let z=m("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let V=ne("chevron-down",14,"currentColor",2);V&&z.appendChild(V),W.append(" "),W.appendChild(z)}C.appendChild(W),i.appendChild(C);let S=m("div","persona-approval-body");if(u){let z=m("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!b,d){let V=m("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,z.appendChild(V)}if(c){let V=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(V.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.textContent=ho(n.parameters),z.appendChild(V)}S.appendChild(z)}if(n.reason){let z=m("p","persona-approval-reason");o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let V=m("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.append(V,document.createTextNode(n.reason)),S.appendChild(z)}let I=m("div","persona-approval-actions"),j=null,q=z=>{o?.approveButtonColor&&(z.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(z.style.color=o.approveButtonTextColor)},w=m("button","persona-approval-deny");if(w.type="button",w.setAttribute("data-action","deny"),o?.denyButtonColor&&(w.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(w.style.color=o.denyButtonTextColor),w.append(o?.denyLabel??"Deny"),a){let z=m("div","persona-approval-split"),V=m("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),q(V),V.append(o?.approveLabel??"Always allow",Lc("\u23CE"));let Y=m("button","persona-approval-caret");Y.type="button",Y.setAttribute("data-action","toggle-menu"),Y.setAttribute("aria-label","More options"),q(Y);let D=ne("chevron-down",15,"currentColor",2);D&&Y.appendChild(D),z.append(V,Y),I.append(z,w),w.append(Lc("Esc"));let N=m("div","persona-approval-menu"),le=m("button","persona-approval-menu-item");le.type="button",le.append("Allow once",Lc("\u2318\u23CE")),N.appendChild(le),j=Og({anchor:z,content:N,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,j),le.addEventListener("click",()=>{or(e,t.id),r()})}else{let z=m("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),q(z),z.append(o?.approveLabel??"Allow"),I.append(z,w)}return S.appendChild(I),i.appendChild(S),i.addEventListener("click",z=>{let V=z.target instanceof Element?z.target.closest("[data-action]"):null;if(!V)return;let Y=V.getAttribute("data-action");if(Y==="toggle-params"){let D=i.querySelector('[data-role="params"]');if(D){let N=D.hidden;D.hidden=!N,C.setAttribute("aria-expanded",N?"true":"false"),C.setAttribute("aria-label",N?y:g),nr.set(t.id,N)}return}if(Y==="toggle-menu"){j?.toggle();return}if(Y==="always"){or(e,t.id),r({remember:!0});return}if(Y==="allow"){or(e,t.id),r();return}if(Y==="deny"){or(e,t.id),s();return}}),i},Fg=()=>{let e=Ob();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let i=o?.approval;if(!i)return null;let p=Db(a);if(i.status!=="pending"){if(or(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return _b(i)}Ng(e,o.id);let d=p?.enableAlwaysAllow===!0,c=$b(e,o,i,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=b=>{Dg(b)||o.id===e.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),or(e,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])or(e,o);e.latestPendingApprovalId=null}}};var _g=e=>{let t=[],n=null;return{buttons:t,render:(r,s,a,i,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(i??(s?s.getMessages():[])).some(k=>k.role==="user"))return;let u=document.createDocumentFragment(),b=s?s.isStreaming():!1,g=y=>{switch(y){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(r.forEach(y=>{let C=m("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=y,C.disabled=b,p?.fontFamily&&(C.style.fontFamily=g(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:y},bubbles:!0,composed:!0})),s.sendMessage(y))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let y=JSON.stringify(r);y!==n&&(n=y,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var js=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){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),this.store?.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 o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,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(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Us=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 o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}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(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var jb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ub=new Set(["step_start","execution_start"]),zb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),qb=new Set(["step_complete","agent_turn_complete"]),Vb=new Set(["flow_complete","agent_complete"]),$g=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ug=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),an=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,rr=(e,t)=>{let n=e[t];return Ug(n)?n:void 0};function Pc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ii(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Kb(e,t){return typeof t.type=="string"?t.type:e}function Gb(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 Jb(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 jg(e){let t=rr(e,"result"),n=[rr(e,"tokens"),rr(e,"totalTokens"),t?rr(t,"tokens"):void 0,rr(e,"usage"),t?rr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=an(o.output)??an(o.outputTokens)??an(o.completionTokens);if(r!==void 0)return r}return an(e.outputTokens)??an(e.completionTokens)??(t?an(t.outputTokens)??an(t.completionTokens):void 0)}function Xb(e){let t=rr(e,"result");return an(e.executionTime)??an(e.executionTimeMs)??an(e.execution_time)??an(e.duration)??(t?an(t.executionTime)??an(t.executionTimeMs):void 0)}function Qb(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var zs=class{constructor(t=Qb){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:Ii(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){if(!Ug(n)){$g.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Kb(t,n),r=this.now();if(jb.has(o)){this.startRun(r);return}if(Ub.has(o)){this.run||this.startRun(r);return}if(zb.has(o)){if(!Jb(o,n))return;let s=Gb(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let i=a.exactOutputTokens+Pc(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ii(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(qb.has(o)){if(!this.run)return;let s=this.run,a=jg(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let i=s.exactOutputTokens>0,p=s.exactOutputTokens+Pc(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Ii(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(Vb.has(o)){if(!this.run)return;let s=this.run,a=jg(n),i=a??s.exactOutputTokens+Pc(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Ii(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if($g.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Xb(n)??o-t.startedAt}};function jr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Yb={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)"}},Zb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ev=["flowName","stepName","reasoningText","text","name","tool","toolName"],tv=100;function nv(e,t){let n={...Yb,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Zb}function ov(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function rv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function sv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function av(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function iv(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 lv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function cv(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 dv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=m("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=m("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,i.appendChild(p),i}}function Rc(e,t,n,o,r,s,a,i){let p=r.has(e.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");jr(d,o.classNames?.eventRow);let c=a.find(b=>b.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let b=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(b)return d.appendChild(b),d}return d.appendChild(u()),d;function u(){let b=m("div",""),g=m("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");g.setAttribute("data-event-id",e.id);let y=m("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ne(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&y.appendChild(C);let k=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),P=o.timestampFormat??"relative";k.textContent=P==="relative"?ov(e.timestamp,n):rv(e.timestamp);let W=null;o.showSequenceNumbers!==!1&&(W=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),W.textContent=String(t+1));let S=nv(e.type,o.badgeColors),I=m("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");I.style.backgroundColor=S.bg,I.style.color=S.text,I.style.borderColor=S.text+"50",I.textContent=e.type;let j=o.descriptionFields??ev,q=sv(e.payload,j),w=null;q&&(w=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=q);let z=m("div","persona-flex-1 persona-min-w-0"),V=m("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"),Y=ne("clipboard","12px","currentColor",1.5);return Y&&V.appendChild(Y),V.addEventListener("click",async D=>{D.stopPropagation(),await av(iv(e)),V.innerHTML="";let N=ne("check","12px","currentColor",1.5);N&&V.appendChild(N),setTimeout(()=>{V.innerHTML="";let le=ne("clipboard","12px","currentColor",1.5);le&&V.appendChild(le)},1500)}),g.appendChild(y),g.appendChild(k),W&&g.appendChild(W),g.appendChild(I),w&&g.appendChild(w),g.appendChild(z),g.appendChild(V),b.appendChild(g),p&&b.appendChild(dv(e,a,i)),b}}function zg(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=r?.features?.scrollToBottom,p=i?.enabled!==!1,d=i?.iconName??"arrow-down",c=i?.label??"",u=r?.features?.eventStream??{},b=s.find(y=>y.renderEventStreamView);if(b?.renderEventStreamView&&r){let y=b.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(y)return{element:y,update:()=>{},destroy:()=>{}}}return g();function g(){let y=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");jr(C,y?.panel);let k=[],P="",W="",S=null,I=[],j={},q=0,w=fi(),z=0,V=0,Y=!1,D=null,N=!1,le=0,he=new Set,Ae=new Map,Me="",ae="",me=null,Z,de,ee,ve,ye=null,pe=null,ke=null;function Ne(){let O=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),U=m("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(jr(U,y?.headerBar),a){pe=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),pe.style.cursor="help",ye=m("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"),ye.textContent="-- tok/s",ke=m("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"),ke.style.display="none",ke.style.pointerEvents="none";let Ze=pe,Po=ke,Ro=()=>{if(!Po.textContent)return;let Zs=Ze.getBoundingClientRect(),Xt=O.getBoundingClientRect();Po.style.left=`${Zs.left-Xt.left}px`,Po.style.top=`${Zs.bottom-Xt.top+4}px`,Po.style.display="block"},Qi=()=>{Po.style.display="none"};pe.addEventListener("mouseenter",Ro),pe.addEventListener("mouseleave",Qi),pe.appendChild(ye)}let ie=m("div","persona-flex-1");Z=m("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 Je=m("option","");Je.value="",Je.textContent="All events (0)",Z.appendChild(Je),de=m("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),de.type="button",de.title="Copy All";let st=ne("clipboard-copy","12px","currentColor",1.5);st&&de.appendChild(st);let G=m("span","persona-event-copy-all persona-text-xs");G.textContent="Copy All",de.appendChild(G),pe&&U.appendChild(pe),U.appendChild(ie),U.appendChild(Z),U.appendChild(de);let qe=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");jr(qe,y?.searchBar);let Se=ne("search","14px","var(--persona-muted, #9ca3af)",1.5),He=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Se&&He.appendChild(Se),ee=m("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"),jr(ee,y?.searchInput),ee.type="text",ee.placeholder="Search event payloads...",ve=m("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"),ve.type="button",ve.style.display="none";let Re=ne("x","12px","currentColor",2);return Re&&ve.appendChild(Re),qe.appendChild(He),qe.appendChild(ee),qe.appendChild(ve),O.appendChild(U),O.appendChild(qe),ke&&O.appendChild(ke),O}let $e,Be=s.find(O=>O.renderEventStreamToolbar);Be?.renderEventStreamToolbar&&r?$e=Be.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ne(),eventCount:t.getSize(),filteredCount:0,onFilterChange:U=>{P=U,Pe(),xe()},onSearchChange:U=>{W=U,Pe(),xe()}})??Ne():$e=Ne();let ze=m("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");ze.style.display="none";function Ke(){if(!a||!ye||!pe)return;let O=a(),U=lv(O);ye.textContent=U;let ie=cv(O);ke&&(ke.textContent=ie,ie||(ke.style.display="none")),pe.setAttribute("aria-label",ie?`Throughput: ${U}, ${ie}`:`Throughput: ${U}`)}let Le=m("div","persona-flex-1 persona-min-h-0 persona-relative"),oe=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");oe.style.height="100%";let Oe=m("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");jr(Oe,y?.scrollIndicator),Oe.style.display="none",Oe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let xt=ne(d,"14px","currentColor",2);xt&&Oe.appendChild(xt);let ht=m("span","");ht.textContent=c,Oe.appendChild(ht);let lt=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");lt.style.display="none",Le.appendChild(oe),Le.appendChild(lt),Le.appendChild(Oe),C.setAttribute("tabindex","0"),C.appendChild($e),C.appendChild(ze),C.appendChild(Le);function De(){let O=t.getAll(),U={};for(let qe of O)U[qe.type]=(U[qe.type]||0)+1;let ie=Object.keys(U).sort(),Je=ie.length!==I.length||!ie.every((qe,Se)=>qe===I[Se]),Ee=!Je&&ie.some(qe=>U[qe]!==j[qe]),st=O.length!==Object.values(j).reduce((qe,Se)=>qe+Se,0);if(!Je&&!Ee&&!st||(I=ie,j=U,!Z))return;let G=Z.value;if(Z.options[0].textContent=`All events (${O.length})`,Je){for(;Z.options.length>1;)Z.remove(1);for(let qe of ie){let Se=m("option","");Se.value=qe,Se.textContent=`${qe} (${U[qe]||0})`,Z.appendChild(Se)}G&&ie.includes(G)?Z.value=G:G&&(Z.value="",P="")}else for(let qe=1;qe<Z.options.length;qe++){let Se=Z.options[qe];Se.textContent=`${Se.value} (${U[Se.value]||0})`}}function be(){let O=t.getAll();if(P&&(O=O.filter(U=>U.type===P)),W){let U=W.toLowerCase();O=O.filter(ie=>ie.type.toLowerCase().includes(U)||ie.payload.toLowerCase().includes(U))}return O}function Qe(){return P!==""||W!==""}function Pe(){q=0,z=0,w.resume(),Oe.style.display="none"}function ge(O){he.has(O)?he.delete(O):he.add(O),me=O;let U=oe.scrollTop,ie=w.isFollowing();N=!0,w.pause(),xe(),oe.scrollTop=U,ie&&w.resume(),N=!1}function ce(){return Eo(oe,50)}function xe(){V=Date.now(),Y=!1,Ke(),De();let O=t.getEvictedCount();O>0?(ze.textContent=`${O.toLocaleString()} older events truncated`,ze.style.display=""):ze.style.display="none",k=be();let U=k.length,ie=t.getSize()>0;U===0&&ie&&Qe()?(lt.textContent=W?`No events matching '${W}'`:"No events matching filter",lt.style.display="",oe.style.display="none"):(lt.style.display="none",oe.style.display=""),de&&(de.title=Qe()?`Copy Filtered (${U})`:"Copy All"),p&&!w.isFollowing()&&U>q&&(z+=U-q,ht.textContent=c?`${c}${z>0?` (${z})`:""}`:"",Oe.style.display=""),q=U;let Je=t.getAll(),Ee=Je.length>0?Je[0].timestamp:0,st=new Set(k.map(Se=>Se.id));for(let Se of he)st.has(Se)||he.delete(Se);let G=P!==Me||W!==ae,qe=Ae.size===0&&k.length>0;if(G||qe||k.length===0){oe.innerHTML="",Ae.clear();let Se=document.createDocumentFragment();for(let He=0;He<k.length;He++){let Re=Rc(k[He],He,Ee,u,he,ge,s,r);Ae.set(k[He].id,Re),Se.appendChild(Re)}oe.appendChild(Se),Me=P,ae=W,me=null}else{if(me!==null){let He=Ae.get(me);if(He&&He.parentNode===oe){let Re=k.findIndex(Ze=>Ze.id===me);if(Re>=0){let Ze=Rc(k[Re],Re,Ee,u,he,ge,s,r);oe.insertBefore(Ze,He),He.remove(),Ae.set(me,Ze)}}me=null}let Se=new Set(k.map(He=>He.id));for(let[He,Re]of Ae)Se.has(He)||(Re.remove(),Ae.delete(He));for(let He=0;He<k.length;He++){let Re=k[He];if(!Ae.has(Re.id)){let Ze=Rc(Re,He,Ee,u,he,ge,s,r);Ae.set(Re.id,Ze),oe.appendChild(Ze)}}}w.isFollowing()&&(oe.scrollTop=oe.scrollHeight)}function Ct(){if(Date.now()-V>=tv){D!==null&&(cancelAnimationFrame(D),D=null),xe();return}Y||(Y=!0,D=requestAnimationFrame(()=>{D=null,xe()}))}let Ce=(O,U)=>{if(!de)return;de.innerHTML="";let ie=ne(O,"12px","currentColor",1.5);ie&&de.appendChild(ie);let Je=m("span","persona-text-xs");Je.textContent="Copy All",de.appendChild(Je),setTimeout(()=>{de.innerHTML="";let Ee=ne("clipboard-copy","12px","currentColor",1.5);Ee&&de.appendChild(Ee);let st=m("span","persona-text-xs");st.textContent="Copy All",de.appendChild(st),de.disabled=!1},U)},ue=async()=>{if(de){de.disabled=!0;try{let O;Qe()?O=k:n?(O=await n(),O.length===0&&(O=t.getAll())):O=t.getAll();let U=O.map(ie=>{try{return JSON.parse(ie.payload)}catch{return ie.payload}});await navigator.clipboard.writeText(JSON.stringify(U,null,2)),Ce("check",1500)}catch{Ce("x",1500)}}},mn=()=>{Z&&(P=Z.value,Pe(),xe())},Q=()=>{!ee||!ve||(ve.style.display=ee.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{W=ee.value,Pe(),xe()},150))},M=()=>{!ee||!ve||(ee.value="",W="",ve.style.display="none",S&&clearTimeout(S),Pe(),xe())},_=()=>{if(N)return;let O=oe.scrollTop,{action:U,nextLastScrollTop:ie}=mi({following:w.isFollowing(),currentScrollTop:O,lastScrollTop:le,nearBottom:ce(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});le=ie,U==="resume"?(w.resume(),z=0,Oe.style.display="none"):U==="pause"&&(w.pause(),p&&(ht.textContent=c,Oe.style.display=""))},v=O=>{let U=hi({following:w.isFollowing(),deltaY:O.deltaY,nearBottom:ce(),resumeWhenNearBottom:!0});U==="pause"?(w.pause(),p&&(ht.textContent=c,Oe.style.display="")):U==="resume"&&(w.resume(),z=0,Oe.style.display="none")},E=()=>{p&&(oe.scrollTop=oe.scrollHeight,w.resume(),z=0,Oe.style.display="none")},L=O=>{let U=O.target;if(!U||U.closest("button"))return;let ie=U.closest("[data-event-id]");if(!ie)return;let Je=ie.getAttribute("data-event-id");Je&&ge(Je)},B=O=>{if((O.metaKey||O.ctrlKey)&&O.key==="f"){O.preventDefault(),ee?.focus(),ee?.select();return}O.key==="Escape"&&(ee&&document.activeElement===ee?(M(),ee.blur(),C.focus()):o&&o())};de&&de.addEventListener("click",ue),Z&&Z.addEventListener("change",mn),ee&&ee.addEventListener("input",Q),ve&&ve.addEventListener("click",M),oe.addEventListener("scroll",_),oe.addEventListener("wheel",v,{passive:!0}),oe.addEventListener("click",L),Oe.addEventListener("click",E),C.addEventListener("keydown",B);function K(){S&&clearTimeout(S),D!==null&&(cancelAnimationFrame(D),D=null),Y=!1,Ae.clear(),de&&de.removeEventListener("click",ue),Z&&Z.removeEventListener("change",mn),ee&&ee.removeEventListener("input",Q),ve&&ve.removeEventListener("click",M),oe.removeEventListener("scroll",_),oe.removeEventListener("wheel",v),oe.removeEventListener("click",L),Oe.removeEventListener("click",E),C.removeEventListener("keydown",B)}return{element:C,update:Ct,destroy:K}}}function Wi(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,i=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let b=u;return s.findIndex(g=>g===b||g.contains(b))},d=u=>{let b=p(u.target);if(b<0)return;let g=b;if(u.key===r)g=Math.min(b+1,s.length-1);else if(u.key===o)g=Math.max(b-1,0);else if(u.key==="Home")g=0;else if(u.key==="End")g=s.length-1;else return;u.preventDefault(),g!==b&&t.onSelect(g)},c=u=>{let b=p(u.target);b>=0&&i(s[b])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,b){if(s=u,u.forEach((g,y)=>{g.setAttribute("role","tab");let C=y===b;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||b<0&&y===0?0:-1}),a){let g=(b>=0?u[b]:void 0)??u[0];g&&typeof g.focus=="function"&&(i(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function qg(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=Q=>({start:Q===!1?!1:typeof Q=="object"&&Q?Q.start!==!1:!0,end:Q===!1?!1:typeof Q=="object"&&Q?Q.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),b=typeof document<"u"?m("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{b?.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"),N?.hide()};b&&b.addEventListener("click",()=>{g(),t.onDismiss?.()});let y=m("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");y.setAttribute("data-persona-theme-zone","artifact-pane"),r&&y.classList.add("persona-artifact-pane-document");let C=m("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let k=m("span","persona-text-xs persona-font-medium persona-truncate");k.textContent=s;let P=ct({icon:"x",label:a});P.addEventListener("click",()=>{g(),t.onDismiss?.()});let W="rendered",S=Gn({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:Q=>{W=Q==="source"?"source":"rendered",Ce()}}),I=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),j=n?.documentToolbarShowCopyLabel===!0,q=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,z=!!(q&&w&&w.length>0),V=null,Y,D=null,N=null;if(r&&(j||q)&&!z){if(Y=j?Kn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):ct({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),q){let Q=ne("chevron-down",14,"currentColor",2);Q&&Y.appendChild(Q)}}else r&&z?(V=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Y=j?Kn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):ct({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=ct({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"}}),V.append(Y,D)):r?Y=ct({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Y=ct({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Y.classList.add("persona-hidden"));let le=r?ct({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):ct({icon:"refresh-cw",label:"Refresh"}),he=r?ct({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):ct({icon:"x",label:a}),Ae=ct({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Ae.classList.add("persona-hidden");let Me=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ae=e.features?.artifacts?.toolbarActions??[],me=()=>{let Q=Le.find(E=>E.id===oe)??Le[Le.length-1],M=Q?.id??null,_=Q?.artifactType==="markdown"?Q.markdown??"":"",v=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:_,jsonPayload:v,id:M}},Z=async()=>{let Q=Le.find(M=>M.id===oe)??Le[Le.length-1];try{await navigator.clipboard.writeText(Bs(Q))}catch{}};if(Y.addEventListener("click",async()=>{let Q=n?.onDocumentToolbarCopyMenuSelect;if(Q&&z){let{markdown:M,jsonPayload:_,id:v}=me();try{await Q({actionId:"primary",artifactId:v,markdown:M,jsonPayload:_})}catch{}return}await Z()}),D&&w?.length){let Q=()=>y.closest("[data-persona-root]")??document.body,M=()=>{N=So({items:w.map(_=>({id:_.id,label:_.label})),onSelect:async _=>{let{markdown:v,jsonPayload:E,id:L}=me(),B=n?.onDocumentToolbarCopyMenuSelect;try{B?await B({actionId:_,artifactId:L,markdown:v,jsonPayload:E}):_==="markdown"||_==="md"?await navigator.clipboard.writeText(v):_==="json"||_==="source"?await navigator.clipboard.writeText(E):await navigator.clipboard.writeText(v||E)}catch{}},anchor:V??D,position:"bottom-right",portal:Q()})};y.isConnected?M():requestAnimationFrame(M),D.addEventListener("click",_=>{_.stopPropagation(),N?.toggle()})}le.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Ce()}),he.addEventListener("click",()=>{g(),t.onDismiss?.()});let de=m("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");if(r)C.replaceChildren(),V?I.append(V,le,he):I.append(Y,le,he),I.insertBefore(Me,he),I.insertBefore(Ae,he),C.append(S.element,de,I);else{let Q=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");Q.append(Y,Me,Ae,P),C.appendChild(k),C.appendChild(Q)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let ee=m("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");p&&ee.style.setProperty("--persona-artifact-tab-fade-size",p);let ve=e.features?.artifacts?.renderTabBar,ye=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),pe=Wi(ee,{onSelect:Q=>t.onSelect(Le[Q].id)}),ke=Q=>{let M=Q.scrollWidth-Q.clientWidth,_=M>1,v=Math.abs(Q.scrollLeft);Q.classList.toggle("persona-artifact-tab-fade-start",c&&_&&v>1),Q.classList.toggle("persona-artifact-tab-fade-end",u&&_&&v<M-1)},Ne=0,$e=()=>{if(Ne)return;let Q=()=>{Ne=0,ke(ee)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(Q):setTimeout(Q,0)};ee.addEventListener("scroll",()=>$e(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ke(ee)).observe(ee);let Be=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),ze=()=>{Be.scrollLeft=0},Ke=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(ze):setTimeout(ze,0)};if(i){for(let Q of[ee,ye])Q.style.paddingLeft=i,Q.style.paddingRight=i;Be.style.padding=i}y.appendChild(C),y.appendChild(ee),y.appendChild(ye),y.appendChild(Be);let Le=[],oe=null,Oe=!1,xt=!1,ht=!0,lt=!1,De=null,be="",Qe=null,Pe=!1,ge=Q=>Q.artifactType==="markdown"&&!!Q.file||r?W:"rendered",ce=Q=>{r||(Q&&!Pe?(C.insertBefore(S.element,k),Pe=!0):!Q&&Pe&&(S.element.remove(),Pe=!1))},xe=()=>oe&&Le.find(Q=>Q.id===oe)||Le[Le.length-1],Ct=()=>{let Q=Ws(xe());if(!Q){Me.replaceChildren();return}let M=ae.filter(_=>_.visible===void 0||_.visible(Q)).map(_=>Br(_,{documentChrome:r,onClick:()=>{let v=Ws(xe());if(v)try{Promise.resolve(_.onClick(v)).catch(()=>{})}catch{}}}));Me.replaceChildren(...M)},Ce=()=>{Ct();let Q=r&&Le.length<=1,M=!!ve;if(ee.classList.toggle("persona-hidden",Q||M),ye.classList.toggle("persona-hidden",Q||!M),M&&ve){let E=Le.map(L=>L.id).join("|")+" "+(oe??"");if(E!==be){be=E;let L=ve({records:Le,selectedId:oe,onSelect:t.onSelect});ye.firstElementChild!==L&&ye.replaceChildren(L)}}else{pe.beforeRender(),ee.replaceChildren();let E=[],L=-1;for(let[B,K]of Le.entries()){let O=m("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");O.type="button";let U=K.artifactType==="markdown"?K.file:void 0,ie=U?Rn(U.path):K.title||K.id.slice(0,8),Je=U?.path||K.title||ie;O.textContent=ie,O.title=Je,O.setAttribute("aria-label",Je),K.id===oe&&(O.classList.add("persona-bg-persona-container","persona-border-persona-border"),L=B),O.addEventListener("click",()=>t.onSelect(K.id)),ee.appendChild(O),E.push(O)}if(pe.render(E,L),L>=0&&oe!==De){De=oe;let B=E[L];typeof B.scrollIntoView=="function"&&B.scrollIntoView({block:"nearest",inline:"nearest"})}ke(ee)}let _=oe&&Le.find(E=>E.id===oe)||Le[Le.length-1];if(!_){Be.replaceChildren(),Qe=null,ce(!1);return}let v=_.artifactType==="markdown"?_.file:void 0;if(ce(!!v),r){let E=v?wo(v):_.artifactType==="markdown"?"MD":_.component??"Component",L=(_.title||"Document").trim(),B=v?Rn(v.path):L.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${B} \xB7 ${E}`}else k.textContent=v?Rn(v.path):s;Qe?(Qe.el.parentElement!==Be&&Be.replaceChildren(Qe.el),Qe.update(_)):(Qe=ui(_,{config:e,resolveViewMode:ge}),Be.replaceChildren(Qe.el)),Be.classList.toggle("persona-artifact-content-flush",!!Be.querySelector(".persona-code-pre"))},ue=()=>{let Q=Le.length>0;if(y.classList.toggle("persona-hidden",!Q),b){let v=((typeof y.closest=="function"?y.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;Q&&v&&Oe?(b.classList.remove("persona-hidden"),y.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"))}},mn=()=>{lt=!1,Ce(),ue()};return{element:y,backdrop:b,update(Q){let M=Q.selectedId??Q.artifacts[Q.artifacts.length-1]?.id??null,_=M!==oe;Le=Q.artifacts,oe=M,Le.length>0&&(Oe=!0),lt=!0,ht&&mn(),_&&ze()},setMobileOpen(Q){Oe=Q,!Q&&b?(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open")):ue()},setExpanded(Q){Q!==xt&&(xt=Q,Ke());let M=ne(Q?"minimize":"maximize",16,"currentColor",2);M&&Ae.replaceChildren(M);let _=Q?"Collapse artifacts panel":"Expand artifacts panel";Ae.setAttribute("aria-label",_),Ae.title=_},setExpandToggleVisible(Q){Ae.classList.toggle("persona-hidden",!Q)},setCopyButtonVisible(Q){r||Y.classList.toggle("persona-hidden",!Q)},setCustomActions(Q){ae=Q,Ct()},setTabFade(Q){let M=d(Q);M.start===c&&M.end===u||(c=M.start,u=M.end,ke(ee))},setRenderTabBar(Q){Q!==ve&&(ve=Q,be="",Ce())},setVisible(Q){Q!==ht&&(ht=Q,Q&&lt&&mn())}}}function Jt(e){return e?.features?.artifacts?.enabled===!0}function Vg(e,t){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"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function pv(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")}var Kg=["panel","seamless","detached"];function Ic(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Kg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Wc(e){return!e||!Jt(e)?!1:Ic(e)==="detached"}function qs(e,t){if(!Jt(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"),pv(e),Vg(e,t);return}let n=t.features?.artifacts?.layout,o=Ic(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Vg(e,t)}function Vs(e,t){for(let i of Kg)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=Ic(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function Gg(e,t){return!t||!Jt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function uv(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function gv(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function fv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function mv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Hc(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Jg(e,t,n,o,r,s){let a=uv(r,200),i=mv(t,n,o,200);i=Math.max(a,i);let p=gv(s);return p!==null&&(i=Math.min(i,p)),fv(e,a,i)}var Xg={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"}},Bc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let i=Xg[a]??Xg.init;s.classList.add("persona-form-card","persona-space-y-4");let p=m("div","persona-space-y-1"),d=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,p.appendChild(d),i.description){let y=m("p","persona-text-sm persona-text-persona-muted");y.textContent=i.description,p.appendChild(y)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(y=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${y.name}`;let k=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=y.label,C.appendChild(k);let P=y.type??"text",W;P==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=P),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${y.name}`,W.name=y.name,W.placeholder=y.placeholder??"",y.required&&(W.required=!0),C.appendChild(W),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=m("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=i.submitLabel??"Submit",u.appendChild(b),u.appendChild(g),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async y=>{y.preventDefault();let C=n.formEndpoint??"/form",k=new FormData(c),P={};k.forEach((W,S)=>{P[S]=W}),P.type=a,g.disabled=!0,b.textContent="Submitting\u2026";try{let W=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let S=await W.json();b.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(W){b.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Oc=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Ks=new Oc;var Qg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hv=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),Yg=(e,t,n)=>{if(!Qg(e)||!Qg(t)||hv.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=Yg(e[r],t[r],s)}return o};function Hi(e,t){let n=Yg(e,t,"");return Rr(n)}var Zg=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var yv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},bv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Gs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=yv(e),n=bv(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Dc=e=>typeof e=="string"?e:e==null?"":String(e),sr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Dc(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Dc(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Dc(n.text)}}},ef=e=>Array.isArray(e)?e.map(t=>String(t)):[],Js=e=>{let t=new Set(ef(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ef(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&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((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!i)return null;t.add(s.message.id),o();let p={action:i,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let b=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:b,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var vv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},xv=e=>e.map(t=>({...t,streaming:!1})),Cv=e=>e.map(t=>({...t,status:"complete"})),Bi=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?vv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?xv(n.messages):void 0,artifacts:n.artifacts?Cv(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Ur=require("partial-json");function wv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Av(e,t){if(!wv(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 Oi(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,Ur.parse)(n,Ur.STR|Ur.OBJ),s=Av(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function tf(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Di(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Tn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function nf(){let e=Oi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function of(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 Xs(e){let t=of(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 Ni(e){let t=of(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 o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Sv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fi(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:d=Sv}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,b=document.createElement("div");b.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,g.appendChild(y);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),b.appendChild(g);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let P=[];for(let q=1;q<=5;q++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${q} star${q>1?"s":""}: ${d[q-1]}`),w.title=d[q-1],w.dataset.rating=String(q),w.innerHTML=`
44
+ `):""},Pc=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},_b=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Fb(e,o?.previewMaxLines??3),a=n?su(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),i&&p.activeTextTemplate?d=Jl(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=Jl(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:i}},Dg=(e,t,n)=>{let o=jr.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=ne(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Rc=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","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),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,i=a&&jr.has(e.id),{summary:p,previewText:d,isActive:c}=_b(e,t),u=m("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");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let b=m("div","persona-flex persona-flex-col persona-text-left"),g=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let y=String(n.startedAt??Date.now()),C=()=>{let D=m("span","");return D.setAttribute("data-tool-elapsed",y),D.textContent=Ts(n),D},k=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Ts(n),createElapsedElement:C});typeof k=="string"&&k.trim()?(g.textContent=k,b.appendChild(g)):k instanceof HTMLElement?b.appendChild(k):(g.textContent=p,b.appendChild(g));let P=s.loadingAnimation??"none",W=o.activeTextTemplate,S=o.completeTextTemplate,I=c?W:S,j=k instanceof HTMLElement,q=(D,N)=>{g.textContent="";let ce=n.name?.trim()||"tool",he=Va(D,ce),Ae=0;for(let Me of he){let ae=Me.styles.length>0?(()=>{let me=m("span",Me.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return g.appendChild(me),me})():g;if(Me.isDuration&&c)ae.appendChild(C());else{let me=Me.isDuration?Ts(n):Me.text;N?Ae=Ao(ae,me,Ae):ae.appendChild(document.createTextNode(me))}}};if(!j)if(c&&P!=="none"){let D=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),P==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${D}ms`),I&&q(I,!1);else if(g.classList.add(`persona-tool-loading-${P}`),g.style.setProperty("--persona-tool-anim-duration",`${D}ms`),P==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),I)q(I,!0);else{let N=g.textContent||p;g.textContent="",Ao(g,N,0)}}else I&&q(I,!1);let w=null;if(a){w=m("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",N=ne(i?"chevron-up":"chevron-down",16,D,2);N?w.appendChild(N):w.textContent=i?"Hide":"Show";let ce=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ce.append(w),u.append(b,ce)}else u.append(b);let z=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","tool"),z.style.display="none",z.style.whiteSpace="pre-wrap",!i&&c&&s.activePreview&&d){let D=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});Nb(z,D)||(z.textContent=d),z.style.display=""}if(!i&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,z),r;let V=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(V.style.display=i?"":"none",o.contentBackgroundColor&&(V.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(V.style.color=o.contentTextColor),o.contentPaddingX&&(V.style.paddingLeft=o.contentPaddingX,V.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(V.style.paddingTop=o.contentPaddingY,V.style.paddingBottom=o.contentPaddingY),n.name){let D=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?D.style.color=o.contentTextColor:o.headerTextColor&&(D.style.color=o.headerTextColor),D.textContent=n.name,V.appendChild(D)}if(n.args!==void 0){let D=m("div","persona-space-y-1"),N=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(N.style.color=o.labelTextColor),N.textContent="Arguments";let ce=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",Pc(ce,o),ce.textContent=ho(n.args),D.append(N,ce),V.appendChild(D)}if(n.chunks&&n.chunks.length){let D=m("div","persona-space-y-1"),N=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(N.style.color=o.labelTextColor),N.textContent="Activity";let ce=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",Pc(ce,o),ce.textContent=n.chunks.join(""),D.append(N,ce),V.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=m("div","persona-space-y-1"),N=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(N.style.color=o.labelTextColor),N.textContent="Result";let ce=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",Pc(ce,o),ce.textContent=ho(n.result),D.append(N,ce),V.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,V.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),w){w.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",N=ne(i?"chevron-up":"chevron-down",16,D,2);N?w.appendChild(N):w.textContent=i?"Hide":"Show"}V.style.display=i?"":"none",z.style.display=i?"none":z.textContent||z.childNodes.length?"":"none"})(),r.append(u,z,V),r};var or=new Map,Oi=e=>{let n=(e.startsWith(wn)?e.slice(wn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Ng=e=>e?.approval!==!1?e?.approval:void 0,Fg=(e,t)=>{let n=Ng(t)?.detailsDisplay??"collapsed";return or.get(e)??n==="expanded"},_g=(e,t,n)=>{let o=Ng(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ne(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},$g=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Fg(e,n);_g(o,s,n),r.style.display=s?"":"none"};var Di=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=m("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=m("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=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?.titleColor??"currentColor",c=ne(p,20,d,2);c&&i.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),b=m("div","persona-flex persona-items-center persona-gap-2"),g=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",b.appendChild(g),!r){let w=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");w.setAttribute("data-approval-status",n.status),n.status==="approved"?(w.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",w.style.color="var(--persona-palette-colors-success-700, #15803d)",w.textContent="Approved"):n.status==="denied"?(w.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",w.style.color="var(--persona-palette-colors-error-700, #b91c1c)",w.textContent="Denied"):n.status==="timeout"&&(w.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",w.style.color="var(--persona-palette-colors-warning-700, #b45309)",w.textContent="Timeout"),b.appendChild(w)}u.appendChild(b);let C=n.toolType==="webmcp"||n.toolName.startsWith(wn)?vs(n.toolName):void 0,k=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),P=!n.toolName,W=k||(P?n.description:`The assistant wants to use \u201C${C??Oi(n.toolName)}\u201D.`),S=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(S.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(S.style.color=o.descriptionColor),S.textContent=W,u.appendChild(S),n.reason){let w=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");w.setAttribute("data-approval-reason","true"),o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let z=m("span","persona-font-medium");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(z),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let I=o?.detailsDisplay??"collapsed",j=!!n.description&&!P,q=j||!!n.parameters;if(I!=="hidden"&&q){let w=Fg(e.id,t),z=m("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");z.type="button",z.setAttribute("data-expand-header","true"),z.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(z.style.color=o.descriptionColor);let V=m("span");V.setAttribute("data-approval-details-label","true");let Y=m("span","persona-inline-flex persona-items-center");Y.setAttribute("data-approval-details-chevron","true"),z.append(V,Y),_g(z,w,t),u.appendChild(z);let D=m("div");if(D.setAttribute("data-approval-details","true"),D.style.display=w?"":"none",j){let N=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(N.style.color=o.descriptionColor),N.textContent=n.description,D.appendChild(N)}if(n.parameters){let N=m("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(N.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(N.style.color=o.parameterTextColor),N.style.fontSize="0.75rem",N.style.lineHeight="1rem",N.textContent=ho(n.parameters),D.appendChild(N)}u.appendChild(D)}if(r){let w=m("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let z=m("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");z.type="button",z.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",z.style.color=o?.approveButtonTextColor??"#ffffff",z.setAttribute("data-approval-action","approve");let V=ne("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",z.appendChild(V));let Y=document.createTextNode(o?.approveLabel??"Approve");z.appendChild(Y);let D=m("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");D.type="button",D.style.backgroundColor=o?.denyButtonColor??"transparent",D.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",D.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,D.setAttribute("data-approval-action","deny");let N=ne("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);N&&(N.style.marginRight="4px",D.appendChild(N));let ce=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(ce),w.append(z,D),u.appendChild(w)}return a.append(i,u),s.appendChild(a),s};function $b(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function jg(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:i,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,u=e.container??$b(t),b=!1,g=null,y=()=>{if(!b)return;let P=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${P.width}px`),a&&(n.style.maxWidth=`${P.width}px`);let W=n.getBoundingClientRect(),S=i?.()??null,I=S!=null?P.top+S:P.top,j=o==="top-start"||o==="top-end"?I-r-W.height:P.bottom+r,w=o==="bottom-end"||o==="top-end"?P.right-W.width:P.left,z=a?.()??null;if(z!=null){let V=Math.max(P.left,P.right-W.width);w=Math.min(Math.max(P.left+z,P.left),V)}n.style.top=`${j}px`,n.style.left=`${w}px`},C=()=>{b&&(b=!1,g&&(g(),g=null),n.remove())},k=()=>{if(b)return;b=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),y();let P=(t.ownerDocument??document).defaultView??window,W=t.ownerDocument??document,S=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}y()},I=q=>{let w=typeof q.composedPath=="function"?q.composedPath():[];w.includes(n)||w.includes(t)||(C(),c?.("outside"))},j=P.setTimeout(()=>{W.addEventListener("pointerdown",I,!0)},0);P.addEventListener("scroll",S,!0),P.addEventListener("resize",S),g=()=>{P.clearTimeout(j),W.removeEventListener("pointerdown",I,!0),P.removeEventListener("scroll",S,!0),P.removeEventListener("resize",S)},d?.()};return{get isOpen(){return b},open:k,close:C,toggle:()=>b?C():k(),reposition:y,destroy:C}}function Ug(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var jb=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),zg=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},rr=(e,t)=>{zg(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Ub=e=>e?.approval!==!1?e?.approval:void 0,zb=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return or.get(e)??n==="expanded"},Ic=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},qb=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(wn)?vs(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??Oi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),i){n.append(" from ");let d=document.createElement("strong");d.textContent=i,n.appendChild(d)}return n},Vb=e=>{let t=m("div","persona-approval-resolved"),n=ne("ban",15,"currentColor",2);n&&t.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=e.toolName?Oi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Kb=(e,t,n,o,r,s,a)=>{let i=m("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,b=u&&zb(t.id,o),g=o?.showDetailsLabel??"Show details",y=o?.hideDetailsLabel??"Hide details",C=m("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",b?"true":"false"),C.setAttribute("aria-label",b?y:g)):C.setAttribute("data-static","true");let k=m("span","persona-approval-logo"),P=ne("shield-check",16,"currentColor",2);P&&k.appendChild(P),C.appendChild(k);let W=qb(n,o);if(u){let z=m("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let V=ne("chevron-down",14,"currentColor",2);V&&z.appendChild(V),W.append(" "),W.appendChild(z)}C.appendChild(W),i.appendChild(C);let S=m("div","persona-approval-body");if(u){let z=m("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!b,d){let V=m("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,z.appendChild(V)}if(c){let V=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(V.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.textContent=ho(n.parameters),z.appendChild(V)}S.appendChild(z)}if(n.reason){let z=m("p","persona-approval-reason");o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let V=m("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.append(V,document.createTextNode(n.reason)),S.appendChild(z)}let I=m("div","persona-approval-actions"),j=null,q=z=>{o?.approveButtonColor&&(z.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(z.style.color=o.approveButtonTextColor)},w=m("button","persona-approval-deny");if(w.type="button",w.setAttribute("data-action","deny"),o?.denyButtonColor&&(w.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(w.style.color=o.denyButtonTextColor),w.append(o?.denyLabel??"Deny"),a){let z=m("div","persona-approval-split"),V=m("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),q(V),V.append(o?.approveLabel??"Always allow",Ic("\u23CE"));let Y=m("button","persona-approval-caret");Y.type="button",Y.setAttribute("data-action","toggle-menu"),Y.setAttribute("aria-label","More options"),q(Y);let D=ne("chevron-down",15,"currentColor",2);D&&Y.appendChild(D),z.append(V,Y),I.append(z,w),w.append(Ic("Esc"));let N=m("div","persona-approval-menu"),ce=m("button","persona-approval-menu-item");ce.type="button",ce.append("Allow once",Ic("\u2318\u23CE")),N.appendChild(ce),j=jg({anchor:z,content:N,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,j),ce.addEventListener("click",()=>{rr(e,t.id),r()})}else{let z=m("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),q(z),z.append(o?.approveLabel??"Allow"),I.append(z,w)}return S.appendChild(I),i.appendChild(S),i.addEventListener("click",z=>{let V=z.target instanceof Element?z.target.closest("[data-action]"):null;if(!V)return;let Y=V.getAttribute("data-action");if(Y==="toggle-params"){let D=i.querySelector('[data-role="params"]');if(D){let N=D.hidden;D.hidden=!N,C.setAttribute("aria-expanded",N?"true":"false"),C.setAttribute("aria-label",N?y:g),or.set(t.id,N)}return}if(Y==="toggle-menu"){j?.toggle();return}if(Y==="always"){rr(e,t.id),r({remember:!0});return}if(Y==="allow"){rr(e,t.id),r();return}if(Y==="deny"){rr(e,t.id),s();return}}),i},qg=()=>{let e=jb();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let i=o?.approval;if(!i)return null;let p=Ub(a);if(i.status!=="pending"){if(rr(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Vb(i)}zg(e,o.id);let d=p?.enableAlwaysAllow===!0,c=Kb(e,o,i,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=b=>{Ug(b)||o.id===e.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),rr(e,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])rr(e,o);e.latestPendingApprovalId=null}}};var Vg=e=>{let t=[],n=null;return{buttons:t,render:(r,s,a,i,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(i??(s?s.getMessages():[])).some(k=>k.role==="user"))return;let u=document.createDocumentFragment(),b=s?s.isStreaming():!1,g=y=>{switch(y){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(r.forEach(y=>{let C=m("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=y,C.disabled=b,p?.fontFamily&&(C.style.fontFamily=g(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:y},bubbles:!0,composed:!0})),s.sendMessage(y))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let y=JSON.stringify(r);y!==n&&(n=y,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var zs=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){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),this.store?.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 o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,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(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var qs=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 o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}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(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var Gb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Jb=new Set(["step_start","execution_start"]),Xb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Qb=new Set(["step_complete","agent_turn_complete"]),Yb=new Set(["flow_complete","agent_complete"]),Kg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Jg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),an=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,sr=(e,t)=>{let n=e[t];return Jg(n)?n:void 0};function Wc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ni(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Zb(e,t){return typeof t.type=="string"?t.type:e}function ev(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function tv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Gg(e){let t=sr(e,"result"),n=[sr(e,"tokens"),sr(e,"totalTokens"),t?sr(t,"tokens"):void 0,sr(e,"usage"),t?sr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=an(o.output)??an(o.outputTokens)??an(o.completionTokens);if(r!==void 0)return r}return an(e.outputTokens)??an(e.completionTokens)??(t?an(t.outputTokens)??an(t.completionTokens):void 0)}function nv(e){let t=sr(e,"result");return an(e.executionTime)??an(e.executionTimeMs)??an(e.execution_time)??an(e.duration)??(t?an(t.executionTime)??an(t.executionTimeMs):void 0)}function ov(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Vs=class{constructor(t=ov){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:Ni(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){if(!Jg(n)){Kg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Zb(t,n),r=this.now();if(Gb.has(o)){this.startRun(r);return}if(Jb.has(o)){this.run||this.startRun(r);return}if(Xb.has(o)){if(!tv(o,n))return;let s=ev(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let i=a.exactOutputTokens+Wc(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ni(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Qb.has(o)){if(!this.run)return;let s=this.run,a=Gg(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let i=s.exactOutputTokens>0,p=s.exactOutputTokens+Wc(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Ni(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(Yb.has(o)){if(!this.run)return;let s=this.run,a=Gg(n),i=a??s.exactOutputTokens+Wc(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Ni(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if(Kg.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:nv(n)??o-t.startedAt}};function Ur(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var rv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},sv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},av=["flowName","stepName","reasoningText","text","name","tool","toolName"],iv=100;function lv(e,t){let n={...rv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return sv}function cv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function dv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function pv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function uv(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function gv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function fv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function mv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function hv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=m("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=m("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,i.appendChild(p),i}}function Hc(e,t,n,o,r,s,a,i){let p=r.has(e.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");Ur(d,o.classNames?.eventRow);let c=a.find(b=>b.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let b=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(b)return d.appendChild(b),d}return d.appendChild(u()),d;function u(){let b=m("div",""),g=m("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");g.setAttribute("data-event-id",e.id);let y=m("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ne(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&y.appendChild(C);let k=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),P=o.timestampFormat??"relative";k.textContent=P==="relative"?cv(e.timestamp,n):dv(e.timestamp);let W=null;o.showSequenceNumbers!==!1&&(W=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),W.textContent=String(t+1));let S=lv(e.type,o.badgeColors),I=m("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");I.style.backgroundColor=S.bg,I.style.color=S.text,I.style.borderColor=S.text+"50",I.textContent=e.type;let j=o.descriptionFields??av,q=pv(e.payload,j),w=null;q&&(w=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=q);let z=m("div","persona-flex-1 persona-min-w-0"),V=m("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"),Y=ne("clipboard","12px","currentColor",1.5);return Y&&V.appendChild(Y),V.addEventListener("click",async D=>{D.stopPropagation(),await uv(gv(e)),V.innerHTML="";let N=ne("check","12px","currentColor",1.5);N&&V.appendChild(N),setTimeout(()=>{V.innerHTML="";let ce=ne("clipboard","12px","currentColor",1.5);ce&&V.appendChild(ce)},1500)}),g.appendChild(y),g.appendChild(k),W&&g.appendChild(W),g.appendChild(I),w&&g.appendChild(w),g.appendChild(z),g.appendChild(V),b.appendChild(g),p&&b.appendChild(hv(e,a,i)),b}}function Xg(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=r?.features?.scrollToBottom,p=i?.enabled!==!1,d=i?.iconName??"arrow-down",c=i?.label??"",u=r?.features?.eventStream??{},b=s.find(y=>y.renderEventStreamView);if(b?.renderEventStreamView&&r){let y=b.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(y)return{element:y,update:()=>{},destroy:()=>{}}}return g();function g(){let y=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ur(C,y?.panel);let k=[],P="",W="",S=null,I=[],j={},q=0,w=xi(),z=0,V=0,Y=!1,D=null,N=!1,ce=0,he=new Set,Ae=new Map,Me="",ae="",me=null,Z,de,ee,ve,ye=null,pe=null,ke=null;function Ne(){let O=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),U=m("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Ur(U,y?.headerBar),a){pe=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),pe.style.cursor="help",ye=m("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"),ye.textContent="-- tok/s",ke=m("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"),ke.style.display="none",ke.style.pointerEvents="none";let Ze=pe,Po=ke,Ro=()=>{if(!Po.textContent)return;let ta=Ze.getBoundingClientRect(),qt=O.getBoundingClientRect();Po.style.left=`${ta.left-qt.left}px`,Po.style.top=`${ta.bottom-qt.top+4}px`,Po.style.display="block"},ol=()=>{Po.style.display="none"};pe.addEventListener("mouseenter",Ro),pe.addEventListener("mouseleave",ol),pe.appendChild(ye)}let ie=m("div","persona-flex-1");Z=m("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 Je=m("option","");Je.value="",Je.textContent="All events (0)",Z.appendChild(Je),de=m("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),de.type="button",de.title="Copy All";let st=ne("clipboard-copy","12px","currentColor",1.5);st&&de.appendChild(st);let G=m("span","persona-event-copy-all persona-text-xs");G.textContent="Copy All",de.appendChild(G),pe&&U.appendChild(pe),U.appendChild(ie),U.appendChild(Z),U.appendChild(de);let qe=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ur(qe,y?.searchBar);let Se=ne("search","14px","var(--persona-muted, #9ca3af)",1.5),He=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Se&&He.appendChild(Se),ee=m("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"),Ur(ee,y?.searchInput),ee.type="text",ee.placeholder="Search event payloads...",ve=m("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"),ve.type="button",ve.style.display="none";let Re=ne("x","12px","currentColor",2);return Re&&ve.appendChild(Re),qe.appendChild(He),qe.appendChild(ee),qe.appendChild(ve),O.appendChild(U),O.appendChild(qe),ke&&O.appendChild(ke),O}let $e,Be=s.find(O=>O.renderEventStreamToolbar);Be?.renderEventStreamToolbar&&r?$e=Be.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ne(),eventCount:t.getSize(),filteredCount:0,onFilterChange:U=>{P=U,Pe(),xe()},onSearchChange:U=>{W=U,Pe(),xe()}})??Ne():$e=Ne();let ze=m("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");ze.style.display="none";function Ke(){if(!a||!ye||!pe)return;let O=a(),U=fv(O);ye.textContent=U;let ie=mv(O);ke&&(ke.textContent=ie,ie||(ke.style.display="none")),pe.setAttribute("aria-label",ie?`Throughput: ${U}, ${ie}`:`Throughput: ${U}`)}let Le=m("div","persona-flex-1 persona-min-h-0 persona-relative"),oe=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");oe.style.height="100%";let Oe=m("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");Ur(Oe,y?.scrollIndicator),Oe.style.display="none",Oe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let xt=ne(d,"14px","currentColor",2);xt&&Oe.appendChild(xt);let ht=m("span","");ht.textContent=c,Oe.appendChild(ht);let lt=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");lt.style.display="none",Le.appendChild(oe),Le.appendChild(lt),Le.appendChild(Oe),C.setAttribute("tabindex","0"),C.appendChild($e),C.appendChild(ze),C.appendChild(Le);function De(){let O=t.getAll(),U={};for(let qe of O)U[qe.type]=(U[qe.type]||0)+1;let ie=Object.keys(U).sort(),Je=ie.length!==I.length||!ie.every((qe,Se)=>qe===I[Se]),Ee=!Je&&ie.some(qe=>U[qe]!==j[qe]),st=O.length!==Object.values(j).reduce((qe,Se)=>qe+Se,0);if(!Je&&!Ee&&!st||(I=ie,j=U,!Z))return;let G=Z.value;if(Z.options[0].textContent=`All events (${O.length})`,Je){for(;Z.options.length>1;)Z.remove(1);for(let qe of ie){let Se=m("option","");Se.value=qe,Se.textContent=`${qe} (${U[qe]||0})`,Z.appendChild(Se)}G&&ie.includes(G)?Z.value=G:G&&(Z.value="",P="")}else for(let qe=1;qe<Z.options.length;qe++){let Se=Z.options[qe];Se.textContent=`${Se.value} (${U[Se.value]||0})`}}function be(){let O=t.getAll();if(P&&(O=O.filter(U=>U.type===P)),W){let U=W.toLowerCase();O=O.filter(ie=>ie.type.toLowerCase().includes(U)||ie.payload.toLowerCase().includes(U))}return O}function Qe(){return P!==""||W!==""}function Pe(){q=0,z=0,w.resume(),Oe.style.display="none"}function ge(O){he.has(O)?he.delete(O):he.add(O),me=O;let U=oe.scrollTop,ie=w.isFollowing();N=!0,w.pause(),xe(),oe.scrollTop=U,ie&&w.resume(),N=!1}function le(){return Eo(oe,50)}function xe(){V=Date.now(),Y=!1,Ke(),De();let O=t.getEvictedCount();O>0?(ze.textContent=`${O.toLocaleString()} older events truncated`,ze.style.display=""):ze.style.display="none",k=be();let U=k.length,ie=t.getSize()>0;U===0&&ie&&Qe()?(lt.textContent=W?`No events matching '${W}'`:"No events matching filter",lt.style.display="",oe.style.display="none"):(lt.style.display="none",oe.style.display=""),de&&(de.title=Qe()?`Copy Filtered (${U})`:"Copy All"),p&&!w.isFollowing()&&U>q&&(z+=U-q,ht.textContent=c?`${c}${z>0?` (${z})`:""}`:"",Oe.style.display=""),q=U;let Je=t.getAll(),Ee=Je.length>0?Je[0].timestamp:0,st=new Set(k.map(Se=>Se.id));for(let Se of he)st.has(Se)||he.delete(Se);let G=P!==Me||W!==ae,qe=Ae.size===0&&k.length>0;if(G||qe||k.length===0){oe.innerHTML="",Ae.clear();let Se=document.createDocumentFragment();for(let He=0;He<k.length;He++){let Re=Hc(k[He],He,Ee,u,he,ge,s,r);Ae.set(k[He].id,Re),Se.appendChild(Re)}oe.appendChild(Se),Me=P,ae=W,me=null}else{if(me!==null){let He=Ae.get(me);if(He&&He.parentNode===oe){let Re=k.findIndex(Ze=>Ze.id===me);if(Re>=0){let Ze=Hc(k[Re],Re,Ee,u,he,ge,s,r);oe.insertBefore(Ze,He),He.remove(),Ae.set(me,Ze)}}me=null}let Se=new Set(k.map(He=>He.id));for(let[He,Re]of Ae)Se.has(He)||(Re.remove(),Ae.delete(He));for(let He=0;He<k.length;He++){let Re=k[He];if(!Ae.has(Re.id)){let Ze=Hc(Re,He,Ee,u,he,ge,s,r);Ae.set(Re.id,Ze),oe.appendChild(Ze)}}}w.isFollowing()&&(oe.scrollTop=oe.scrollHeight)}function Ct(){if(Date.now()-V>=iv){D!==null&&(cancelAnimationFrame(D),D=null),xe();return}Y||(Y=!0,D=requestAnimationFrame(()=>{D=null,xe()}))}let Ce=(O,U)=>{if(!de)return;de.innerHTML="";let ie=ne(O,"12px","currentColor",1.5);ie&&de.appendChild(ie);let Je=m("span","persona-text-xs");Je.textContent="Copy All",de.appendChild(Je),setTimeout(()=>{de.innerHTML="";let Ee=ne("clipboard-copy","12px","currentColor",1.5);Ee&&de.appendChild(Ee);let st=m("span","persona-text-xs");st.textContent="Copy All",de.appendChild(st),de.disabled=!1},U)},ue=async()=>{if(de){de.disabled=!0;try{let O;Qe()?O=k:n?(O=await n(),O.length===0&&(O=t.getAll())):O=t.getAll();let U=O.map(ie=>{try{return JSON.parse(ie.payload)}catch{return ie.payload}});await navigator.clipboard.writeText(JSON.stringify(U,null,2)),Ce("check",1500)}catch{Ce("x",1500)}}},fn=()=>{Z&&(P=Z.value,Pe(),xe())},Q=()=>{!ee||!ve||(ve.style.display=ee.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{W=ee.value,Pe(),xe()},150))},M=()=>{!ee||!ve||(ee.value="",W="",ve.style.display="none",S&&clearTimeout(S),Pe(),xe())},_=()=>{if(N)return;let O=oe.scrollTop,{action:U,nextLastScrollTop:ie}=Ci({following:w.isFollowing(),currentScrollTop:O,lastScrollTop:ce,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ce=ie,U==="resume"?(w.resume(),z=0,Oe.style.display="none"):U==="pause"&&(w.pause(),p&&(ht.textContent=c,Oe.style.display=""))},v=O=>{let U=wi({following:w.isFollowing(),deltaY:O.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});U==="pause"?(w.pause(),p&&(ht.textContent=c,Oe.style.display="")):U==="resume"&&(w.resume(),z=0,Oe.style.display="none")},E=()=>{p&&(oe.scrollTop=oe.scrollHeight,w.resume(),z=0,Oe.style.display="none")},L=O=>{let U=O.target;if(!U||U.closest("button"))return;let ie=U.closest("[data-event-id]");if(!ie)return;let Je=ie.getAttribute("data-event-id");Je&&ge(Je)},B=O=>{if((O.metaKey||O.ctrlKey)&&O.key==="f"){O.preventDefault(),ee?.focus(),ee?.select();return}O.key==="Escape"&&(ee&&document.activeElement===ee?(M(),ee.blur(),C.focus()):o&&o())};de&&de.addEventListener("click",ue),Z&&Z.addEventListener("change",fn),ee&&ee.addEventListener("input",Q),ve&&ve.addEventListener("click",M),oe.addEventListener("scroll",_),oe.addEventListener("wheel",v,{passive:!0}),oe.addEventListener("click",L),Oe.addEventListener("click",E),C.addEventListener("keydown",B);function K(){S&&clearTimeout(S),D!==null&&(cancelAnimationFrame(D),D=null),Y=!1,Ae.clear(),de&&de.removeEventListener("click",ue),Z&&Z.removeEventListener("change",fn),ee&&ee.removeEventListener("input",Q),ve&&ve.removeEventListener("click",M),oe.removeEventListener("scroll",_),oe.removeEventListener("wheel",v),oe.removeEventListener("click",L),Oe.removeEventListener("click",E),C.removeEventListener("keydown",B)}return{element:C,update:Ct,destroy:K}}}function Fi(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,i=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let b=u;return s.findIndex(g=>g===b||g.contains(b))},d=u=>{let b=p(u.target);if(b<0)return;let g=b;if(u.key===r)g=Math.min(b+1,s.length-1);else if(u.key===o)g=Math.max(b-1,0);else if(u.key==="Home")g=0;else if(u.key==="End")g=s.length-1;else return;u.preventDefault(),g!==b&&t.onSelect(g)},c=u=>{let b=p(u.target);b>=0&&i(s[b])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,b){if(s=u,u.forEach((g,y)=>{g.setAttribute("role","tab");let C=y===b;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||b<0&&y===0?0:-1}),a){let g=(b>=0?u[b]:void 0)??u[0];g&&typeof g.focus=="function"&&(i(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Qg(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=Q=>({start:Q===!1?!1:typeof Q=="object"&&Q?Q.start!==!1:!0,end:Q===!1?!1:typeof Q=="object"&&Q?Q.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),b=typeof document<"u"?m("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{b?.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"),N?.hide()};b&&b.addEventListener("click",()=>{g(),t.onDismiss?.()});let y=m("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");y.setAttribute("data-persona-theme-zone","artifact-pane"),r&&y.classList.add("persona-artifact-pane-document");let C=m("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let k=m("span","persona-text-xs persona-font-medium persona-truncate");k.textContent=s;let P=ct({icon:"x",label:a});P.addEventListener("click",()=>{g(),t.onDismiss?.()});let W="rendered",S=Gn({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:Q=>{W=Q==="source"?"source":"rendered",Ce()}}),I=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),j=n?.documentToolbarShowCopyLabel===!0,q=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,z=!!(q&&w&&w.length>0),V=null,Y,D=null,N=null;if(r&&(j||q)&&!z){if(Y=j?Kn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):ct({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),q){let Q=ne("chevron-down",14,"currentColor",2);Q&&Y.appendChild(Q)}}else r&&z?(V=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Y=j?Kn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):ct({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=ct({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"}}),V.append(Y,D)):r?Y=ct({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Y=ct({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Y.classList.add("persona-hidden"));let ce=r?ct({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):ct({icon:"refresh-cw",label:"Refresh"}),he=r?ct({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):ct({icon:"x",label:a}),Ae=ct({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Ae.classList.add("persona-hidden");let Me=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ae=e.features?.artifacts?.toolbarActions??[],me=()=>{let Q=Le.find(E=>E.id===oe)??Le[Le.length-1],M=Q?.id??null,_=Q?.artifactType==="markdown"?Q.markdown??"":"",v=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:_,jsonPayload:v,id:M}},Z=async()=>{let Q=Le.find(M=>M.id===oe)??Le[Le.length-1];try{await navigator.clipboard.writeText(Ds(Q))}catch{}};if(Y.addEventListener("click",async()=>{let Q=n?.onDocumentToolbarCopyMenuSelect;if(Q&&z){let{markdown:M,jsonPayload:_,id:v}=me();try{await Q({actionId:"primary",artifactId:v,markdown:M,jsonPayload:_})}catch{}return}await Z()}),D&&w?.length){let Q=()=>y.closest("[data-persona-root]")??document.body,M=()=>{N=So({items:w.map(_=>({id:_.id,label:_.label})),onSelect:async _=>{let{markdown:v,jsonPayload:E,id:L}=me(),B=n?.onDocumentToolbarCopyMenuSelect;try{B?await B({actionId:_,artifactId:L,markdown:v,jsonPayload:E}):_==="markdown"||_==="md"?await navigator.clipboard.writeText(v):_==="json"||_==="source"?await navigator.clipboard.writeText(E):await navigator.clipboard.writeText(v||E)}catch{}},anchor:V??D,position:"bottom-right",portal:Q()})};y.isConnected?M():requestAnimationFrame(M),D.addEventListener("click",_=>{_.stopPropagation(),N?.toggle()})}ce.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Ce()}),he.addEventListener("click",()=>{g(),t.onDismiss?.()});let de=m("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");if(r)C.replaceChildren(),V?I.append(V,ce,he):I.append(Y,ce,he),I.insertBefore(Me,he),I.insertBefore(Ae,he),C.append(S.element,de,I);else{let Q=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");Q.append(Y,Me,Ae,P),C.appendChild(k),C.appendChild(Q)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let ee=m("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");p&&ee.style.setProperty("--persona-artifact-tab-fade-size",p);let ve=e.features?.artifacts?.renderTabBar,ye=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),pe=Fi(ee,{onSelect:Q=>t.onSelect(Le[Q].id)}),ke=Q=>{let M=Q.scrollWidth-Q.clientWidth,_=M>1,v=Math.abs(Q.scrollLeft);Q.classList.toggle("persona-artifact-tab-fade-start",c&&_&&v>1),Q.classList.toggle("persona-artifact-tab-fade-end",u&&_&&v<M-1)},Ne=0,$e=()=>{if(Ne)return;let Q=()=>{Ne=0,ke(ee)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(Q):setTimeout(Q,0)};ee.addEventListener("scroll",()=>$e(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ke(ee)).observe(ee);let Be=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),ze=()=>{Be.scrollLeft=0},Ke=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(ze):setTimeout(ze,0)};if(i){for(let Q of[ee,ye])Q.style.paddingLeft=i,Q.style.paddingRight=i;Be.style.padding=i}y.appendChild(C),y.appendChild(ee),y.appendChild(ye),y.appendChild(Be);let Le=[],oe=null,Oe=!1,xt=!1,ht=!0,lt=!1,De=null,be="",Qe=null,Pe=!1,ge=Q=>Q.artifactType==="markdown"&&!!Q.file||r?W:"rendered",le=Q=>{r||(Q&&!Pe?(C.insertBefore(S.element,k),Pe=!0):!Q&&Pe&&(S.element.remove(),Pe=!1))},xe=()=>oe&&Le.find(Q=>Q.id===oe)||Le[Le.length-1],Ct=()=>{let Q=Bs(xe());if(!Q){Me.replaceChildren();return}let M=ae.filter(_=>_.visible===void 0||_.visible(Q)).map(_=>Or(_,{documentChrome:r,onClick:()=>{let v=Bs(xe());if(v)try{Promise.resolve(_.onClick(v)).catch(()=>{})}catch{}}}));Me.replaceChildren(...M)},Ce=()=>{Ct();let Q=r&&Le.length<=1,M=!!ve;if(ee.classList.toggle("persona-hidden",Q||M),ye.classList.toggle("persona-hidden",Q||!M),M&&ve){let E=Le.map(L=>L.id).join("|")+" "+(oe??"");if(E!==be){be=E;let L=ve({records:Le,selectedId:oe,onSelect:t.onSelect});ye.firstElementChild!==L&&ye.replaceChildren(L)}}else{pe.beforeRender(),ee.replaceChildren();let E=[],L=-1;for(let[B,K]of Le.entries()){let O=m("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");O.type="button";let U=K.artifactType==="markdown"?K.file:void 0,ie=U?Pn(U.path):K.title||K.id.slice(0,8),Je=U?.path||K.title||ie;O.textContent=ie,O.title=Je,O.setAttribute("aria-label",Je),K.id===oe&&(O.classList.add("persona-bg-persona-container","persona-border-persona-border"),L=B),O.addEventListener("click",()=>t.onSelect(K.id)),ee.appendChild(O),E.push(O)}if(pe.render(E,L),L>=0&&oe!==De){De=oe;let B=E[L];typeof B.scrollIntoView=="function"&&B.scrollIntoView({block:"nearest",inline:"nearest"})}ke(ee)}let _=oe&&Le.find(E=>E.id===oe)||Le[Le.length-1];if(!_){Be.replaceChildren(),Qe=null,le(!1);return}let v=_.artifactType==="markdown"?_.file:void 0;if(le(!!v),r){let E=v?wo(v):_.artifactType==="markdown"?"MD":_.component??"Component",L=(_.title||"Document").trim(),B=v?Pn(v.path):L.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${B} \xB7 ${E}`}else k.textContent=v?Pn(v.path):s;Qe?(Qe.el.parentElement!==Be&&Be.replaceChildren(Qe.el),Qe.update(_)):(Qe=bi(_,{config:e,resolveViewMode:ge}),Be.replaceChildren(Qe.el)),Be.classList.toggle("persona-artifact-content-flush",!!Be.querySelector(".persona-code-pre"))},ue=()=>{let Q=Le.length>0;if(y.classList.toggle("persona-hidden",!Q),b){let v=((typeof y.closest=="function"?y.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;Q&&v&&Oe?(b.classList.remove("persona-hidden"),y.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"))}},fn=()=>{lt=!1,Ce(),ue()};return{element:y,backdrop:b,update(Q){let M=Q.selectedId??Q.artifacts[Q.artifacts.length-1]?.id??null,_=M!==oe;Le=Q.artifacts,oe=M,Le.length>0&&(Oe=!0),lt=!0,ht&&fn(),_&&ze()},setMobileOpen(Q){Oe=Q,!Q&&b?(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open")):ue()},setExpanded(Q){Q!==xt&&(xt=Q,Ke());let M=ne(Q?"minimize":"maximize",16,"currentColor",2);M&&Ae.replaceChildren(M);let _=Q?"Collapse artifacts panel":"Expand artifacts panel";Ae.setAttribute("aria-label",_),Ae.title=_},setExpandToggleVisible(Q){Ae.classList.toggle("persona-hidden",!Q)},setCopyButtonVisible(Q){r||Y.classList.toggle("persona-hidden",!Q)},setCustomActions(Q){ae=Q,Ct()},setTabFade(Q){let M=d(Q);M.start===c&&M.end===u||(c=M.start,u=M.end,ke(ee))},setRenderTabBar(Q){Q!==ve&&(ve=Q,be="",Ce())},setVisible(Q){Q!==ht&&(ht=Q,Q&&lt&&fn())}}}function Xt(e){return e?.features?.artifacts?.enabled===!0}function Yg(e,t){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"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function yv(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")}var Zg=["panel","seamless","detached"];function Bc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Zg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Oc(e){return!e||!Xt(e)?!1:Bc(e)==="detached"}function Ks(e,t){if(!Xt(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"),yv(e),Yg(e,t);return}let n=t.features?.artifacts?.layout,o=Bc(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Yg(e,t)}function Gs(e,t){for(let i of Zg)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=Bc(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function ef(e,t){return!t||!Xt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function bv(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function vv(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function xv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Cv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Dc(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function tf(e,t,n,o,r,s){let a=bv(r,200),i=Cv(t,n,o,200);i=Math.max(a,i);let p=vv(s);return p!==null&&(i=Math.min(i,p)),xv(e,a,i)}var nf={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"}},Nc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let i=nf[a]??nf.init;s.classList.add("persona-form-card","persona-space-y-4");let p=m("div","persona-space-y-1"),d=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,p.appendChild(d),i.description){let y=m("p","persona-text-sm persona-text-persona-muted");y.textContent=i.description,p.appendChild(y)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(y=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${y.name}`;let k=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=y.label,C.appendChild(k);let P=y.type??"text",W;P==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=P),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${y.name}`,W.name=y.name,W.placeholder=y.placeholder??"",y.required&&(W.required=!0),C.appendChild(W),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=m("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=i.submitLabel??"Submit",u.appendChild(b),u.appendChild(g),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async y=>{y.preventDefault();let C=n.formEndpoint??"/form",k=new FormData(c),P={};k.forEach((W,S)=>{P[S]=W}),P.type=a,g.disabled=!0,b.textContent="Submitting\u2026";try{let W=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let S=await W.json();b.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(W){b.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Fc=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Js=new Fc;var of=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wv=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),rf=(e,t,n)=>{if(!of(e)||!of(t)||wv.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=rf(e[r],t[r],s)}return o};function _i(e,t){let n=rf(e,t,"");return Ir(n)}var sf=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var Av=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Sv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Xs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Av(e),n=Sv(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},_c=e=>typeof e=="string"?e:e==null?"":String(e),ar={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:_c(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=_c(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:_c(n.text)}}},af=e=>Array.isArray(e)?e.map(t=>String(t)):[],Qs=e=>{let t=new Set(af(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(af(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&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((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!i)return null;t.add(s.message.id),o();let p={action:i,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let b=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:b,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var Tv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Ev=e=>e.map(t=>({...t,streaming:!1})),Mv=e=>e.map(t=>({...t,status:"complete"})),$i=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Tv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Ev(n.messages):void 0,artifacts:n.artifacts?Mv(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var zr=require("partial-json");function kv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Lv(e,t){if(!kv(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 ji(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,zr.parse)(n,zr.STR|zr.OBJ),s=Lv(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function lf(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ui(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Sn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function cf(){let e=ji();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function df(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 Ys(e){let t=df(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 zi(e){let t=df(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 o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Pv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function qi(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:d=Pv}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,b=document.createElement("div");b.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,g.appendChild(y);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),b.appendChild(g);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let P=[];for(let q=1;q<=5;q++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${q} star${q>1?"s":""}: ${d[q-1]}`),w.title=d[q-1],w.dataset.rating=String(q),w.innerHTML=`
45
45
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
46
46
  <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>
47
47
  </svg>
48
- `,w.addEventListener("click",()=>{u=q,P.forEach((z,V)=>{let Y=V<q;z.classList.toggle("selected",Y),z.setAttribute("aria-checked",V===q-1?"true":"false")})}),P.push(w),k.appendChild(w)}b.appendChild(k);let W=null;if(p){let q=document.createElement("div");q.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),q.appendChild(W),b.appendChild(q)}let S=document.createElement("div");S.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{n?.(),c.remove()});let j=document.createElement("button");return j.type="button",j.className="persona-feedback-btn persona-feedback-btn-submit",j.textContent=a,j.addEventListener("click",async()=>{if(u===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}j.disabled=!0,j.textContent="Submitting...";try{let q=W?.value.trim()||void 0;await t(u,q),c.remove()}catch(q){j.disabled=!1,j.textContent=a,console.error("[CSAT Feedback] Failed to submit:",q)}}),S.appendChild(I),S.appendChild(j),b.appendChild(S),c.appendChild(b),c}function _i(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let b=null,g=document.createElement("div");g.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,y.appendChild(C);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=r,y.appendChild(k),g.appendChild(y);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-nps",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Likelihood rating from 0 to 10");let W=document.createElement("div");W.className="persona-feedback-labels";let S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=d;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=c,W.appendChild(S),W.appendChild(I);let j=document.createElement("div");j.className="persona-feedback-numbers";let q=[];for(let D=0;D<=10;D++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-number-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`Rating ${D} out of 10`),N.textContent=String(D),N.dataset.rating=String(D),D<=6?N.classList.add("persona-feedback-detractor"):D<=8?N.classList.add("persona-feedback-passive"):N.classList.add("persona-feedback-promoter"),N.addEventListener("click",()=>{b=D,q.forEach((le,he)=>{le.classList.toggle("selected",he===D),le.setAttribute("aria-checked",he===D?"true":"false")})}),q.push(N),j.appendChild(N)}P.appendChild(W),P.appendChild(j),g.appendChild(P);let w=null;if(p){let D=document.createElement("div");D.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=s,w.rows=3,w.setAttribute("aria-label","Additional comments"),D.appendChild(w),g.appendChild(D)}let z=document.createElement("div");z.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=i,V.addEventListener("click",()=>{n?.(),u.remove()});let Y=document.createElement("button");return Y.type="button",Y.className="persona-feedback-btn persona-feedback-btn-submit",Y.textContent=a,Y.addEventListener("click",async()=>{if(b===null){j.classList.add("persona-feedback-shake"),setTimeout(()=>j.classList.remove("persona-feedback-shake"),500);return}Y.disabled=!0,Y.textContent="Submitting...";try{let D=w?.value.trim()||void 0;await t(b,D),u.remove()}catch(D){Y.disabled=!1,Y.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),z.appendChild(V),z.appendChild(Y),g.appendChild(z),u.appendChild(g),u}var zr="persona-chat-history",Tv=30*1e3,Ev=641,Mv={"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 kv(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=Mv[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function $i(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 Lv(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function Pv(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Nc=e=>!e||typeof e!="object"?{}:{...e},rf=e=>e.map(t=>({...t,streaming:!1})),sf=(e,t,n)=>{let o=e?.markdown?qo(e.markdown):null,r=Cr(e?.sanitize);return e?.postprocessMessage&&r&&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."),s=>{let a=s.text??"",i=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=$n()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:i??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Mp(a):a,u=o(c);d=r&&p?r(u):u}else d=Pn(a);return d}};function af(e){let t=m("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=ne(n,o,r,s);if(a&&t.appendChild(a),e?.label){let i=m("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var Rv=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},Iv=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:Rv(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),ji=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Rr(t),r=Ks.getForInstance(o.plugins),{plugin:s,teardown:a}=Fg();o.components&&Tn.registerAll(o.components);let i=Zg(),d=o.persistState===!1?null:o.storageAdapter??Bi(),c={},u=null,b=!1,g=l=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(l);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:x}=f;return x&&(b=!0),h}return f}catch(f){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return l};if(d?.load)try{let l=d.load();if(l&&typeof l.then=="function")u=l.then(f=>g(f??{messages:[],metadata:{}}));else{let h=g(l??{messages:[],metadata:{}});h.metadata&&(c=Nc(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=g({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let y=()=>c,C=l=>{c=l({...c})??{},gl()},k=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Gs],P=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[sr.message,sr.messageAndClick],W=Js({parsers:k,handlers:P,getSessionMetadata:y,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null});W.syncFromMetadata();let S=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,j=o.autoFocusInput??!1,q=I,w=S,z=o.layout?.header?.layout,V=!1,Y=()=>ko(o),D=()=>S||Y(),N=Y()?!1:S?I:!0,le=!1,he=null,Ae=()=>{le=!0,he&&clearTimeout(he),he=setTimeout(()=>{le&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),le=!1)},1e4)},Me=sf(o,W,Ae),ae=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,Z=o.features?.showEventStreamToggle??!1,de=o.features?.scrollToBottom??{},ee=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,pe=Z?new Us(ye):null,ke=o.features?.eventStream?.maxEvents??2e3,Ne=Z?new js(ke,pe):null,$e=Z?new zs:null,Be=null,ze=!1,Ke=null,Le=0;pe?.open().then(()=>Ne?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let oe={onCopy:l=>{i.emit("message:copy",l),$?.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",f)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{i.emit("message:feedback",l),$?.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",f)}),o.messageActions?.onFeedback?.(l)}},Oe=o.statusIndicator??{},xt=l=>l==="idle"?Oe.idleText??Ht.idle:l==="connecting"?Oe.connectingText??Ht.connecting:l==="connected"?Oe.connectedText??Ht.connected:l==="error"?Oe.errorText??Ht.error:l==="paused"?Oe.pausedText??Ht.paused:l==="resuming"?Oe.resumingText??Ht.resuming:Ht[l];function ht(l,f,h,x){if(x==="idle"&&h.idleLink){l.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=f,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=f}let lt=Sg({config:o,showClose:D()}),{wrapper:De,panel:be,pillRoot:Qe}=lt.shell,Pe=lt.panelElements,{container:ge,body:ce,messagesWrapper:xe,suggestions:Ct,textarea:Ce,sendButton:ue,sendButtonWrapper:mn,composerForm:Q,statusText:M,introTitle:_,introSubtitle:v,closeButton:E,iconHolder:L,headerTitle:B,headerSubtitle:K,header:O,footer:U,actionsRow:ie,rightActions:Je}=Pe,Ee=Pe.leftActions,st=Pe.setSendButtonMode,G=Pe.micButton,qe=Pe.micButtonWrapper,Se=Pe.attachmentButton,He=Pe.attachmentButtonWrapper,Re=Pe.attachmentInput,Ze=Pe.attachmentPreviewsContainer;ge.classList.add("persona-relative"),ce.classList.add("persona-relative");let Po=12,Ro=()=>de.label??"",Qi=()=>de.iconName??"arrow-down",Zs=()=>de.enabled!==!1,Xt=()=>ee.mode??"anchor-top",Qn=()=>Xt()==="follow"||Xt()==="anchor-top"&&Zr,td=()=>ee.anchorTopOffset??16,Xf=()=>ee.restorePosition??"bottom",nd=()=>ee.pauseOnInteraction===!0,od=()=>ee.showActivityWhilePinned!==!1,rd=()=>ee.announce===!0,Pt=m("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 qr=m("span","persona-flex persona-items-center"),Yi=m("span",""),Io=m("span","");Io.setAttribute("data-persona-scroll-to-bottom-count",""),Io.style.display="none",Pt.append(qr,Yi,Io),ge.appendChild(Pt);let Yn=m("div","persona-stream-anchor-spacer");Yn.setAttribute("aria-hidden","true"),Yn.setAttribute("data-persona-anchor-spacer",""),Yn.style.flexShrink="0",Yn.style.pointerEvents="none",Yn.style.height="0px",ce.appendChild(Yn);let Wo=m("div","persona-sr-only");Wo.setAttribute("aria-live","polite"),Wo.setAttribute("aria-atomic","true"),Wo.setAttribute("role","status"),Wo.setAttribute("data-persona-live-region",""),Object.assign(Wo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ge.appendChild(Wo);let Vr=null,ea=null,sd=l=>{!rd()||!l||(ea=l,Vr===null&&(Vr=setTimeout(()=>{Vr=null,ea&&rd()&&(Wo.textContent=ea),ea=null},400)))},ar=()=>{let f=U.style.display==="none"?0:U.offsetHeight;Pt.style.bottom=`${f+Po}px`};ar();let ad=()=>{let l=!!Ro();Pt.setAttribute("aria-label",Ro()||"Jump to latest"),Pt.title=Ro(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),qr.innerHTML="";let f=ne(Qi(),"14px","currentColor",2);f?(qr.appendChild(f),qr.style.display=""):qr.style.display="none",Yi.textContent=Ro(),Yi.style.display=l?"":"none"};ad();let Tt=null,en=null,id=null,ld=r.find(l=>l.renderHeader);if(ld?.renderHeader){let l=ld.renderHeader({config:o,defaultRenderer:()=>{let f=Jn({config:o,showClose:D()});return er(ge,f,o),f.header},onClose:()=>ut(!1,"user")});if(l){let f=ge.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),O=l,lt.header.element=l)}}let Zi=()=>{if(!Ne)return;if(ze=!0,!Be&&Ne&&(Be=zg({buffer:Ne,getFullHistory:()=>Ne.getAllFromStore(),onClose:()=>Kr(),config:o,plugins:r,getThroughput:()=>$e?.getMetric()??{status:"idle"}})),Be&&(ce.style.display="none",U.parentNode?.insertBefore(Be.element,U),Be.update()),nt){nt.style.boxShadow=`inset 0 0 0 1.5px ${Gt.actionIconColor}`;let f=o.features?.eventStream?.classNames?.toggleButtonActive;f&&f.split(/\s+/).forEach(h=>h&&nt.classList.add(h))}let l=()=>{if(!ze)return;let f=Date.now();f-Le>=200&&(Be?.update(),Le=f),Ke=requestAnimationFrame(l)};Le=0,Ke=requestAnimationFrame(l),nn(),i.emit("eventStream:opened",{timestamp:Date.now()})},Kr=()=>{if(ze){if(ze=!1,Be&&Be.element.remove(),ce.style.display="",nt){nt.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&nt.classList.remove(f))}Ke!==null&&(cancelAnimationFrame(Ke),Ke=null),nn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},nt=null;if(Z){let l=o.features?.eventStream?.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");nt=m("button",f),nt.style.width="28px",nt.style.height="28px",nt.style.color=Gt.actionIconColor,nt.type="button",nt.setAttribute("aria-label","Event Stream"),nt.title="Event Stream";let h=ne("activity","18px","currentColor",1.5);h&&nt.appendChild(h);let x=Pe.clearChatButtonWrapper,A=Pe.closeButtonWrapper,R=x||A;R&&R.parentNode===O?O.insertBefore(nt,R):O.appendChild(nt),nt.addEventListener("click",()=>{ze?Kr():Zi()})}let Qf=l=>{let f=o.attachments;if(!f?.enabled)return;let h=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!h){h=m("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 A=l.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(h,A):l.insertBefore(h,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let A=m("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(f.allowedTypes??Vn).join(","),A.multiple=(f.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",f.buttonTooltipText??"Attach files"),l.appendChild(A)}},cd=r.find(l=>l.renderComposer);if(cd?.renderComposer){let l=o.composer,f=cd.renderComposer({config:o,defaultRenderer:()=>Nr({config:o}).footer,onSubmit:h=>{if(!$||$.isStreaming())return;let x=h.trim(),A=Tt?.hasAttachments()??!1;if(!x&&!A)return;Nd();let R;A&&(R=[],R.push(...Tt.getContentParts()),x&&R.push(bo(x))),$.sendMessage(x,{contentParts:R}),A&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Re?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{id?.()}:void 0});f&&(lt.replaceComposer(f),U=lt.composer.footer)}let Yf=l=>{let f=(...fe)=>{for(let re of fe){let we=l.querySelector(re);if(we)return we}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),R=l.querySelector("[data-persona-composer-mic]"),X=l.querySelector("[data-persona-composer-status]");h&&(Q=h),x&&(Ce=x),A&&(ue=A),R&&(G=R,qe=R.parentElement),X&&(M=X);let F=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Ct=F);let J=f("[data-persona-composer-attachment-button]",".persona-attachment-button");J&&(Se=J,He=J.parentElement),Re=f("[data-persona-composer-attachment-input]",'input[type="file"]'),Ze=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(ie=se),Ee=f(".persona-widget-composer__left-actions")};Qf(U),Yf(U);let Zn=o.layout?.contentMaxWidth??(Y()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Zn&&(xe.style.maxWidth=Zn,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%"),Zn&&Q&&!Y()&&(Q.style.maxWidth=Zn,Q.style.marginLeft="auto",Q.style.marginRight="auto"),Zn&&Ct&&!Y()&&(Ct.style.maxWidth=Zn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Zn&&Ze&&!Y()&&(Ze.style.maxWidth=Zn,Ze.style.marginLeft="auto",Ze.style.marginRight="auto"),o.attachments?.enabled&&Re&&Ze){Tt=Qo.fromConfig(o.attachments),Tt.setPreviewsContainer(Ze),Re.addEventListener("change",h=>{let x=h.target;Tt?.handleFileSelect(x.files),x.value=""});let l=o.attachments.dropOverlay,f=af(l);ge.appendChild(f)}let Zf=()=>en?.prefetch();if(o.contextMentions?.enabled&&Ce&&(en=Wu({config:o,textarea:Ce,anchor:Q??Ce,getMessages:()=>$.getMessages(),liveRegionHost:ge}),en)){let l=Ce;l.parentElement?.insertBefore(en.contextRow,l);let f=en.affordanceButtons;for(let h=f.length-1;h>=0;h--){let x=f[h];Ee?Ee.insertBefore(x,Ee.firstChild):Q?.appendChild(x)}}(()=>{let l=o.layout?.slots??{},f=x=>{switch(x){case"body-top":return ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return xe;case"footer-top":return Ct;case"composer":return Q;case"footer-bottom":return M;default:return null}},h=(x,A)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")O.insertBefore(A,O.firstChild);else if(x==="header-right")O.appendChild(A);else{let R=O.querySelector(".persona-flex-col");R?R.parentNode?.insertBefore(A,R.nextSibling):O.appendChild(A)}break;case"body-top":{let R=ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(A):ce.insertBefore(A,ce.firstChild);break}case"body-bottom":ce.appendChild(A);break;case"footer-top":Ct.replaceWith(A);break;case"footer-bottom":M.replaceWith(A);break;default:break}};for(let[x,A]of Object.entries(l))if(A)try{let R=A({config:o,defaultContent:()=>f(x)});R&&h(x,R)}catch(R){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,R)}})();let dd=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let R=h.getAttribute("data-bubble-type");if(R==="reasoning")_r.has(A)?_r.delete(A):_r.add(A),Pg(A,x);else if(R==="tool")$r.has(A)?$r.delete(A):$r.add(A),Rg(A,x,o);else if(R==="approval"){let F=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",J=nr.get(A)??F;nr.set(A,!J),Bg(A,x,o)}Do.delete(A)};xe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),dd(l))}),xe.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),dd(l))}),xe.addEventListener("copy",l=>{let{clipboardData:f}=l;if(!f)return;let h=xe.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),R=rg(A);!R||R===A||(f.setData("text/plain",R),l.preventDefault())});let el=new Map,pd=null,ud="idle",em={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},tm=(l,f)=>{let{icon:h,label:x}=em[f];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",f==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",f!=="idle"),l.classList.toggle("persona-message-action-loading",f==="loading");let A=ne(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},gd=()=>{xe.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{let x=f.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;tm(f,x&&x===pd?ud:"idle")})};xe.addEventListener("click",l=>{let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let A=x.getAttribute("data-actions-for");if(!A)return;let R=h.getAttribute("data-action");if(R==="copy"){let F=$.getMessages().find(J=>J.id===A);if(F&&oe.onCopy){let J=F.content||"";navigator.clipboard.writeText(J).then(()=>{h.classList.add("persona-message-action-success");let se=ne("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let fe=ne("copy",14,"currentColor",2);fe&&(h.innerHTML="",h.appendChild(fe))},2e3)}).catch(se=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",se)}),oe.onCopy(F)}}else if(R==="read-aloud")$.toggleReadAloud(A);else if(R==="upvote"||R==="downvote"){let F=(el.get(A)??null)===R,J=R==="upvote"?"thumbs-up":"thumbs-down";if(F){el.delete(A),h.classList.remove("persona-message-action-active");let se=ne(J,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=R==="upvote"?"downvote":"upvote",fe=x.querySelector(`[data-action="${se}"]`);if(fe){fe.classList.remove("persona-message-action-active");let ot=ne(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ot&&(fe.innerHTML="",fe.appendChild(ot))}el.set(A,R),h.classList.add("persona-message-action-active");let re=ne(J,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(re)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ge=$.getMessages().find(gt=>gt.id===A);Ge&&oe.onFeedback&&oe.onFeedback({type:R,messageId:Ge.id,message:Ge})}}}),xe.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let R=h.getAttribute("data-approval-action");if(!R)return;let X=R==="approve"?"approved":"denied",J=$.getMessages().find(fe=>fe.id===A);if(!J?.approval)return;let se=x.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),J.approval.toolType==="webmcp"?$.resolveWebMcpApproval(A,X):$.resolveApproval(J.approval,X)});let et=null,Gr=null,Jr=()=>{},Xr="none",ta=null,hn={artifacts:[],selectedId:null},Hn=!1,yn=!1,Qr=!1,ir=!1,fd=()=>ir||hn.artifacts.some(l=>Vo(o.features?.artifacts,l.artifactType)==="panel"),na=()=>hn.artifacts.length>0&&!Hn&&fd(),dt={current:null},tl=(l,f)=>{let h=$.getArtifactById(f),x=h?.markdown,A=h?.title||"artifact",R=h?.file,X=h?.artifactType??"markdown";if(!x){let se=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(se){let re=$.getMessages().find(we=>we.id===se);if(re?.rawContent)try{let we=JSON.parse(re.rawContent);x=we?.props?.markdown,A=we?.props?.title||A,we?.props?.file&&typeof we.props.file=="object"&&(R=we.props.file),!h&&typeof we?.props?.artifactType=="string"&&(X=we.props.artifactType)}catch{}}}return{markdown:x,title:A,file:R,artifactType:X}};xe.addEventListener("click",l=>{let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:R,title:X,file:F}=tl(h,x);if(!R)return;let{filename:J,mime:se,content:fe}=_u({title:X,markdown:R,file:F}),re=new Blob([fe],{type:se}),we=URL.createObjectURL(re),Ge=document.createElement("a");Ge.href=we,Ge.download=J,Ge.click(),URL.revokeObjectURL(we)}),xe.addEventListener("click",l=>{let h=l.target.closest("[data-artifact-custom-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-artifact-custom-action");if(!x)return;let A=h.closest("[data-artifact-inline]"),R=A?null:h.closest("[data-open-artifact]"),X=A?A.getAttribute("data-artifact-inline"):R?.getAttribute("data-open-artifact")??null,J=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===x);if(!J)return;let{markdown:se,title:fe,file:re,artifactType:we}=tl(h,X??""),Ge={artifactId:X,title:fe,artifactType:we,markdown:se,file:re};try{Promise.resolve(J.onClick(Ge)).catch(()=>{})}catch{}}),xe.addEventListener("click",l=>{let h=l.target.closest("[data-copy-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-copy-artifact");if(!x)return;let A=$.getArtifactById(x),R="";if(A)R=Bs(A);else{let{markdown:X,file:F,artifactType:J}=tl(h,x);J==="markdown"&&(R=Bs({id:x,artifactType:"markdown",status:"complete",markdown:X??"",...F?{file:F}:{}}))}R&&navigator.clipboard.writeText(R).then(()=>{let X=ne("check",16,"currentColor",2);X&&(h.replaceChildren(X),setTimeout(()=>{let F=ne("copy",16,"currentColor",2);F&&h.replaceChildren(F)},1500))}).catch(()=>{})}),xe.addEventListener("click",l=>{let h=l.target.closest("[data-expand-artifact-inline]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Hn=!1,ir=!0,yn=!0,Qr=!0,$.selectArtifact(x),Bn())}),xe.addEventListener("click",l=>{let f=l.target;if(f.closest("[data-download-artifact]")||f.closest("[data-artifact-custom-action]"))return;let h=f.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(l.preventDefault(),l.stopPropagation(),Hn=!1,ir=!0,$.selectArtifact(x),Bn())}),xe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;!f.hasAttribute("data-open-artifact")&&!f.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),f.click())});let lr=Pe.composerOverlay,cr=(l,f,h)=>{let x=f.trim();if(!x||!dt.current)return;let A=l.getAttribute("data-tool-call-id")??"",R=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:x,answers:h.structured,values:h.values??(h.source==="multi"?x.split(", "):[x]),isFreeText:R,source:h.source},bubbles:!0,composed:!0})),fo(lr,A);let X=dt.current.getMessages().find(F=>F.toolCall?.id===A);X?.agentMetadata?.awaitingLocalTool?dt.current.resolveAskUserQuestion(X,h.structured??x):dt.current.sendMessage(x)},Ho=l=>{let f=dt.current;if(!f)return;let h=l.getAttribute("data-tool-call-id")??"",x=f.getMessages().find(A=>A.toolCall?.id===h);x&&f.persistAskUserQuestionProgress(x,{answers:Wa(l,x),currentIndex:gn(l)})},md=l=>Object.entries(l).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),nl=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=gn(l),h=Sr(l);if(f>=h-1)return;let x=dt.current?.getMessages().find(A=>A.toolCall?.id===l.getAttribute("data-tool-call-id"));x&&(Ha(l,x,o,f+1),Ho(l))};lr.addEventListener("click",l=>{let h=l.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let A=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),A==="dismiss"){let R=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),fo(lr,R);let X=dt.current?.getMessages().find(F=>F.toolCall?.id===R);X?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(X),dt.current?.resolveAskUserQuestion(X,"(dismissed)"));return}if(A==="pick"){let R=h.getAttribute("data-option-label");if(!R)return;let X=x.getAttribute("data-multi-select")==="true",F=go(x);if(F&&X){let J=Ko(x)[gn(x)],se=new Set(Array.isArray(J)?J:[]);se.has(R)?se.delete(R):se.add(R),mo(x,Array.from(se)),Ho(x);return}if(F){mo(x,R),Ho(x),nl(x);return}if(X){let J=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",J?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!J);let se=x.querySelector('[data-ask-user-action="submit-multi"]');se&&(se.disabled=_l(x).length===0);return}cr(x,R,{source:"pick",values:[R]});return}if(A==="submit-multi"){let R=_l(x);if(R.length===0)return;cr(x,R.join(", "),{source:"multi",values:R});return}if(A==="open-free-text"){let R=x.querySelector('[data-ask-free-text-row="true"]');R&&(R.classList.remove("persona-hidden"),R.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let X=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!X.trim())return;if(go(x)){mo(x,X.trim()),Ho(x),nl(x);return}cr(x,X,{source:"free-text"});return}if(A==="next"||A==="back"){if(!dt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=dt.current.getMessages().find(re=>re.toolCall?.id===R);if(!X)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(J){let re=Ko(x)[gn(x)];(typeof re!="string"||re!==J)&&mo(x,J)}let se=A==="next"?1:-1,fe=gn(x)+se;Ha(x,X,o,fe),Ho(x);return}if(A==="submit-all"){if(!dt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=dt.current.getMessages().find(re=>re.toolCall?.id===R);if(!X)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";J&&mo(x,J);let se=Wa(x,X);dt.current.persistAskUserQuestionProgress(X,{answers:se,currentIndex:gn(x)});let fe=md(se);cr(x,fe||"(submitted)",{source:"submit-all",structured:se});return}if(A==="skip"){if(!dt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=dt.current.getMessages().find(we=>we.toolCall?.id===R);if(!X)return;let F=go(x),J=gn(x),se=Sr(x),fe=J>=se-1;if(!F){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),fo(lr,R),X.agentMetadata?.awaitingLocalTool&&(dt.current.markAskUserQuestionResolved(X),dt.current.resolveAskUserQuestion(X,"(dismissed)"));return}mo(x,"");let re=x.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),fe){let we=Wa(x,X),Ge=md(we);cr(x,Ge||"(skipped)",{source:"submit-all",structured:we});return}Ha(x,X,o,J+1),Ho(x);return}}),lr.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let h=l.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let A=h.value;if(A.trim()){if(go(x)){mo(x,A.trim()),Ho(x),nl(x);return}cr(x,A,{source:"free-text"})}});let hd=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let f=l.target;if(f?.tagName==="INPUT"||f?.tagName==="TEXTAREA"||f?.isContentEditable)return;let h=lr.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),R=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];R&&(l.preventDefault(),R.click())};document.addEventListener("keydown",hd);let eo=null,wt=null,Yr=null,oa=null,ol=()=>{},yd=!1,ra="",sa="";function rl(){oa?.(),oa=null}let bd=()=>{if(!eo||!wt)return;let l=e.classList.contains("persona-artifact-welded-split"),f=e.ownerDocument.defaultView??window,h=f.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let x=eo.firstElementChild;if(!x||x===wt)return;let A=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${A}px`,wt.style.zIndex="5";let R=Hc(eo,f),X=x.offsetWidth+R/2-A/2;wt.style.left=`${Math.max(0,X)}px`},aa=()=>{},nm=()=>{let l=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!f||l.innerWidth>h?!1:S||Lt(o)},ia=()=>!Jt(o)||!na()||e.classList.contains("persona-artifact-narrow-host")||nm()||(e.ownerDocument.defaultView??window).innerWidth<Ev?"none":Wc(o)?"detached":"welded",Bn=()=>{if(!et||!Jt(o))return;qs(e,o),Vs(e,o),aa();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,f=be.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l);let h=na();et.setVisible(h),et.update(hn),Hn?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),yn=!1,Qr=!1):hn.artifacts.length>0&&fd()?(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)):(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),yn=!1,Qr=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(et.setExpandToggleVisible(x),et.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),et.setCustomActions(o.features?.artifacts?.toolbarActions??[]),et.setTabFade(o.features?.artifacts?.layout?.tabFade),et.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Qr&&(yn=!1),yn!==yd){let R=et.element;yn?(ra=R.style.width,sa=R.style.maxWidth,R.style.removeProperty("width"),R.style.removeProperty("max-width")):(ra&&(R.style.width=ra),sa&&(R.style.maxWidth=sa),ra="",sa=""),yd=yn}e.classList.toggle("persona-artifact-expanded",yn),et.setExpanded(yn);let A=ia();A!==Xr&&(Xr=A,Jr()),ol()};if(Jt(o)){be.style.position="relative";let l=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ge),et=qg(o,{onSelect:h=>dt.current?.selectArtifact(h),onDismiss:()=>{Hn=!0,Bn()},onToggleExpand:()=>{let h=!yn,x=hn.selectedId??hn.artifacts[hn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:h})!==!0&&(yn=h,h||(Qr=!1),Bn())}}),et.element.classList.add("persona-hidden"),eo=f,f.appendChild(l),f.appendChild(et.element),et.backdrop&&be.appendChild(et.backdrop),be.appendChild(f),ol=()=>{if(!eo||!et)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Yr?.(),Yr=null,rl(),wt&&(wt.remove(),wt=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!wt){let x=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let A=e.ownerDocument,R=A.defaultView??window,X=F=>{if(!et||F.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||R.innerWidth<=640)return;F.preventDefault(),rl();let J=F.clientX,se=et.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,re=Ge=>{let gt=eo.getBoundingClientRect().width,ot=e.classList.contains("persona-artifact-welded-split"),on=Hc(eo,R),Et=ot?0:x.getBoundingClientRect().width||6,It=se-(Ge.clientX-J),H=Jg(It,gt,on,Et,fe?.resizableMinWidth,fe?.resizableMaxWidth);et.element.style.width=`${H}px`,et.element.style.maxWidth="none",bd()},we=()=>{A.removeEventListener("pointermove",re),A.removeEventListener("pointerup",we),A.removeEventListener("pointercancel",we),oa=null;try{x.releasePointerCapture(F.pointerId)}catch{}};oa=we,A.addEventListener("pointermove",re),A.addEventListener("pointerup",we),A.addEventListener("pointercancel",we);try{x.setPointerCapture(F.pointerId)}catch{}};x.addEventListener("pointerdown",X),wt=x,eo.insertBefore(x,et.element),Yr=()=>{x.removeEventListener("pointerdown",X)}}if(wt){let x=na();wt.classList.toggle("persona-hidden",!x),bd()}},aa=()=>{if(!S||!et||(o.launcher?.sidebarMode??!1)||Lt(o)&&Zt(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640;if(A&&x.innerWidth<=R||!Gg(o,S))return;let X=o.launcher?.width??o.launcherWidth??sn,F=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";na()?(be.style.width=F,be.style.maxWidth=F):(be.style.width=X,be.style.maxWidth=X)},typeof ResizeObserver<"u"&&(Gr=new ResizeObserver(()=>{Bn()}),Gr.observe(be))}else be.appendChild(ge);Y()&&Qe&&(Pe.peekBanner&&Qe.appendChild(Pe.peekBanner),Qe.appendChild(U)),e.appendChild(De),Qe&&e.appendChild(Qe);let la=()=>{if(Y()){be.style.width="100%",be.style.maxWidth="100%";let kt=o.launcher?.composerBar??{},Yt=De.dataset.state==="expanded",wa=kt.expandedSize??"anchored";if(!(Yt&&wa!=="fullscreen")){ge.style.background="",ge.style.border="",ge.style.borderRadius="",ge.style.overflow="",ge.style.boxShadow="";return}let gs=o.theme?.components?.panel,Aa=Co(o),yr=(Fn,zo)=>Fn==null||Fn===""?zo:Kt(Aa,Fn)??Fn,Sa="1px solid var(--persona-border)",Ll="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Uo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ge.style.background="var(--persona-surface, #ffffff)",ge.style.border=yr(gs?.border,Sa),ge.style.borderRadius=yr(gs?.borderRadius,Uo),ge.style.boxShadow=yr(gs?.shadow,Ll),ge.style.overflow="hidden";return}let l=Lt(o),f=o.launcher?.sidebarMode??!1,h=l||f||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,R=o.theme?.components?.panel,X=Co(o),F=(kt,Yt)=>kt==null||kt===""?Yt:Kt(X,kt)??kt,J=e.ownerDocument.defaultView??window,se=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,re=J.innerWidth<=fe,we=se&&re&&S,Ge=l&&se&&re,gt=o.launcher?.position??"bottom-left",ot=gt==="bottom-left"||gt==="top-left",on=o.launcher?.zIndex??zt,Et="var(--persona-panel-border, 1px solid var(--persona-border))",It="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",H="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ie=A&&!we&&!Ge;Ie?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let je=Ie?Et:f||we?"none":Et,Te=Ie?It:we?"none":f?ot?"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))":x?"none":It;l&&!we&&!Ie&&(Te="none",je="none");let Mt=Ie?H:f||we?"0":H,ft=F(R?.border,je),Vt=F(R?.shadow,Te),mt=F(R?.borderRadius,Mt),Qt=ia(),Wt=Qt==="detached",We=Qt==="welded";e.classList.toggle("persona-artifact-detached-split",Wt),e.classList.toggle("persona-artifact-welded-split",We);let Ue="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",St=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Jt(o)&&Wc(o)&&x&&!l;e.classList.toggle("persona-artifact-chat-flush",St);let pt=Wt||St?"none":Vt,yt=Wt?Et:We?"none":ft,tt=Wt?H:mt;St&&(yt="none",tt="0");let Fe=R?.borderRadius!=null&&R.borderRadius!=="",vt=St&&!Fe?"0":mt,$t=ce.scrollTop;e.style.cssText="",De.style.cssText="",be.style.cssText="",ge.style.cssText="",ce.style.cssText="",U.style.cssText="",ze&&(ce.style.display="none"),(h||x)&&(e.style.minWidth="0");let un=()=>{if($t<=0)return;(ce.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ce.scrollTop===$t)return;let Yt=ce.scrollHeight-ce.clientHeight;Yt<=0||(ce.scrollTop=Math.min($t,Yt))})};if(we){De.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"),De.style.cssText=`
48
+ `,w.addEventListener("click",()=>{u=q,P.forEach((z,V)=>{let Y=V<q;z.classList.toggle("selected",Y),z.setAttribute("aria-checked",V===q-1?"true":"false")})}),P.push(w),k.appendChild(w)}b.appendChild(k);let W=null;if(p){let q=document.createElement("div");q.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),q.appendChild(W),b.appendChild(q)}let S=document.createElement("div");S.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{n?.(),c.remove()});let j=document.createElement("button");return j.type="button",j.className="persona-feedback-btn persona-feedback-btn-submit",j.textContent=a,j.addEventListener("click",async()=>{if(u===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}j.disabled=!0,j.textContent="Submitting...";try{let q=W?.value.trim()||void 0;await t(u,q),c.remove()}catch(q){j.disabled=!1,j.textContent=a,console.error("[CSAT Feedback] Failed to submit:",q)}}),S.appendChild(I),S.appendChild(j),b.appendChild(S),c.appendChild(b),c}function Vi(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let b=null,g=document.createElement("div");g.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,y.appendChild(C);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=r,y.appendChild(k),g.appendChild(y);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-nps",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Likelihood rating from 0 to 10");let W=document.createElement("div");W.className="persona-feedback-labels";let S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=d;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=c,W.appendChild(S),W.appendChild(I);let j=document.createElement("div");j.className="persona-feedback-numbers";let q=[];for(let D=0;D<=10;D++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-number-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`Rating ${D} out of 10`),N.textContent=String(D),N.dataset.rating=String(D),D<=6?N.classList.add("persona-feedback-detractor"):D<=8?N.classList.add("persona-feedback-passive"):N.classList.add("persona-feedback-promoter"),N.addEventListener("click",()=>{b=D,q.forEach((ce,he)=>{ce.classList.toggle("selected",he===D),ce.setAttribute("aria-checked",he===D?"true":"false")})}),q.push(N),j.appendChild(N)}P.appendChild(W),P.appendChild(j),g.appendChild(P);let w=null;if(p){let D=document.createElement("div");D.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=s,w.rows=3,w.setAttribute("aria-label","Additional comments"),D.appendChild(w),g.appendChild(D)}let z=document.createElement("div");z.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=i,V.addEventListener("click",()=>{n?.(),u.remove()});let Y=document.createElement("button");return Y.type="button",Y.className="persona-feedback-btn persona-feedback-btn-submit",Y.textContent=a,Y.addEventListener("click",async()=>{if(b===null){j.classList.add("persona-feedback-shake"),setTimeout(()=>j.classList.remove("persona-feedback-shake"),500);return}Y.disabled=!0,Y.textContent="Submitting...";try{let D=w?.value.trim()||void 0;await t(b,D),u.remove()}catch(D){Y.disabled=!1,Y.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),z.appendChild(V),z.appendChild(Y),g.appendChild(z),u.appendChild(g),u}var qr="persona-chat-history",Rv=30*1e3,Iv=641,Wv={"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 Hv(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=Wv[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function Ki(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 Bv(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function Ov(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var $c=e=>!e||typeof e!="object"?{}:{...e},pf=e=>e.map(t=>({...t,streaming:!1})),uf=(e,t,n)=>{let o=e?.markdown?Vo(e.markdown):null,r=wr(e?.sanitize);return e?.postprocessMessage&&r&&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."),s=>{let a=s.text??"",i=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=_n()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:i??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Ip(a):a,u=o(c);d=r&&p?r(u):u}else d=Ln(a);return d}};function gf(e){let t=m("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=ne(n,o,r,s);if(a&&t.appendChild(a),e?.label){let i=m("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var Dv=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},Nv=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:Dv(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Gi=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Ir(t),r=Js.getForInstance(o.plugins),{plugin:s,teardown:a}=qg();o.components&&Sn.registerAll(o.components);let i=sf(),d=o.persistState===!1?null:o.storageAdapter??$i(),c={},u=null,b=!1,g=l=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(l);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:x}=f;return x&&(b=!0),h}return f}catch(f){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return l};if(d?.load)try{let l=d.load();if(l&&typeof l.then=="function")u=l.then(f=>g(f??{messages:[],metadata:{}}));else{let h=g(l??{messages:[],metadata:{}});h.metadata&&(c=$c(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=g({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let y=()=>c,C=l=>{c=l({...c})??{},yl()},k=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Xs],P=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ar.message,ar.messageAndClick],W=Qs({parsers:k,handlers:P,getSessionMetadata:y,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null});W.syncFromMetadata();let S=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,j=o.autoFocusInput??!1,q=I,w=S,z=o.layout?.header?.layout,V=!1,Y=()=>ko(o),D=()=>S||Y(),N=Y()?!1:S?I:!0,ce=!1,he=null,Ae=()=>{ce=!0,he&&clearTimeout(he),he=setTimeout(()=>{ce&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ce=!1)},1e4)},Me=uf(o,W,Ae),ae=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,Z=o.features?.showEventStreamToggle??!1,de=o.features?.scrollToBottom??{},ee=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,pe=Z?new qs(ye):null,ke=o.features?.eventStream?.maxEvents??2e3,Ne=Z?new zs(ke,pe):null,$e=Z?new Vs:null,Be=null,ze=!1,Ke=null,Le=0;pe?.open().then(()=>Ne?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let oe={onCopy:l=>{i.emit("message:copy",l),$?.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",f)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{i.emit("message:feedback",l),$?.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",f)}),o.messageActions?.onFeedback?.(l)}},Oe=o.statusIndicator??{},xt=l=>l==="idle"?Oe.idleText??Ht.idle:l==="connecting"?Oe.connectingText??Ht.connecting:l==="connected"?Oe.connectedText??Ht.connected:l==="error"?Oe.errorText??Ht.error:l==="paused"?Oe.pausedText??Ht.paused:l==="resuming"?Oe.resumingText??Ht.resuming:Ht[l];function ht(l,f,h,x){if(x==="idle"&&h.idleLink){l.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=f,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=f}let lt=Pg({config:o,showClose:D()}),{wrapper:De,panel:be,pillRoot:Qe}=lt.shell,Pe=lt.panelElements,{container:ge,body:le,messagesWrapper:xe,suggestions:Ct,textarea:Ce,sendButton:ue,sendButtonWrapper:fn,composerForm:Q,statusText:M,introTitle:_,introSubtitle:v,closeButton:E,iconHolder:L,headerTitle:B,headerSubtitle:K,header:O,footer:U,actionsRow:ie,rightActions:Je}=Pe,Ee=Pe.leftActions,st=Pe.setSendButtonMode,G=Pe.micButton,qe=Pe.micButtonWrapper,Se=Pe.attachmentButton,He=Pe.attachmentButtonWrapper,Re=Pe.attachmentInput,Ze=Pe.attachmentPreviewsContainer;ge.classList.add("persona-relative"),le.classList.add("persona-relative");let Po=12,Ro=()=>de.label??"",ol=()=>de.iconName??"arrow-down",ta=()=>de.enabled!==!1,qt=()=>ee.mode??"anchor-top",Qn=()=>qt()==="follow"||qt()==="anchor-top"&&ts,sd=()=>ee.anchorTopOffset??16,nm=()=>ee.restorePosition??"bottom",ad=()=>ee.pauseOnInteraction===!0,id=()=>ee.showActivityWhilePinned!==!1,ld=()=>ee.announce===!0,Pt=m("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 Vr=m("span","persona-flex persona-items-center"),rl=m("span",""),Io=m("span","");Io.setAttribute("data-persona-scroll-to-bottom-count",""),Io.style.display="none",Pt.append(Vr,rl,Io),ge.appendChild(Pt);let Yn=m("div","persona-stream-anchor-spacer");Yn.setAttribute("aria-hidden","true"),Yn.setAttribute("data-persona-anchor-spacer",""),Yn.style.flexShrink="0",Yn.style.pointerEvents="none",Yn.style.height="0px",le.appendChild(Yn);let Wo=m("div","persona-sr-only");Wo.setAttribute("aria-live","polite"),Wo.setAttribute("aria-atomic","true"),Wo.setAttribute("role","status"),Wo.setAttribute("data-persona-live-region",""),Object.assign(Wo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ge.appendChild(Wo);let Kr=null,na=null,cd=l=>{!ld()||!l||(na=l,Kr===null&&(Kr=setTimeout(()=>{Kr=null,na&&ld()&&(Wo.textContent=na),na=null},400)))},ir=()=>{let f=U.style.display==="none"?0:U.offsetHeight;Pt.style.bottom=`${f+Po}px`};ir();let dd=()=>{let l=!!Ro();Pt.setAttribute("aria-label",Ro()||"Jump to latest"),Pt.title=Ro(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Vr.innerHTML="";let f=ne(ol(),"14px","currentColor",2);f?(Vr.appendChild(f),Vr.style.display=""):Vr.style.display="none",rl.textContent=Ro(),rl.style.display=l?"":"none"};dd();let Tt=null,en=null,pd=null,ud=r.find(l=>l.renderHeader);if(ud?.renderHeader){let l=ud.renderHeader({config:o,defaultRenderer:()=>{let f=Jn({config:o,showClose:D()});return tr(ge,f,o),f.header},onClose:()=>ut(!1,"user")});if(l){let f=ge.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),O=l,lt.header.element=l)}}let sl=()=>{if(!Ne)return;if(ze=!0,!Be&&Ne&&(Be=Xg({buffer:Ne,getFullHistory:()=>Ne.getAllFromStore(),onClose:()=>Gr(),config:o,plugins:r,getThroughput:()=>$e?.getMetric()??{status:"idle"}})),Be&&(le.style.display="none",U.parentNode?.insertBefore(Be.element,U),Be.update()),nt){nt.style.boxShadow=`inset 0 0 0 1.5px ${Jt.actionIconColor}`;let f=o.features?.eventStream?.classNames?.toggleButtonActive;f&&f.split(/\s+/).forEach(h=>h&&nt.classList.add(h))}let l=()=>{if(!ze)return;let f=Date.now();f-Le>=200&&(Be?.update(),Le=f),Ke=requestAnimationFrame(l)};Le=0,Ke=requestAnimationFrame(l),nn(),i.emit("eventStream:opened",{timestamp:Date.now()})},Gr=()=>{if(ze){if(ze=!1,Be&&Be.element.remove(),le.style.display="",nt){nt.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&nt.classList.remove(f))}Ke!==null&&(cancelAnimationFrame(Ke),Ke=null),nn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},nt=null;if(Z){let l=o.features?.eventStream?.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");nt=m("button",f),nt.style.width="28px",nt.style.height="28px",nt.style.color=Jt.actionIconColor,nt.type="button",nt.setAttribute("aria-label","Event Stream"),nt.title="Event Stream";let h=ne("activity","18px","currentColor",1.5);h&&nt.appendChild(h);let x=Pe.clearChatButtonWrapper,A=Pe.closeButtonWrapper,R=x||A;R&&R.parentNode===O?O.insertBefore(nt,R):O.appendChild(nt),nt.addEventListener("click",()=>{ze?Gr():sl()})}let om=l=>{let f=o.attachments;if(!f?.enabled)return;let h=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!h){h=m("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 A=l.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(h,A):l.insertBefore(h,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let A=m("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(f.allowedTypes??Vn).join(","),A.multiple=(f.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",f.buttonTooltipText??"Attach files"),l.appendChild(A)}},gd=r.find(l=>l.renderComposer);if(gd?.renderComposer){let l=o.composer,f=gd.renderComposer({config:o,defaultRenderer:()=>Fr({config:o}).footer,onSubmit:h=>{if(!$||$.isStreaming())return;let x=h.trim(),A=Tt?.hasAttachments()??!1;if(!x&&!A)return;Ud();let R;A&&(R=[],R.push(...Tt.getContentParts()),x&&R.push(bo(x))),$.sendMessage(x,{contentParts:R}),A&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Re?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{pd?.()}:void 0});f&&(lt.replaceComposer(f),U=lt.composer.footer)}let rm=l=>{let f=(...fe)=>{for(let re of fe){let we=l.querySelector(re);if(we)return we}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),R=l.querySelector("[data-persona-composer-mic]"),X=l.querySelector("[data-persona-composer-status]");h&&(Q=h),x&&(Ce=x),A&&(ue=A),R&&(G=R,qe=R.parentElement),X&&(M=X);let F=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Ct=F);let J=f("[data-persona-composer-attachment-button]",".persona-attachment-button");J&&(Se=J,He=J.parentElement),Re=f("[data-persona-composer-attachment-input]",'input[type="file"]'),Ze=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(ie=se),Ee=f(".persona-widget-composer__left-actions")};om(U),rm(U);let Zn=o.layout?.contentMaxWidth??(Y()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Zn&&(xe.style.maxWidth=Zn,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%"),Zn&&Q&&!Y()&&(Q.style.maxWidth=Zn,Q.style.marginLeft="auto",Q.style.marginRight="auto"),Zn&&Ct&&!Y()&&(Ct.style.maxWidth=Zn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Zn&&Ze&&!Y()&&(Ze.style.maxWidth=Zn,Ze.style.marginLeft="auto",Ze.style.marginRight="auto"),o.attachments?.enabled&&Re&&Ze){Tt=Yo.fromConfig(o.attachments),Tt.setPreviewsContainer(Ze),Re.addEventListener("change",h=>{let x=h.target;Tt?.handleFileSelect(x.files),x.value=""});let l=o.attachments.dropOverlay,f=gf(l);ge.appendChild(f)}let sm=()=>en?.prefetch();if(o.contextMentions?.enabled&&Ce&&(en=Nu({config:o,textarea:Ce,anchor:Q??Ce,getMessages:()=>$.getMessages(),liveRegionHost:ge}),en)){let l=Ce;l.parentElement?.insertBefore(en.contextRow,l);let f=en.affordanceButtons;for(let h=f.length-1;h>=0;h--){let x=f[h];Ee?Ee.insertBefore(x,Ee.firstChild):Q?.appendChild(x)}}(()=>{let l=o.layout?.slots??{},f=x=>{switch(x){case"body-top":return ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return xe;case"footer-top":return Ct;case"composer":return Q;case"footer-bottom":return M;default:return null}},h=(x,A)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")O.insertBefore(A,O.firstChild);else if(x==="header-right")O.appendChild(A);else{let R=O.querySelector(".persona-flex-col");R?R.parentNode?.insertBefore(A,R.nextSibling):O.appendChild(A)}break;case"body-top":{let R=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(A):le.insertBefore(A,le.firstChild);break}case"body-bottom":le.appendChild(A);break;case"footer-top":Ct.replaceWith(A);break;case"footer-bottom":M.replaceWith(A);break;default:break}};for(let[x,A]of Object.entries(l))if(A)try{let R=A({config:o,defaultContent:()=>f(x)});R&&h(x,R)}catch(R){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,R)}})();let fd=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let R=h.getAttribute("data-bubble-type");if(R==="reasoning")$r.has(A)?$r.delete(A):$r.add(A),Og(A,x);else if(R==="tool")jr.has(A)?jr.delete(A):jr.add(A),Dg(A,x,o);else if(R==="approval"){let F=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",J=or.get(A)??F;or.set(A,!J),$g(A,x,o)}Do.delete(A)};xe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),fd(l))}),xe.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),fd(l))}),xe.addEventListener("copy",l=>{let{clipboardData:f}=l;if(!f)return;let h=xe.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),R=cg(A);!R||R===A||(f.setData("text/plain",R),l.preventDefault())});let al=new Map,md=null,hd="idle",am={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},im=(l,f)=>{let{icon:h,label:x}=am[f];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",f==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",f!=="idle"),l.classList.toggle("persona-message-action-loading",f==="loading");let A=ne(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},yd=()=>{xe.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{let x=f.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;im(f,x&&x===md?hd:"idle")})};xe.addEventListener("click",l=>{let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let A=x.getAttribute("data-actions-for");if(!A)return;let R=h.getAttribute("data-action");if(R==="copy"){let F=$.getMessages().find(J=>J.id===A);if(F&&oe.onCopy){let J=F.content||"";navigator.clipboard.writeText(J).then(()=>{h.classList.add("persona-message-action-success");let se=ne("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let fe=ne("copy",14,"currentColor",2);fe&&(h.innerHTML="",h.appendChild(fe))},2e3)}).catch(se=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",se)}),oe.onCopy(F)}}else if(R==="read-aloud")$.toggleReadAloud(A);else if(R==="upvote"||R==="downvote"){let F=(al.get(A)??null)===R,J=R==="upvote"?"thumbs-up":"thumbs-down";if(F){al.delete(A),h.classList.remove("persona-message-action-active");let se=ne(J,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=R==="upvote"?"downvote":"upvote",fe=x.querySelector(`[data-action="${se}"]`);if(fe){fe.classList.remove("persona-message-action-active");let ot=ne(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ot&&(fe.innerHTML="",fe.appendChild(ot))}al.set(A,R),h.classList.add("persona-message-action-active");let re=ne(J,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(re)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ge=$.getMessages().find(gt=>gt.id===A);Ge&&oe.onFeedback&&oe.onFeedback({type:R,messageId:Ge.id,message:Ge})}}}),xe.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let R=h.getAttribute("data-approval-action");if(!R)return;let X=R==="approve"?"approved":"denied",J=$.getMessages().find(fe=>fe.id===A);if(!J?.approval)return;let se=x.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),J.approval.toolType==="webmcp"?$.resolveWebMcpApproval(A,X):$.resolveApproval(J.approval,X)});let et=null,Jr=null,Xr=()=>{},Qr="none",oa=null,mn={artifacts:[],selectedId:null},Wn=!1,hn=!1,Yr=!1,lr=!1,bd=()=>lr||mn.artifacts.some(l=>Ko(o.features?.artifacts,l.artifactType)==="panel"),ra=()=>mn.artifacts.length>0&&!Wn&&bd(),dt={current:null},il=(l,f)=>{let h=$.getArtifactById(f),x=h?.markdown,A=h?.title||"artifact",R=h?.file,X=h?.artifactType??"markdown";if(!x){let se=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(se){let re=$.getMessages().find(we=>we.id===se);if(re?.rawContent)try{let we=JSON.parse(re.rawContent);x=we?.props?.markdown,A=we?.props?.title||A,we?.props?.file&&typeof we.props.file=="object"&&(R=we.props.file),!h&&typeof we?.props?.artifactType=="string"&&(X=we.props.artifactType)}catch{}}}return{markdown:x,title:A,file:R,artifactType:X}};xe.addEventListener("click",l=>{let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:R,title:X,file:F}=il(h,x);if(!R)return;let{filename:J,mime:se,content:fe}=qu({title:X,markdown:R,file:F}),re=new Blob([fe],{type:se}),we=URL.createObjectURL(re),Ge=document.createElement("a");Ge.href=we,Ge.download=J,Ge.click(),URL.revokeObjectURL(we)}),xe.addEventListener("click",l=>{let h=l.target.closest("[data-artifact-custom-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-artifact-custom-action");if(!x)return;let A=h.closest("[data-artifact-inline]"),R=A?null:h.closest("[data-open-artifact]"),X=A?A.getAttribute("data-artifact-inline"):R?.getAttribute("data-open-artifact")??null,J=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===x);if(!J)return;let{markdown:se,title:fe,file:re,artifactType:we}=il(h,X??""),Ge={artifactId:X,title:fe,artifactType:we,markdown:se,file:re};try{Promise.resolve(J.onClick(Ge)).catch(()=>{})}catch{}}),xe.addEventListener("click",l=>{let h=l.target.closest("[data-copy-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-copy-artifact");if(!x)return;let A=$.getArtifactById(x),R="";if(A)R=Ds(A);else{let{markdown:X,file:F,artifactType:J}=il(h,x);J==="markdown"&&(R=Ds({id:x,artifactType:"markdown",status:"complete",markdown:X??"",...F?{file:F}:{}}))}R&&navigator.clipboard.writeText(R).then(()=>{let X=ne("check",16,"currentColor",2);X&&(h.replaceChildren(X),setTimeout(()=>{let F=ne("copy",16,"currentColor",2);F&&h.replaceChildren(F)},1500))}).catch(()=>{})}),xe.addEventListener("click",l=>{let h=l.target.closest("[data-expand-artifact-inline]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Wn=!1,lr=!0,hn=!0,Yr=!0,$.selectArtifact(x),Hn())}),xe.addEventListener("click",l=>{let f=l.target;if(f.closest("[data-download-artifact]")||f.closest("[data-artifact-custom-action]"))return;let h=f.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(l.preventDefault(),l.stopPropagation(),Wn=!1,lr=!0,$.selectArtifact(x),Hn())}),xe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;!f.hasAttribute("data-open-artifact")&&!f.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),f.click())});let cr=Pe.composerOverlay,dr=(l,f,h)=>{let x=f.trim();if(!x||!dt.current)return;let A=l.getAttribute("data-tool-call-id")??"",R=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:x,answers:h.structured,values:h.values??(h.source==="multi"?x.split(", "):[x]),isFreeText:R,source:h.source},bubbles:!0,composed:!0})),fo(cr,A);let X=dt.current.getMessages().find(F=>F.toolCall?.id===A);X?.agentMetadata?.awaitingLocalTool?dt.current.resolveAskUserQuestion(X,h.structured??x):dt.current.sendMessage(x)},Ho=l=>{let f=dt.current;if(!f)return;let h=l.getAttribute("data-tool-call-id")??"",x=f.getMessages().find(A=>A.toolCall?.id===h);x&&f.persistAskUserQuestionProgress(x,{answers:Fa(l,x),currentIndex:gn(l)})},vd=l=>Object.entries(l).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),ll=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=gn(l),h=Tr(l);if(f>=h-1)return;let x=dt.current?.getMessages().find(A=>A.toolCall?.id===l.getAttribute("data-tool-call-id"));x&&(_a(l,x,o,f+1),Ho(l))};cr.addEventListener("click",l=>{let h=l.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let A=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),A==="dismiss"){let R=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),fo(cr,R);let X=dt.current?.getMessages().find(F=>F.toolCall?.id===R);X?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(X),dt.current?.resolveAskUserQuestion(X,"(dismissed)"));return}if(A==="pick"){let R=h.getAttribute("data-option-label");if(!R)return;let X=x.getAttribute("data-multi-select")==="true",F=go(x);if(F&&X){let J=Go(x)[gn(x)],se=new Set(Array.isArray(J)?J:[]);se.has(R)?se.delete(R):se.add(R),mo(x,Array.from(se)),Ho(x);return}if(F){mo(x,R),Ho(x),ll(x);return}if(X){let J=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",J?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!J);let se=x.querySelector('[data-ask-user-action="submit-multi"]');se&&(se.disabled=Ul(x).length===0);return}dr(x,R,{source:"pick",values:[R]});return}if(A==="submit-multi"){let R=Ul(x);if(R.length===0)return;dr(x,R.join(", "),{source:"multi",values:R});return}if(A==="open-free-text"){let R=x.querySelector('[data-ask-free-text-row="true"]');R&&(R.classList.remove("persona-hidden"),R.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let X=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!X.trim())return;if(go(x)){mo(x,X.trim()),Ho(x),ll(x);return}dr(x,X,{source:"free-text"});return}if(A==="next"||A==="back"){if(!dt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=dt.current.getMessages().find(re=>re.toolCall?.id===R);if(!X)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(J){let re=Go(x)[gn(x)];(typeof re!="string"||re!==J)&&mo(x,J)}let se=A==="next"?1:-1,fe=gn(x)+se;_a(x,X,o,fe),Ho(x);return}if(A==="submit-all"){if(!dt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=dt.current.getMessages().find(re=>re.toolCall?.id===R);if(!X)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";J&&mo(x,J);let se=Fa(x,X);dt.current.persistAskUserQuestionProgress(X,{answers:se,currentIndex:gn(x)});let fe=vd(se);dr(x,fe||"(submitted)",{source:"submit-all",structured:se});return}if(A==="skip"){if(!dt.current)return;let R=x.getAttribute("data-tool-call-id")??"",X=dt.current.getMessages().find(we=>we.toolCall?.id===R);if(!X)return;let F=go(x),J=gn(x),se=Tr(x),fe=J>=se-1;if(!F){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),fo(cr,R),X.agentMetadata?.awaitingLocalTool&&(dt.current.markAskUserQuestionResolved(X),dt.current.resolveAskUserQuestion(X,"(dismissed)"));return}mo(x,"");let re=x.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),fe){let we=Fa(x,X),Ge=vd(we);dr(x,Ge||"(skipped)",{source:"submit-all",structured:we});return}_a(x,X,o,J+1),Ho(x);return}}),cr.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let h=l.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let A=h.value;if(A.trim()){if(go(x)){mo(x,A.trim()),Ho(x),ll(x);return}dr(x,A,{source:"free-text"})}});let xd=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let f=l.target;if(f?.tagName==="INPUT"||f?.tagName==="TEXTAREA"||f?.isContentEditable)return;let h=cr.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),R=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];R&&(l.preventDefault(),R.click())};document.addEventListener("keydown",xd);let eo=null,wt=null,Zr=null,sa=null,cl=()=>{},Cd=!1,aa="",ia="";function dl(){sa?.(),sa=null}let wd=()=>{if(!eo||!wt)return;let l=e.classList.contains("persona-artifact-welded-split"),f=e.ownerDocument.defaultView??window,h=f.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let x=eo.firstElementChild;if(!x||x===wt)return;let A=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${A}px`,wt.style.zIndex="5";let R=Dc(eo,f),X=x.offsetWidth+R/2-A/2;wt.style.left=`${Math.max(0,X)}px`},la=()=>{},lm=()=>{let l=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!f||l.innerWidth>h?!1:S||Lt(o)},ca=()=>!Xt(o)||!ra()||e.classList.contains("persona-artifact-narrow-host")||lm()||(e.ownerDocument.defaultView??window).innerWidth<Iv?"none":Oc(o)?"detached":"welded",Hn=()=>{if(!et||!Xt(o))return;Ks(e,o),Gs(e,o),la();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,f=be.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l);let h=ra();et.setVisible(h),et.update(mn),Wn?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),hn=!1,Yr=!1):mn.artifacts.length>0&&bd()?(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)):(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),hn=!1,Yr=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(et.setExpandToggleVisible(x),et.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),et.setCustomActions(o.features?.artifacts?.toolbarActions??[]),et.setTabFade(o.features?.artifacts?.layout?.tabFade),et.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Yr&&(hn=!1),hn!==Cd){let R=et.element;hn?(aa=R.style.width,ia=R.style.maxWidth,R.style.removeProperty("width"),R.style.removeProperty("max-width")):(aa&&(R.style.width=aa),ia&&(R.style.maxWidth=ia),aa="",ia=""),Cd=hn}e.classList.toggle("persona-artifact-expanded",hn),et.setExpanded(hn);let A=ca();A!==Qr&&(Qr=A,Xr()),cl()};if(Xt(o)){be.style.position="relative";let l=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ge),et=Qg(o,{onSelect:h=>dt.current?.selectArtifact(h),onDismiss:()=>{Wn=!0,Hn()},onToggleExpand:()=>{let h=!hn,x=mn.selectedId??mn.artifacts[mn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:h})!==!0&&(hn=h,h||(Yr=!1),Hn())}}),et.element.classList.add("persona-hidden"),eo=f,f.appendChild(l),f.appendChild(et.element),et.backdrop&&be.appendChild(et.backdrop),be.appendChild(f),cl=()=>{if(!eo||!et)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Zr?.(),Zr=null,dl(),wt&&(wt.remove(),wt=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!wt){let x=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let A=e.ownerDocument,R=A.defaultView??window,X=F=>{if(!et||F.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||R.innerWidth<=640)return;F.preventDefault(),dl();let J=F.clientX,se=et.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,re=Ge=>{let gt=eo.getBoundingClientRect().width,ot=e.classList.contains("persona-artifact-welded-split"),on=Dc(eo,R),Et=ot?0:x.getBoundingClientRect().width||6,It=se-(Ge.clientX-J),H=tf(It,gt,on,Et,fe?.resizableMinWidth,fe?.resizableMaxWidth);et.element.style.width=`${H}px`,et.element.style.maxWidth="none",wd()},we=()=>{A.removeEventListener("pointermove",re),A.removeEventListener("pointerup",we),A.removeEventListener("pointercancel",we),sa=null;try{x.releasePointerCapture(F.pointerId)}catch{}};sa=we,A.addEventListener("pointermove",re),A.addEventListener("pointerup",we),A.addEventListener("pointercancel",we);try{x.setPointerCapture(F.pointerId)}catch{}};x.addEventListener("pointerdown",X),wt=x,eo.insertBefore(x,et.element),Zr=()=>{x.removeEventListener("pointerdown",X)}}if(wt){let x=ra();wt.classList.toggle("persona-hidden",!x),wd()}},la=()=>{if(!S||!et||(o.launcher?.sidebarMode??!1)||Lt(o)&&Zt(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640;if(A&&x.innerWidth<=R||!ef(o,S))return;let X=o.launcher?.width??o.launcherWidth??sn,F=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ra()?(be.style.width=F,be.style.maxWidth=F):(be.style.width=X,be.style.maxWidth=X)},typeof ResizeObserver<"u"&&(Jr=new ResizeObserver(()=>{Hn()}),Jr.observe(be))}else be.appendChild(ge);Y()&&Qe&&(Pe.peekBanner&&Qe.appendChild(Pe.peekBanner),Qe.appendChild(U)),e.appendChild(De),Qe&&e.appendChild(Qe);let da=()=>{if(Y()){be.style.width="100%",be.style.maxWidth="100%";let kt=o.launcher?.composerBar??{},Yt=De.dataset.state==="expanded",ka=kt.expandedSize??"anchored";if(!(Yt&&ka!=="fullscreen")){ge.style.background="",ge.style.border="",ge.style.borderRadius="",ge.style.overflow="",ge.style.boxShadow="";return}let ms=o.theme?.components?.panel,La=Co(o),br=(Nn,qo)=>Nn==null||Nn===""?qo:Gt(La,Nn)??Nn,Pa="1px solid var(--persona-border)",Il="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",zo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ge.style.background="var(--persona-surface, #ffffff)",ge.style.border=br(ms?.border,Pa),ge.style.borderRadius=br(ms?.borderRadius,zo),ge.style.boxShadow=br(ms?.shadow,Il),ge.style.overflow="hidden";return}let l=Lt(o),f=o.launcher?.sidebarMode??!1,h=l||f||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,R=o.theme?.components?.panel,X=Co(o),F=(kt,Yt)=>kt==null||kt===""?Yt:Gt(X,kt)??kt,J=e.ownerDocument.defaultView??window,se=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,re=J.innerWidth<=fe,we=se&&re&&S,Ge=l&&se&&re,gt=o.launcher?.position??"bottom-left",ot=gt==="bottom-left"||gt==="top-left",on=o.launcher?.zIndex??zt,Et="var(--persona-panel-border, 1px solid var(--persona-border))",It="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",H="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ie=A&&!we&&!Ge;Ie?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let je=Ie?Et:f||we?"none":Et,Te=Ie?It:we?"none":f?ot?"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))":x?"none":It;l&&!we&&!Ie&&(Te="none",je="none");let Mt=Ie?H:f||we?"0":H,ft=F(R?.border,je),Kt=F(R?.shadow,Te),mt=F(R?.borderRadius,Mt),Qt=ca(),Wt=Qt==="detached",We=Qt==="welded";e.classList.toggle("persona-artifact-detached-split",Wt),e.classList.toggle("persona-artifact-welded-split",We);let Ue="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",St=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Xt(o)&&Oc(o)&&x&&!l;e.classList.toggle("persona-artifact-chat-flush",St);let pt=Wt||St?"none":Kt,yt=Wt?Et:We?"none":ft,tt=Wt?H:mt;St&&(yt="none",tt="0");let Fe=R?.borderRadius!=null&&R.borderRadius!=="",vt=St&&!Fe?"0":mt,$t=le.scrollTop;e.style.cssText="",De.style.cssText="",be.style.cssText="",ge.style.cssText="",le.style.cssText="",U.style.cssText="",ze&&(le.style.display="none"),(h||x)&&(e.style.minWidth="0");let un=()=>{if($t<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===$t)return;let Yt=le.scrollHeight-le.clientHeight;Yt<=0||(le.scrollTop=Math.min($t,Yt))})};if(we){De.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"),De.style.cssText=`
49
49
  position: fixed !important;
50
50
  inset: 0 !important;
51
51
  width: 100% !important;
@@ -81,7 +81,7 @@ _Details: ${n.message}_`:o}var Ms=e=>({isError:!0,content:[{type:"text",text:e}]
81
81
  overflow: hidden !important;
82
82
  border-radius: 0 !important;
83
83
  border: none !important;
84
- `,ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.overflowY="auto",U.style.flexShrink="0",V=!0,un();return}let Ca=o?.launcher?.width??o?.launcherWidth??sn;if(!f&&!l)x&&h?(be.style.width="100%",be.style.maxWidth="100%"):(be.style.width=Ca,be.style.maxWidth=Ca);else if(l)if(Zt(o).reveal==="emerge"&&!A){let Yt=Zt(o).width;be.style.width=Yt,be.style.maxWidth=Yt}else be.style.width="100%",be.style.maxWidth="100%";if(aa(),be.style.boxShadow=pt,be.style.borderRadius=vt,Wt?be.style.border="none":We&&(be.style.border=ft),ge.style.border=yt,ge.style.borderRadius=tt,ge.style.boxShadow=Wt&&!St?Ue:"",St&&(ge.style.background="transparent",ce.style.background="transparent",U.style.background="transparent",U.style.borderTop="none"),We){let kt=o.features?.artifacts?.layout;ta=kt?.unifiedSplitOuterRadius?.trim()||kt?.paneBorderRadius?.trim()||mt}else ta=null;if(l&&!we&&!Ie&&!Wt&&!We&&R?.border===void 0&&(ge.style.border="none",Zt(o).side==="right"?ge.style.borderLeft="1px solid var(--persona-border)":ge.style.borderRight="1px solid var(--persona-border)"),l&&!we&&We&&R?.border===void 0&&(Zt(o).side==="right"?be.style.borderLeft="1px solid var(--persona-border)":be.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),De.style.display="flex",De.style.flexDirection="column",De.style.flex="1 1 0%",De.style.minHeight="0",De.style.maxHeight="100%",De.style.height="100%",x&&(De.style.overflow="hidden"),be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.height="100%",Wt||(be.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",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.overflowY="auto",U.style.flexShrink="0"),x&&(Ie||Wt||St)&&!l&&(St||(De.style.padding="var(--persona-panel-inset)"),De.style.background="var(--persona-panel-canvas-bg)"),De.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!x&&!l&&(En[gt]??En["bottom-right"]).split(" ").forEach(Yt=>De.classList.add(Yt)),f){let kt=o.launcher?.sidebarWidth??"420px";A?De.style.cssText=`
84
+ `,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",U.style.flexShrink="0",V=!0,un();return}let Ma=o?.launcher?.width??o?.launcherWidth??sn;if(!f&&!l)x&&h?(be.style.width="100%",be.style.maxWidth="100%"):(be.style.width=Ma,be.style.maxWidth=Ma);else if(l)if(Zt(o).reveal==="emerge"&&!A){let Yt=Zt(o).width;be.style.width=Yt,be.style.maxWidth=Yt}else be.style.width="100%",be.style.maxWidth="100%";if(la(),be.style.boxShadow=pt,be.style.borderRadius=vt,Wt?be.style.border="none":We&&(be.style.border=ft),ge.style.border=yt,ge.style.borderRadius=tt,ge.style.boxShadow=Wt&&!St?Ue:"",St&&(ge.style.background="transparent",le.style.background="transparent",U.style.background="transparent",U.style.borderTop="none"),We){let kt=o.features?.artifacts?.layout;oa=kt?.unifiedSplitOuterRadius?.trim()||kt?.paneBorderRadius?.trim()||mt}else oa=null;if(l&&!we&&!Ie&&!Wt&&!We&&R?.border===void 0&&(ge.style.border="none",Zt(o).side==="right"?ge.style.borderLeft="1px solid var(--persona-border)":ge.style.borderRight="1px solid var(--persona-border)"),l&&!we&&We&&R?.border===void 0&&(Zt(o).side==="right"?be.style.borderLeft="1px solid var(--persona-border)":be.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),De.style.display="flex",De.style.flexDirection="column",De.style.flex="1 1 0%",De.style.minHeight="0",De.style.maxHeight="100%",De.style.height="100%",x&&(De.style.overflow="hidden"),be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.height="100%",Wt||(be.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",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",U.style.flexShrink="0"),x&&(Ie||Wt||St)&&!l&&(St||(De.style.padding="var(--persona-panel-inset)"),De.style.background="var(--persona-panel-canvas-bg)"),De.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!x&&!l&&(Tn[gt]??Tn["bottom-right"]).split(" ").forEach(Yt=>De.classList.add(Yt)),f){let kt=o.launcher?.sidebarWidth??"420px";A?De.style.cssText=`
85
85
  position: fixed !important;
86
86
  top: var(--persona-panel-inset) !important;
87
87
  bottom: var(--persona-panel-inset) !important;
@@ -139,23 +139,23 @@ _Details: ${n.message}_`:o}var Ms=e=>({isError:!0,content:[{type:"text",text:e}]
139
139
  border-top: none !important;
140
140
  padding: 8px 16px 12px 16px !important;
141
141
  ${St?"background: transparent !important;":""}
142
- `}if(!x&&!l){let kt="max-height: -moz-available !important; max-height: stretch !important;",Yt=f?"":"padding-top: 1.25em !important;",wa=f?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;De.style.cssText+=kt+Yt+wa}un()};la(),Yo(e,o),qs(e,o),Vs(e,o),Jr=()=>{la(),Yo(e,o),qs(e,o),Vs(e,o),ta?e.style.setProperty("--persona-artifact-welded-outer-radius",ta):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",hd)}),Ve.push(()=>{Vr!==null&&clearTimeout(Vr)});let Mn=null,kn=null;Ve.push(()=>{Mn?.(),Mn=null,kn?.(),kn=null}),Gr&&Ve.push(()=>{Gr?.disconnect(),Gr=null}),Ve.push(()=>{Yr?.(),Yr=null,rl(),wt&&(wt.remove(),wt=null),et?.element.style.removeProperty("width"),et?.element.style.removeProperty("maxWidth")}),Z&&Ve.push(()=>{Ke!==null&&(cancelAnimationFrame(Ke),Ke=null),Be?.destroy(),Be=null,Ne?.destroy(),Ne=null,pe=null});let Bo=null,vd=()=>{Bo&&(Bo(),Bo=null),o.colorScheme==="auto"&&(Bo=Ir(()=>{Yo(e,o)}))};vd(),Ve.push(()=>{Bo&&(Bo(),Bo=null)}),Ve.push(a);let ca=o.features?.streamAnimation;if(ca?.type&&ca.type!=="none"){let l=Or(ca.type,ca.plugins);l&&(xi(l,e),Ve.push(()=>vg(e)))}let da=_g(Ct),Oo=null,$,sl=l=>{if(!$)return;let f=l??$.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?Oa(f):null;h?da.render(h,$,Ce,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(x=>x.role==="user")?da.render([],$,Ce,f):da.render(o.suggestionChips,$,Ce,f,o.suggestionChipsConfig)},bn=!1,Do=ig(),dr=new Map,No=new Map,to=new Map,al=0,om=$n()!==null,tn=fi(),ln=0,no=null,cn=!1,pa=!1,oo=0,vn=null,Fo=null,il=!1,ua=!1,ll=null,Zr=!0,cl=!1,dl=null,rm=4,ga=24,sm=80,pl=new Map,Ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},xd=o.voiceRecognition?.autoResume??!1,On=l=>{i.emit("voice:state",{active:Ye.active,source:l,timestamp:Date.now()})},xn=()=>{C(l=>({...l,voiceState:{active:Ye.active,timestamp:Date.now(),manuallyDeactivated:Ye.manuallyDeactivated}}))},am=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=Nc(c.voiceState),f=!!l.active,h=Number(l.timestamp??0);Ye.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-h<Tv&&setTimeout(()=>{Ye.active||(Ye.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Ye.active=$.isVoiceActive(),On("restore"),$.isVoiceActive()&&mr()}):ya("restore"))},1e3)},im=()=>$?rf($.getMessages()).filter(l=>!l.__skipPersist):[],fa=null,Cd=(l,f)=>{typeof console<"u"&&console.error(l,f)},ul=(l,f)=>{let h=()=>{try{let X=l();return!X||typeof X.then!="function"?null:Promise.resolve(X).catch(F=>{Cd(f,F)})}catch(X){return Cd(f,X),null}},x=fa,A=x?x.then(()=>h()??void 0):h();if(!A)return;let R=A.finally(()=>{fa===R&&(fa=null)});fa=R};function gl(l){if(!d?.save)return;let h={messages:l?rf(l):$?im():[],metadata:c,artifacts:hn.artifacts,selectedArtifactId:hn.selectedId};ul(()=>d.save(h),"[AgentWidget] Failed to persist state:")}let pr=null,wd=()=>De.querySelector("#persona-scroll-container")||ce,es=()=>{pr!==null&&(cancelAnimationFrame(pr),pr=null),cn=!1},Ad=()=>{no!==null&&(cancelAnimationFrame(no),no=null),pa=!1,es()},lm=()=>bn&&ml()&&(Xt()!=="anchor-top"||od()),fl=()=>{let l=Ro()||"Jump to latest",f=lm();Pt.toggleAttribute("data-persona-scroll-to-bottom-streaming",f),oo>0?(Io.textContent=String(oo),Io.style.display="",Pt.setAttribute("aria-label",`${l} (${oo} new)`)):(Io.textContent="",Io.style.display="none",Pt.setAttribute("aria-label",f?`${l} (response streaming below)`:l))},Sd=()=>{oo!==0&&(oo=0,fl())},ml=()=>Qn()?!tn.isFollowing():!Eo(ce,ga),nn=()=>{if(!Zs()||ze){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==ge&&ge.appendChild(Pt),ar();let f=In(ce)>0&&ml();f?fl():Sd(),Pt.style.display=f?"":"none"},ts=()=>{tn.pause()&&(Ad(),nn())},ro=()=>{tn.resume(),Sd(),nn()},so=(l=!1)=>{Qn()&&tn.isFollowing()&&(!l&&!bn||(no!==null&&(cancelAnimationFrame(no),no=null),pa=!0,no=requestAnimationFrame(()=>{no=null,pa=!1,tn.isFollowing()&&cm(wd(),l?220:140)})))},Td=(l,f,h,x=()=>!0)=>{let A=l.scrollTop,R=f(),X=R-A;if(es(),Math.abs(X)<1){cn=!0,l.scrollTop=R,ln=l.scrollTop,cn=!1;return}let F=performance.now();cn=!0;let J=fe=>1-Math.pow(1-fe,3),se=fe=>{if(!x()){es();return}let re=f();re!==R&&(R=re,X=R-A);let we=fe-F,Ge=Math.min(we/h,1),gt=J(Ge),ot=A+X*gt;l.scrollTop=ot,ln=l.scrollTop,Ge<1?pr=requestAnimationFrame(se):(l.scrollTop=R,ln=l.scrollTop,pr=null,cn=!1)};pr=requestAnimationFrame(se)},cm=(l,f=500)=>{let h=In(l)-l.scrollTop;if(Math.abs(h)<1){ln=l.scrollTop;return}if(Math.abs(h)>=sm){es(),cn=!0,l.scrollTop=In(l),ln=l.scrollTop,cn=!1;return}Td(l,()=>In(l),f,()=>tn.isFollowing())},Ed=()=>{let l=wd();cn=!0,l.scrollTop=In(l),ln=l.scrollTop,cn=!1,nn()},Md=l=>{let f=0,h=l;for(;h&&h!==ce;)f+=h.offsetTop,h=h.offsetParent;return f},kd=()=>{if(Xf()!=="last-user-turn")return!1;let l=$?.getMessages()??[];if(l.length<2)return!1;let f=[...l].reverse().find(R=>R.role==="user");if(!f)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(f.id):f.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ce.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let A=Math.min(Math.max(0,Md(x)-td()),In(ce));return cn=!0,ce.scrollTop=A,ln=ce.scrollTop,cn=!1,Xt()==="follow"&&!Eo(ce,ga)&&tn.pause(),nn(),!0},Ld=l=>{Yn.style.height=`${Math.max(0,Math.round(l))}px`,vn&&(vn.spacerHeight=Math.max(0,l))},ns=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null),es(),vn=null,Yn.style.height="0px"},dm=l=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=requestAnimationFrame(()=>{Fo=null;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=ce.querySelector(`[data-message-id="${f}"]`);if(!h)return;let x=Md(h),A=vn?.spacerHeight??0,R=ce.scrollHeight-A,{targetScrollTop:X,spacerHeight:F}=ug({anchorOffsetTop:x,topOffset:td(),viewportHeight:ce.clientHeight,contentHeight:R});vn={initialSpacerHeight:F,contentHeightAtAnchor:R,spacerHeight:F},Ld(F),Td(ce,()=>X,220)})},pm=()=>{if(Qn()){if(!tn.isFollowing()||Eo(ce,1))return;so(!bn);return}if(vn&&vn.initialSpacerHeight>0){let l=ce.scrollHeight-vn.spacerHeight,f=gg({initialSpacerHeight:vn.initialSpacerHeight,contentHeightAtAnchor:vn.contentHeightAtAnchor,currentContentHeight:l});f!==vn.spacerHeight&&Ld(f)}nn()},um=l=>{let f=Xt();f==="follow"?(ro(),so(!0)):f==="anchor-top"&&(Zr=!1,cl=!0,dm(l))},gm=()=>{if(Xt()==="anchor-top"){if(cl){Zr=!1;return}Zr=!0,ns(),ro(),so(!0)}},fm=l=>{let f=new Map;l.forEach(h=>{let x=pl.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(i.emit("assistant:message",h),!ua&&(Xt()!=="anchor-top"||od())&&ml()&&(oo+=1,fl(),nn(),sd(oo===1?"1 new message below.":`${oo} new messages below.`))),h.role==="assistant"&&x?.streaming&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),pl.clear(),f.forEach((h,x)=>{pl.set(x,h)})},ma=(l,f)=>{let h=f==="user"?"user":"assistant",x=o.layout?.messages?.[h],A=x?.width??"content",R=x?.maxWidth??(A==="full"?"100%":"85%");l.classList.add("persona-message-row"),l.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),l.classList.add(`persona-message-row-${f}`,`persona-message-width-${A}`),l.classList.toggle("persona-justify-end",f==="user"),l.setAttribute("data-message-role",f),l.setAttribute("data-message-width",A),l.style.setProperty("--persona-message-row-max-width",R)},_o=(l,f)=>{let h=document.createElement("div");return h.className="persona-flex",h.id=`wrapper-${l}`,h.setAttribute("data-wrapper-id",l),ma(h,f),h},mm=(l,f,h)=>{let x=document.createElement("div"),R=(()=>{let H=r.find(Ie=>Ie.renderLoadingIndicator);if(H?.renderLoadingIndicator)return H.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),X=(H,Ie)=>Ie==null?!1:typeof Ie=="string"?(H.textContent=Ie,!0):(H.appendChild(Ie),!0),F=new Set,J=new Map,se=new Set,fe=r.some(H=>H.renderAskUserQuestion),re=[],we=[],Ge=o.enableComponentStreaming!==!1,gt=o.approval!==!1,ot=[];if(f.forEach(H=>{F.add(H.id),J.set(H.id,H.role);let Ie=fe&&Un(H),je=gt&&H.variant==="approval"&&!!H.approval,Te=!Ie&&H.role==="assistant"&&!H.variant&&Ge&&Xs(H);!je&&to.has(H.id)&&(l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),to.delete(H.id)),!Te&&No.has(H.id)&&(l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),No.delete(H.id));let Mt=Un(H)?`:${H.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${H.agentMetadata?.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",ft=ag(H,al)+Mt,Vt=Ie||je||Te?null:lg(Do,H.id,ft);if(Vt){x.appendChild(Vt.cloneNode(!0)),Un(H)&&H.toolCall?.id&&H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(se.add(H.toolCall.id),Tr(H,o,Pe.composerOverlay));return}let mt=null,Qt=r.find(Ue=>!!(H.variant==="reasoning"&&Ue.renderReasoning||H.variant==="tool"&&Ue.renderToolCall||!H.variant&&Ue.renderMessage)),Wt=o.layout?.messages;if(Un(H)&&H.agentMetadata?.askUserQuestionAnswered===!0){dr.delete(H.id),l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime");return}if(Cs(H)&&o.features?.suggestReplies?.enabled!==!1)return;if(Un(H)&&o.features?.askUserQuestion?.enabled!==!1){let Ue=r.find(Ft=>typeof Ft.renderAskUserQuestion=="function");if(Ue&&dt.current){let Ft=dr.get(H.id),_t=Ft!==ft,St=null;if(_t){let{payload:tt,complete:Fe}=zn(H),vt=H.id,$t=()=>dt.current?.getMessages().find(un=>un.id===vt);St=Ue.renderAskUserQuestion({message:H,payload:tt,complete:Fe,resolve:un=>{let us=$t();us&&dt.current?.resolveAskUserQuestion(us,un)},dismiss:()=>{let un=$t();un?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(un),dt.current?.resolveAskUserQuestion(un,"(dismissed)"))},config:o})}let pt=Ft!=null;if(_t&&St===null&&!pt){H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(se.add(H.toolCall.id),Tr(H,o,Pe.composerOverlay));return}let yt=_o(H.id,H.role);yt.setAttribute("data-ask-plugin-stub","true"),yt.setAttribute("data-preserve-runtime","true"),x.appendChild(yt),re.push({messageId:H.id,fingerprint:ft,bubble:St});return}else{H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(se.add(H.toolCall.id),Tr(H,o,Pe.composerOverlay));return}}else if(je){let Ue=r.find(pt=>typeof pt.renderApproval=="function")??s,_t=to.get(H.id)!==ft,St=null;if(_t&&Ue?.renderApproval){let pt=H.id,yt=(tt,Fe)=>{let vt=dt.current?.getMessages().find($t=>$t.id===pt);vt?.approval&&(vt.approval.toolType==="webmcp"?dt.current?.resolveWebMcpApproval(vt.id,tt):dt.current?.resolveApproval(vt.approval,tt,Fe))};St=Ue.renderApproval({message:H,defaultRenderer:()=>Ri(H,o),config:o,approve:tt=>yt("approved",tt),deny:tt=>yt("denied",tt)})}if(_t&&St===null)l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),to.delete(H.id),mt=Ri(H,o);else{let pt=_o(H.id,H.role);pt.setAttribute("data-approval-plugin-stub","true"),pt.setAttribute("data-preserve-runtime","true"),x.appendChild(pt),ot.push({messageId:H.id,fingerprint:ft,bubble:St});return}}else if(Qt)if(H.variant==="reasoning"&&H.reasoning&&Qt.renderReasoning){if(!ae)return;mt=Qt.renderReasoning({message:H,defaultRenderer:()=>Ec(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&Qt.renderToolCall){if(!me)return;mt=Qt.renderToolCall({message:H,defaultRenderer:()=>kc(H,o),config:o})}else Qt.renderMessage&&(mt=Qt.renderMessage({message:H,defaultRenderer:()=>{let Ue=Fr(H,h,Wt,o.messageActions,oe,{loadingIndicatorRenderer:R,widgetConfig:o});return H.role!=="user"&&Bc(Ue,H,o,$),Ue},config:o}));if(!mt&&Te){let Ue=Ni(H);if(Ue){let Ft=No.get(H.id),_t=Ft!==ft,St=o.wrapComponentDirectiveInBubble!==!1&&Tn.getOptions(Ue.component)?.bubbleChrome!==!1,pt=null;if(_t){let yt=Di(Ue,{config:o,message:H,transform:h});if(yt&&Ue.component==="PersonaArtifactInline"){let tt=yt.hasAttribute("data-artifact-inline")?yt:yt.querySelector("[data-artifact-inline]"),Fe=tt?.getAttribute("data-artifact-inline")??"",vt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Fe):Fe,$t=Fe?l.querySelector(`#wrapper-${H.id}`)?.querySelector(`[data-artifact-inline="${vt}"]`)??null:null;tt&&$t&&$t!==tt&&eg($t)&&(tt===yt?yt=$t:tt.replaceWith($t))}if(yt)if(St){let tt=document.createElement("div");if(tt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),tt.id=`bubble-${H.id}`,tt.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Fe=document.createElement("div");Fe.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Fe.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),tt.appendChild(Fe)}tt.appendChild(yt),pt=tt}else{let tt=document.createElement("div");if(tt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",tt.id=`bubble-${H.id}`,tt.setAttribute("data-message-id",H.id),tt.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Fe=document.createElement("div");Fe.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Fe.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),tt.appendChild(Fe)}tt.appendChild(yt),pt=tt}}if(pt||Ft!=null){let yt=_o(H.id,H.role);yt.setAttribute("data-component-directive-stub","true"),yt.setAttribute("data-preserve-runtime","true"),x.appendChild(yt),we.push({messageId:H.id,fingerprint:ft,bubble:pt});return}}}if(!mt)if(H.variant==="reasoning"&&H.reasoning){if(!ae)return;mt=Ec(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!me)return;mt=kc(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;mt=Ri(H,o)}else{let Ue=o.layout?.messages;Ue?.renderUserMessage&&H.role==="user"?mt=Ue.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):Ue?.renderAssistantMessage&&H.role==="assistant"?mt=Ue.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):mt=Fr(H,h,Ue,o.messageActions,oe,{loadingIndicatorRenderer:R,widgetConfig:o}),H.role!=="user"&&mt&&Bc(mt,H,o,$)}let We=_o(H.id,H.role);We.appendChild(mt),cg(Do,H.id,ft,We),x.appendChild(We)}),Pe.composerOverlay&&Pe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ie=>{let je=Ie.getAttribute("data-persona-ask-sheet-for");je&&!se.has(je)&&fo(Pe.composerOverlay,je)}),o.features?.toolCallDisplay?.grouped){let H=[],Ie=[],je=o.features.toolCallDisplay.groupedMode==="summary";f.forEach(Te=>{if(Te.variant==="tool"&&Te.toolCall&&me){Ie.push(Te);return}Te.variant==="reasoning"&&!ae||((Ie.length>1||je&&Ie.length>0)&&H.push(Ie),Ie=[])}),(Ie.length>1||je&&Ie.length>0)&&H.push(Ie),H.forEach(Te=>{let Mt=Te.map(Ue=>Array.from(x.children).find(Ft=>Ft instanceof HTMLElement&&Ft.getAttribute("data-wrapper-id")===Ue.id)).filter(Ue=>!!Ue);if(Mt.length<(je?1:2))return;let ft=_o(`tool-group-${Te[0].id}`,"assistant");ft.setAttribute("data-persona-tool-group-row","true");let Vt=document.createElement("div");Vt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Vt.setAttribute("data-persona-tool-group","true");let mt=document.createElement("div");mt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mt.id=`tool-group-summary-${Te[0].id}`;let Qt=`Called ${Te.length} ${Te.length===1?"tool":"tools"}`,Wt=o.toolCall?.renderGroupedSummary?.({messages:Te,toolCalls:Te.map(Ue=>Ue.toolCall).filter(Ue=>!!Ue),defaultSummary:Qt,config:o});X(mt,Wt)||(mt.textContent=Qt);let We=document.createElement("div");We.className="persona-tool-group-stack persona-flex persona-flex-col",We.id=`tool-group-stack-${Te[0].id}`,We.setAttribute("data-persona-tool-group-stack","true"),Vt.appendChild(mt),je||Vt.appendChild(We),ft.appendChild(Vt),Mt[0].before(ft),Mt.forEach((Ue,Ft)=>{if(je){Ue.remove();return}Ue.style.setProperty("--persona-message-row-max-width","100%");let _t=document.createElement("div");_t.className="persona-tool-group-item persona-relative",_t.setAttribute("data-persona-tool-group-item","true"),Ft<Mt.length-1&&_t.setAttribute("data-persona-tool-group-connector","true"),_t.appendChild(Ue),We.appendChild(_t)})})}dg(Do,F);let on=f.some(H=>H.role==="assistant"&&H.streaming),Et=f[f.length-1],It=Et?.role==="assistant"&&!Et.streaming&&Et.variant!=="approval";if(bn&&f.some(H=>H.role==="user")&&!on&&!It){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:tr},Ie=r.find(Te=>Te.renderLoadingIndicator),je=null;if(Ie?.renderLoadingIndicator&&(je=Ie.renderLoadingIndicator(H)),je===null&&o.loadingIndicator?.render&&(je=o.loadingIndicator.render(H)),je===null&&(je=tr()),je){let Te=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1;Te.className=Mt?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Te.setAttribute("data-typing-indicator","true"),Te.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Te.appendChild(je);let ft=_o("typing-indicator","assistant");ft.appendChild(Te),x.appendChild(ft)}}if(!bn&&f.length>0){let H=f[f.length-1],Ie={config:o,lastMessage:H,messageCount:f.length},je=r.find(Mt=>Mt.renderIdleIndicator),Te=null;if(je?.renderIdleIndicator&&(Te=je.renderIdleIndicator(Ie)),Te===null&&o.loadingIndicator?.renderIdle&&(Te=o.loadingIndicator.renderIdle(Ie)),Te){let Mt=document.createElement("div"),ft=o.loadingIndicator?.showBubble!==!1;Mt.className=ft?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild(Te);let Vt=_o("idle-indicator","assistant");Vt.appendChild(Mt),x.appendChild(Vt)}}if(Rp(x),gi(l,x),Hl(l),re.length>0)for(let{messageId:H,fingerprint:Ie,bubble:je}of re){let Te=l.querySelector(`#wrapper-${H}`);Te&&(ma(Te,J.get(H)??"assistant"),je!==null&&(Te.replaceChildren(je),Te.setAttribute("data-bubble-fp",Ie),dr.set(H,Ie)))}if(dr.size>0)for(let H of dr.keys())F.has(H)||dr.delete(H);if(we.length>0)for(let{messageId:H,fingerprint:Ie,bubble:je}of we){let Te=l.querySelector(`#wrapper-${H}`);Te&&(ma(Te,J.get(H)??"assistant"),je!==null&&(Te.replaceChildren(je),Te.setAttribute("data-bubble-fp",Ie),No.set(H,Ie)))}if(No.size>0)for(let H of No.keys())F.has(H)||No.delete(H);if(ot.length>0)for(let{messageId:H,fingerprint:Ie,bubble:je}of ot){let Te=l.querySelector(`#wrapper-${H}`);Te&&(ma(Te,J.get(H)??"assistant"),je!==null&&(Te.replaceChildren(je),Te.setAttribute("data-bubble-fp",Ie),to.set(H,Ie)))}if(to.size>0)for(let H of to.keys())F.has(H)||to.delete(H)},os=(l,f,h)=>{mm(l,f,h),gd()},rs=null,hm=()=>{if(rs)return;let l=h=>{let x=h.composedPath();x.includes(De)||Qe&&x.includes(Qe)||ut(!1,"user")};rs=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},Pd=()=>{if(!rs)return;(e.ownerDocument??document).removeEventListener("pointerdown",rs,!0),rs=null};Ve.push(()=>Pd());let ss=null,ym=()=>{if(ss)return;let l=h=>{h.key==="Escape"&&(h.isComposing||ut(!1,"user"))};ss=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},Rd=()=>{if(!ss)return;(e.ownerDocument??document).removeEventListener("keydown",ss,!0),ss=null};Ve.push(()=>Rd());let as=!1,Id=new Set,bm=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},ur=()=>{if(!Y())return;let l=Pe.peekBanner,f=Pe.peekTextNode;if(!l||!f)return;if(N){l.classList.remove("persona-pill-peek--visible");return}let h=$?.getMessages()??[],x;for(let Et=h.length-1;Et>=0;Et--){let It=h[Et];if(It.role==="assistant"&&It.content){x=It;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let A=x.content,R=!!x.streaming,X=bm(),F=yi(X),J=F.type!=="none"?Or(F.type,X?.plugins):null,se=J?.isAnimating?.(x)===!0,fe=J!==null&&(R||se);fe&&J&&!Id.has(J.name)&&(xi(J,e),Id.add(J.name));let re=fe&&J?.containerClass?J.containerClass:null,we=f.dataset.personaPeekStreamClass??null;we&&we!==re&&(f.classList.remove(we),delete f.dataset.personaPeekStreamClass),re&&we!==re&&(f.classList.add(re),f.dataset.personaPeekStreamClass=re),fe?(f.style.setProperty("--persona-stream-step",`${F.speed}ms`),f.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Ge=fe?bi(A,F.buffer,J,x,R):A;if(fe&&F.placeholder==="skeleton"&&R&&(!Ge||!Ge.trim())){let Et=document.createElement("div"),It=Fs();It.classList.add("persona-pill-peek__skeleton"),Et.appendChild(It),gi(f,Et)}else{let Et=Math.max(0,Ge.length-100),It=Ge.length>100?Ge.slice(-100):Ge,H=Pn(It);if(!fe||!J){let Ie=Ge.length>100?`\u2026${It}`:It;f.textContent!==Ie&&(f.textContent=Ie)}else{let Ie=H;(J.wrap==="char"||J.wrap==="word")&&(Ie=Ns(H,J.wrap,`peek-${x.id}`,{skipTags:J.skipTags,startIndex:Et}));let je=document.createElement("div");if(je.innerHTML=Ie,J.useCaret&&It.length>0){let Te=vi(),Mt=je.querySelectorAll(".persona-stream-char, .persona-stream-word"),ft=Mt[Mt.length-1];ft?.parentNode?ft.parentNode.insertBefore(Te,ft.nextSibling):je.appendChild(Te)}gi(f,je),J.onAfterRender?.({container:f,bubble:l,messageId:x.id,message:x,speed:F.speed,duration:F.duration})}}let on=bn||as;l.classList.toggle("persona-pill-peek--visible",on)};if(Y()){let l=Pe.peekBanner;if(l){let x=A=>{A.preventDefault(),A.stopPropagation(),ut(!0,"user")};l.addEventListener("pointerdown",x),Ve.push(()=>{l.removeEventListener("pointerdown",x)})}let f=()=>{as||(as=!0,ur())},h=()=>{as&&(as=!1,ur())};be.addEventListener("pointerenter",f),be.addEventListener("pointerleave",h),Ve.push(()=>{be.removeEventListener("pointerenter",f),be.removeEventListener("pointerleave",h)}),Qe&&(Qe.addEventListener("pointerenter",f),Qe.addEventListener("pointerleave",h),Ve.push(()=>{Qe.removeEventListener("pointerenter",f),Qe.removeEventListener("pointerleave",h)}))}let vm=l=>{let f=o.launcher?.composerBar??{},h=f.expandedSize??"anchored",x=f.bottomOffset??"16px",A=f.collapsedMaxWidth,R=f.expandedMaxWidth??"880px",X=f.expandedTopOffset??"5vh",F=f.modalMaxWidth??"880px",J=f.modalMaxHeight??"min(90vh, 800px)",se="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",re=De.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",Qe){let we=Qe.style;we.bottom=x,we.width=A??""}if(l&&h!=="fullscreen"){if(h==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=F,re.maxWidth=se,re.maxHeight=J,re.height=J;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${x} + ${fe})`,re.top=X,re.width=R,re.maxWidth=se}},is=()=>{if(!D())return;if(Y()){let se=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=N?"expanded":"collapsed";De.dataset.state=fe,De.dataset.expandedSize=se,Qe&&(Qe.dataset.state=fe,Qe.dataset.expandedSize=se),De.style.removeProperty("display"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),vm(N),ge.style.display=N?"flex":"none",la(),N?(hm(),ym()):(Pd(),Rd()),ur();return}let l=Lt(o),f=e.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,A=f.innerWidth<=h,R=x&&A&&S,X=Zt(o).reveal;N?(De.style.removeProperty("display"),De.style.display=l?"flex":"",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0"),be.classList.add("persona-scale-100","persona-opacity-100"),Ot?Ot.element.style.display="none":qt&&(qt.style.display="none")):(l?l&&(X==="overlay"||X==="push")&&!R?(De.style.removeProperty("display"),De.style.display="flex",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.setProperty("display","none","important"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.display="",De.classList.add("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100"),be.classList.add("persona-scale-95","persona-opacity-0")),Ot?Ot.element.style.display=l?"none":"":qt&&(qt.style.display=l?"none":""))},ut=(l,f="user")=>{if(!D()||N===l)return;let h=N;N=l,is();let x=(()=>{let R=o.launcher?.sidebarMode??!1,X=e.ownerDocument.defaultView??window,F=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,se=X.innerWidth<=J,fe=Lt(o)&&F&&se,re=Y()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return R||F&&se&&S||fe||re})();if(N&&x){if(!Mn){let R=e.getRootNode(),X=R instanceof ShadowRoot?R.host:e.closest(".persona-host");X&&(Mn=mc(X,o.launcher?.zIndex??zt))}kn||(kn=hc(e.ownerDocument))}else N||(Mn?.(),Mn=null,kn?.(),kn=null);N&&(ds(),kd()||(Xt()==="follow"?so(!0):Ed()));let A={open:N,source:f,timestamp:Date.now()};N&&!h?i.emit("widget:opened",A):!N&&h&&i.emit("widget:closed",A),i.emit("widget:state",{open:N,launcherEnabled:S,voiceActive:Ye.active,streaming:$.isStreaming()})},hl=l=>{st(l?"stop":"send"),G&&(G.disabled=l),da.buttons.forEach(f=>{f.disabled=l}),U.dataset.personaComposerStreaming=l?"true":"false",U.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},yl=()=>{Ye.active||Ce&&Ce.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>yl(),200)});let Wd=()=>{_.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",v.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",Ce.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=ce.querySelector("[data-persona-intro-card]");if(l){let h=o.copy?.showWelcomeCard!==!1;l.style.display=h?"":"none",h?(ce.classList.remove("persona-gap-3"),ce.classList.add("persona-gap-6")):(ce.classList.remove("persona-gap-6"),ce.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!$?.isStreaming()&&(ue.textContent=o.copy?.sendButtonLabel??"Send"),Ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{C(f=>({...f,sessionId:l}))}});let $o=null,xm=()=>{$o==null&&($o=setInterval(()=>{let l=xe.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval($o),$o=null;return}let f=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=Na(f-x))})},100))},bl=(l,f)=>{if(Object.is(l,f))return!0;if(l===null||f===null||typeof l!="object"||typeof f!="object")return!1;if(Array.isArray(l)||Array.isArray(f))return!Array.isArray(l)||!Array.isArray(f)||l.length!==f.length?!1:l.every((X,F)=>bl(X,f[F]));let h=l,x=f,A=Object.keys(h),R=Object.keys(x);return A.length===R.length&&A.every(X=>Object.prototype.hasOwnProperty.call(x,X)&&bl(h[X],x[X]))},Hd=l=>{let{content:f,rawContent:h,llmContent:x,...A}=l;return A},vl=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!Xs(l),Cm=(l,f,h)=>{if(l.length!==f.length)return!1;let x=l[h.index],A=f[h.index];return!x||!A||x.id!==h.id||A.id!==h.id?!1:(!Object.is(x.content,A.content)||!Object.is(x.rawContent,A.rawContent)||!Object.is(x.llmContent,A.llmContent))&&vl(x)&&vl(A)&&bl(Hd(x),Hd(A))},Bd=null,gr=null,jo=null,Dn=null,ha=l=>{Bd=l;let f,h;gr=null;for(let A=l.length-1;A>=0;A-=1){let R=l[A];if(!f&&R.role==="user"&&(f=R),!h&&R.role==="assistant"&&(h=R),!gr&&vl(R)&&(gr={index:A,id:R.id}),f&&h&&gr)break}os(xe,l,Me),cc(xe,hn.artifacts,{suppressTransition:bn}),xm(),sl(l),so(!bn),fm(l),l.length===0&&(ns(),Zr=!0,cl=!1),!il||ua?(il=!0,ll=f?.id??null,dl=h?.id??null):f&&f.id!==ll?(ll=f.id,um(f.id)):h&&h.id!==dl&&gm(),h&&(dl=h.id);let x=Ye.lastUserMessageId;f&&f.id!==x&&(Ye.lastUserMessageId=f.id,i.emit("user:message",f)),Ye.lastUserMessageWasVoice=!!f?.viaVoice,gl(l),ur()},xl=()=>{Dn!==null&&(cancelAnimationFrame(Dn),Dn=null);let l=jo;jo=null,l&&ha(l)},Od=()=>{Dn!==null&&cancelAnimationFrame(Dn),Dn=null,jo=null},wm=l=>{let f=jo??Bd;if(bn&&f&&gr&&Cm(f,l,gr)){jo=l,Dn===null&&(Dn=requestAnimationFrame(()=>{Dn=null;let h=jo;jo=null,h&&ha(h)}));return}if(l.length===0){Od(),ha(l);return}xl(),ha(l)};$=new Pr(o,{onMessagesChanged(l){wm(l)},onStatusChanged(l){let f=o.statusIndicator??{};ht(M,(x=>x==="idle"?f.idleText??Ht.idle:x==="connecting"?f.connectingText??Ht.connecting:x==="connected"?f.connectedText??Ht.connected:x==="error"?f.errorText??Ht.error:x==="paused"?f.pausedText??Ht.paused:x==="resuming"?f.resumingText??Ht.resuming:Ht[x])(l),f,l)},onStreamingChanged(l){l||($?.getMessages().length===0?Od():xl()),bn=l,hl(l),$&&os(xe,$.getMessages(),Me),l||so(!0),nn(),sd(l?"Responding\u2026":"Response complete."),ur()},onVoiceStatusChanged(l){if(i.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":Nn(),mr();break;case"processing":Nn(),Wm();break;case"speaking":Nn(),Hm();break;default:l==="idle"&&$.isBargeInActive()?(Nn(),mr(),G?.setAttribute("aria-label","End voice session")):(Ye.active=!1,Nn(),On("system"),xn());break}},onArtifactsState(l){hn=l,l.artifacts.length===0&&(ir=!1),cc(xe,l.artifacts,{suppressTransition:bn}),Bn(),gl()},onReconnect(l){let{executionId:f,lastEventId:h}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:f,after:h}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:f,after:h,attempt:l.attempt??1}):i.emit("stream:resumed",{executionId:f,after:h})}}),dt.current=$,Ve.push(()=>$.cancel());let Cl=null;if($.onReadAloudChange((l,f)=>{pd=l,ud=f,gd();let h=l??Cl;l&&(Cl=l);let x=h?$.getMessages().find(A=>A.id===h)??null:null;i.emit("message:read-aloud",{messageId:h,message:x,state:f,timestamp:Date.now()}),f==="idle"&&(Cl=null)}),il=!0,o.voiceRecognition?.provider?.type==="runtype")try{$.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&$.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Ne||o.onSSEEvent)&&$.setSSEEventCallback((l,f)=>{o.onSSEEvent?.(l,f),$e?.processEvent(l,f),Ne?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(f)})});let Dd=()=>{o.resume&&typeof o.reconnectStream=="function"&&$.resumeFromHandle(o.resume)};u?u.then(l=>{if(l){if(l.metadata&&(c=Nc(l.metadata),W.syncFromMetadata()),l.messages?.length){ua=!0;try{$.hydrateMessages(l.messages)}finally{ua=!1}}l.artifacts?.length&&$.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>Dd()):Dd();let Nd=()=>{!Y()||N||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ut(!0,"auto")},Am=(l,f)=>l?f?{refs:[...l.refs,...f.refs],finalize:async()=>{let[h,x]=await Promise.allSettled([l.finalize(),f.finalize()]),A=[];return h.status==="fulfilled"?A.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),x.status==="fulfilled"?A.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),Iv(A)}}:l:f,Sm=()=>{let f=Ce.getInlineMessageFields?.();return f&&f.contentSegments.some(x=>x.kind==="mention")?f.contentSegments:void 0},ls=!1,Tm=async l=>{let f=Ce.value.trim(),h=Tt?.hasAttachments()??!1,x=f?await(en?.takeInlineCommand(f)??Promise.resolve(null)):null;if(x?.kind==="action"){Ce.value="",Ce.style.height="auto",cs(),en?.clear();return}let A=en?.collectForSubmit()??null,R=x?.kind==="server"?x.mentions:null,X=Am(A,R),F=x?.kind==="prompt"?x.sendText:f,J=!!A&&A.refs.length>0;if(!F&&!h&&!J&&!R)return;Nd();let se;h&&(se=[],se.push(...Tt.getContentParts()),F&&se.push(bo(F)));let fe=x?.kind==="prompt"?void 0:Sm();Ce.value="",Ce.style.height="auto",cs(),$.sendMessage(F,{contentParts:se,mentions:X??void 0,contentSegments:fe,viaVoice:l?.viaVoice}),h&&Tt.clearAttachments(),A&&en?.clear()},wl=async l=>{if(!ls){ls=!0;try{await Tm(l)}finally{ls=!1}}},Fd=l=>{if(l.preventDefault(),$.isStreaming()){$.cancel(),$e?.reset(),Be?.update();return}ls||wl()},Em=()=>o.features?.composerHistory!==!1,Al={...uc},Sl=!1,cs=()=>{Al={...uc}},Mm=()=>$.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),km=l=>{if(!Ce)return;Sl=!0,Ce.value=l,Ce.dispatchEvent(new Event("input",{bubbles:!0})),Sl=!1;let f=Ce.value.length;Ce.setSelectionRange(f,f)},Lm=l=>{Sl||(l.isComposing||en?.handleInput(l.inputType??void 0),cs())},Pm=l=>{if(Ce&&!(!l.isComposing&&en?.handleKeydown(l))){if(Em()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=Ce.selectionStart===0&&Ce.selectionEnd===0,h=sg({direction:l.key==="ArrowUp"?"up":"down",history:Mm(),currentValue:Ce.value,atStart:f,state:Al});if(Al=h.state,h.handled){l.preventDefault(),h.value!==void 0&&km(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if($.isStreaming()){l.preventDefault();return}if(ls){l.preventDefault();return}cs(),l.preventDefault(),ue.click()}}},_d=l=>{l.key!=="Escape"||l.isComposing||$.isStreaming()&&l.composedPath().includes(ge)&&($.cancel(),$e?.reset(),Be?.update(),cs(),l.preventDefault(),l.stopImmediatePropagation())},Rm=async l=>{if(o.attachments?.enabled!==!0||!Tt)return;let f=kv(l.clipboardData);f.length!==0&&(l.preventDefault(),await Tt.handleFiles(f))},dn=null,Ln=!1,fr=null,At=null,$d=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ya=(l="user")=>{if(Ln||$.isStreaming())return;let f=$d();if(!f)return;dn=new f;let x=(o.voiceRecognition??{}).pauseDuration??2e3;dn.continuous=!0,dn.interimResults=!0,dn.lang="en-US";let A=Ce.value;dn.onresult=R=>{let X="",F="";for(let se=0;se<R.results.length;se++){let fe=R.results[se],re=fe[0].transcript;fe.isFinal?X+=re+" ":F=re}let J=A+X+F;Ce.value=J,fr&&clearTimeout(fr),(X||F)&&(fr=window.setTimeout(()=>{Ce.value.trim()&&dn&&Ln&&(ao(),wl({viaVoice:!0}))},x))},dn.onerror=R=>{R.error!=="no-speech"&&ao()},dn.onend=()=>{if(Ln){let R=Ce.value.trim();R&&R!==A.trim()&&wl({viaVoice:!0}),ao()}};try{if(dn.start(),Ln=!0,Ye.active=!0,l!=="system"&&(Ye.manuallyDeactivated=!1),On(l),xn(),G){let R=o.voiceRecognition??{};At={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:R.iconName??"mic",iconSize:parseFloat(R.iconSize??o.sendButton?.size??"40")||24};let X=R.recordingBackgroundColor,F=R.recordingIconColor,J=R.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=X??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=F??"var(--persona-voice-recording-indicator, #ffffff)",F){let se=G.querySelector("svg");se&&se.setAttribute("stroke",F)}J&&(G.style.borderColor=J),G.setAttribute("aria-label","Stop voice recognition")}}catch{ao("system")}},ao=(l="user")=>{if(Ln){if(Ln=!1,fr&&(clearTimeout(fr),fr=null),dn){try{dn.stop()}catch{}dn=null}if(Ye.active=!1,On(l),xn(),G){if(G.classList.remove("persona-voice-recording"),At){G.style.backgroundColor=At.backgroundColor,G.style.color=At.color,G.style.borderColor=At.borderColor;let f=G.querySelector("svg");f&&f.setAttribute("stroke",At.color||"currentColor"),At=null}G.setAttribute("aria-label","Start voice recognition")}}},Im=(l,f)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=l?.provider?.type==="runtype",A=l?.provider?.type==="custom";if(!(h||x||A))return null;let X=m("div","persona-send-button-wrapper"),F=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button";let J=l?.tooltipText??"Start voice recognition";F.setAttribute("aria-label",J);let se=l?.iconName??"mic",fe=f?.size??"40px",re=l?.iconSize??fe,we=parseFloat(re)||24,Ge=l?.backgroundColor??f?.backgroundColor,gt=l?.iconColor??f?.textColor;F.style.width=re,F.style.height=re,F.style.minWidth=re,F.style.minHeight=re,F.style.fontSize="18px",F.style.lineHeight="1",gt?F.style.color=gt:F.style.color="var(--persona-text, #111827)";let on=ne(se,we,gt||"currentColor",1.5);on?F.appendChild(on):F.textContent="\u{1F3A4}",Ge?F.style.backgroundColor=Ge:F.style.backgroundColor="",l?.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l?.borderColor&&(F.style.borderColor=l.borderColor),l?.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l?.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),X.appendChild(F);let Et=l?.showTooltip??!1;return Nt({anchor:F,trigger:X,text:()=>F.getAttribute("aria-label")??J,enabled:Et}),{micButton:F,micButtonWrapper:X}},Tl=()=>{if(!G||At)return;let l=o.voiceRecognition??{};At={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},El=(l,f)=>{if(!G)return;let h=G.querySelector("svg");h&&h.remove();let x=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=ne(l,x,f,1.5);A&&G.appendChild(A)},ba=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},mr=()=>{if(!G)return;Tl();let l=o.voiceRecognition??{},f=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(ba(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=f??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let A=G.querySelector("svg");A&&A.setAttribute("stroke",h)}x&&(G.style.borderColor=x),G.setAttribute("aria-label","Stop voice recognition")},Wm=()=>{if(!G)return;Tl();let l=o.voiceRecognition??{},f=$.getVoiceInterruptionMode(),h=l.processingIconName??"loader",x=l.processingIconColor??At?.color??"",A=l.processingBackgroundColor??At?.backgroundColor??"",R=l.processingBorderColor??At?.borderColor??"";ba(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=A,G.style.borderColor=R;let X=x||"currentColor";G.style.color=X,El(h,X),G.setAttribute("aria-label","Processing voice input"),f==="none"&&(G.style.cursor="default")},Hm=()=>{if(!G)return;Tl();let l=o.voiceRecognition??{},f=$.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",x=l.speakingIconName??h,A=l.speakingIconColor??(f==="barge-in"?l.recordingIconColor??At?.color??"":At?.color??""),R=l.speakingBackgroundColor??(f==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),X=l.speakingBorderColor??(f==="barge-in"?l.recordingBorderColor??"":At?.borderColor??"");ba(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=R,G.style.borderColor=X;let F=A||"currentColor";G.style.color=F,El(x,F);let J=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",J),f==="none"&&(G.style.cursor="default"),f==="barge-in"&&G.classList.add("persona-voice-recording")},Nn=()=>{G&&(ba(),At&&(G.style.backgroundColor=At.backgroundColor??"",G.style.color=At.color??"",G.style.borderColor=At.borderColor??"",El(At.iconName,At.color||"currentColor"),At=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},va=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=$.getVoiceStatus(),f=$.getVoiceInterruptionMode();if(f==="none"&&(l==="processing"||l==="speaking"))return;if(f==="cancel"&&(l==="processing"||l==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,xn(),On("user"),Nn()});return}$.toggleVoice().then(()=>{Ye.active=$.isVoiceActive(),Ye.manuallyDeactivated=!$.isVoiceActive(),xn(),On("user"),$.isVoiceActive()?mr():Nn()});return}if(Ln){let l=Ce.value.trim();Ye.manuallyDeactivated=!0,xn(),ao("user"),l&&(Ce.value="",Ce.style.height="auto",$.sendMessage(l))}else Ye.manuallyDeactivated=!1,xn(),ya("user")};id=va,G&&(G.addEventListener("click",va),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()&&$.toggleVoice(),Nn()):ao("system"),G&&G.removeEventListener("click",va)}));let Bm=i.on("assistant:complete",()=>{xd&&(Ye.active||Ye.manuallyDeactivated||xd==="assistant"&&!Ye.lastUserMessageWasVoice||setTimeout(()=>{!Ye.active&&!Ye.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Ye.active=$.isVoiceActive(),On("auto"),$.isVoiceActive()&&mr()}):ya("auto"))},600))});Ve.push(Bm);let Om=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});Ve.push(Om);let jd=()=>{ut(!N,"user")},Ot=null,qt=null;if(S&&!Y()){let{instance:l,element:f}=Cc({config:o,plugins:r,onToggle:jd});Ot=l,l||(qt=f)}Ot?e.appendChild(Ot.element):qt&&e.appendChild(qt),is(),sl(),Wd(),hl($.isStreaming()),kd()||(Xt()==="follow"?so(!0):Ed()),am(),j&&(!S||Y()?setTimeout(()=>yl(),0):N&&setTimeout(()=>yl(),200));let ds=()=>{if(Y()){ar(),is();return}let l=Lt(o),f=o.launcher?.sidebarMode??!1,h=l||f||(o.launcher?.fullHeight??!1),x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640,X=x.innerWidth<=R,F=A&&X&&S;try{if(F){Jr(),Xr=ia();return}let J=!1;V&&(V=!1,Jr(),J=!0);let se=ia();if(!J&&se!==Xr&&(Jr(),J=!0),Xr=se,J&&ol(),!S&&!l){be.style.height="",be.style.width="";return}if(!f&&!l){let re=o?.launcher?.width??o?.launcherWidth??sn;be.style.width=re,be.style.maxWidth=re}if(aa(),!h){let fe=x.innerHeight,re=64,we=o.launcher?.heightOffset??0,Ge=Math.max(200,fe-re),gt=Math.min(640,Ge),ot=Math.max(200,gt-we);be.style.height=`${ot}px`}}finally{if(ar(),is(),N&&S){let se=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),fe=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,we=Lt(o)&&re&&se,Ge=fe||re&&se&&S||we;if(Ge&&!kn){let gt=e.getRootNode(),ot=gt instanceof ShadowRoot?gt.host:e.closest(".persona-host");ot&&!Mn&&(Mn=mc(ot,o.launcher?.zIndex??zt)),kn=hc(e.ownerDocument)}else Ge||(Mn?.(),Mn=null,kn?.(),kn=null)}}};ds();let Ud=e.ownerDocument.defaultView??window;if(Ud.addEventListener("resize",ds),Ve.push(()=>Ud.removeEventListener("resize",ds)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{ar()});l.observe(U),Ve.push(()=>l.disconnect())}ln=ce.scrollTop;let zd=In(ce),Dm=()=>{let l=ce.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??ce.ownerDocument.getSelection()},Ml=()=>pg(Dm(),ce),qd=()=>{let l=ce.scrollTop,f=In(ce),h=f<zd;if(zd=f,!Qn()){ln=l,nn();return}let{action:x,nextLastScrollTop:A}=mi({following:tn.isFollowing(),currentScrollTop:l,lastScrollTop:ln,nearBottom:Eo(ce,ga),userScrollThreshold:rm,isAutoScrolling:cn||pa||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ln=A,x==="resume"){Ml()||ro();return}x==="pause"&&ts()};if(ce.addEventListener("scroll",qd,{passive:!0}),Ve.push(()=>ce.removeEventListener("scroll",qd)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{pm(),Hl(xe)});l.observe(xe),l.observe(ce),Ve.push(()=>l.disconnect())}let Vd=()=>{Qn()&&tn.isFollowing()&&Ml()&&ts()},Kd=ce.ownerDocument;Kd.addEventListener("selectionchange",Vd),Ve.push(()=>{Kd.removeEventListener("selectionchange",Vd)});let Nm=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Gd=l=>{nd()&&Qn()&&tn.isFollowing()&&Nm.has(l.key)&&ts()},Jd=l=>{if(!nd()||!Qn()||!tn.isFollowing())return;let f=l.target;f&&f.closest("a, button, [tabindex], input, textarea, select")&&ts()};ce.addEventListener("keydown",Gd),ce.addEventListener("focusin",Jd),Ve.push(()=>{ce.removeEventListener("keydown",Gd),ce.removeEventListener("focusin",Jd)});let Xd=l=>{if(!Qn())return;let f=hi({following:tn.isFollowing(),deltaY:l.deltaY,nearBottom:Eo(ce,ga),resumeWhenNearBottom:!0});f==="pause"?ts():f==="resume"&&!Ml()&&ro()};ce.addEventListener("wheel",Xd,{passive:!0}),Ve.push(()=>ce.removeEventListener("wheel",Xd)),Pt.addEventListener("click",()=>{ns(),ce.scrollTop=ce.scrollHeight,ln=ce.scrollTop,ro(),so(!0),nn()}),Ve.push(()=>Pt.remove()),Ve.push(()=>{Ad(),ns()});let Qd=()=>{E&&(Oo&&(E.removeEventListener("click",Oo),Oo=null),D()?(E.style.display="",Oo=()=>{ut(!1,"user")},E.addEventListener("click",Oo)):E.style.display="none")};Qd(),(()=>{let{clearChatButton:l}=Pe;l&&l.addEventListener("click",()=>{$.clearMessages(),Do.clear(),ro(),fo(Pe.composerOverlay);try{localStorage.removeItem(zr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==zr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(f),d?.clear&&ul(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},W.syncFromMetadata(),Ne?.clear(),$e?.reset(),Be?.update()})})(),Q&&Q.addEventListener("submit",Fd);let Yd=[["keydown",Pm],["input",Lm],["paste",Rm],["focus",Zf]],Zd=l=>{if(l)for(let[f,h]of Yd)l.addEventListener(f,h)},ep=l=>{if(l)for(let[f,h]of Yd)l.removeEventListener(f,h)};Zd(Ce),en?.onComposerSwap((l,f)=>{ep(f),Ce=l,Zd(l)});let tp=e.ownerDocument??document;tp.addEventListener("keydown",_d,!0);let np="persona-attachment-drop-active",ps=0,kl=()=>{ps=0,ge.classList.remove(np)},hr=()=>o.attachments?.enabled===!0&&Tt!==null,op=l=>{!$i(l.dataTransfer)||!hr()||(ps++,ps===1&&ge.classList.add(np))},rp=l=>{!$i(l.dataTransfer)||!hr()||(ps--,ps<=0&&kl())},sp=l=>{!$i(l.dataTransfer)||!hr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},ap=l=>{if(!$i(l.dataTransfer)||!hr())return;l.preventDefault(),l.stopPropagation(),kl();let f=Array.from(l.dataTransfer.files??[]);f.length!==0&&Tt.handleFiles(f)},io=!0;ge.addEventListener("dragenter",op,io),ge.addEventListener("dragleave",rp,io),e.addEventListener("dragover",sp,io),e.addEventListener("drop",ap,io);let xa=e.ownerDocument,ip=l=>{hr()&&l.preventDefault()},lp=l=>{hr()&&l.preventDefault()};xa.addEventListener("dragover",ip),xa.addEventListener("drop",lp),Ve.push(()=>{Q&&Q.removeEventListener("submit",Fd),ep(Ce),tp.removeEventListener("keydown",_d,!0),en?.destroy()}),Ve.push(()=>{ge.removeEventListener("dragenter",op,io),ge.removeEventListener("dragleave",rp,io),e.removeEventListener("dragover",sp,io),e.removeEventListener("drop",ap,io),xa.removeEventListener("dragover",ip),xa.removeEventListener("drop",lp),kl()}),Ve.push(()=>{$.cancel()}),Ot?Ve.push(()=>{Ot?.destroy()}):qt&&Ve.push(()=>{qt?.remove()});let Rt={update(l){let f=o.toolCall,h=o.messageActions,x=o.layout?.messages,A=o.colorScheme,R=o.loadingIndicator,X=o.iterationDisplay,F=o.features?.showReasoning,J=o.features?.showToolCalls,se=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=Hi(o,l),la(),Yo(e,o),qs(e,o),Vs(e,o),Bn(),o.colorScheme!==A&&vd();let we=Ks.getForInstance(o.plugins);r.length=0,r.push(...we),S=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,ae=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,de=o.features?.scrollToBottom??{};let Ge=Xt();ee=o.features?.scrollBehavior??{},Ge!==Xt()&&(ns(),ro()),ad(),nn();let gt=Z;if(Z=o.features?.showEventStreamToggle??!1,Z&&!gt){if(Ne||(pe=new Us(ye),Ne=new js(ke,pe),$e=$e??new zs,pe.open().then(()=>Ne?.restore()).catch(()=>{}),$.setSSEEventCallback((te,Xe)=>{o.onSSEEvent?.(te,Xe),$e?.processEvent(te,Xe),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Xe)})})),!nt&&O){let te=o.features?.eventStream?.classNames,Xe="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(te?.toggleButton?" "+te.toggleButton:"");nt=m("button",Xe),nt.style.width="28px",nt.style.height="28px",nt.style.color=Gt.actionIconColor,nt.type="button",nt.setAttribute("aria-label","Event Stream"),nt.title="Event Stream";let bt=ne("activity","18px","currentColor",1.5);bt&&nt.appendChild(bt);let rt=Pe.clearChatButtonWrapper,at=Pe.closeButtonWrapper,jt=rt||at;jt&&jt.parentNode===O?O.insertBefore(nt,jt):O.appendChild(nt),nt.addEventListener("click",()=>{ze?Kr():Zi()})}}else!Z&&gt&&(Kr(),nt&&(nt.remove(),nt=null),Ne?.clear(),pe?.destroy(),Ne=null,pe=null,$e?.reset(),$e=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&qt&&(qt.remove(),qt=null),o.launcher?.enabled!==!1&&!Ot&&!qt){let{instance:te,element:Xe}=Cc({config:o,plugins:r,onToggle:jd});Ot=te,te||(qt=Xe),e.appendChild(Xe)}Ot&&Ot.update(o),B&&o.launcher?.title!==void 0&&(B.textContent=o.launcher.title),K&&o.launcher?.subtitle!==void 0&&(K.textContent=o.launcher.subtitle);let ot=o.layout?.header;if(ot?.layout!==z&&O){let te=ot?Dr(o,ot,{showClose:D(),onClose:()=>ut(!1,"user")}):Jn({config:o,showClose:D(),onClose:()=>ut(!1,"user")});lt.replaceHeader(te),O=lt.header.element,L=lt.header.iconHolder,B=lt.header.headerTitle,K=lt.header.headerSubtitle,E=lt.header.closeButton,z=ot?.layout}else if(ot){if(L&&(L.style.display=ot.showIcon===!1?"none":""),B&&(B.style.display=ot.showTitle===!1?"none":""),K&&(K.style.display=ot.showSubtitle===!1?"none":""),E){let te=D()&&ot.showCloseButton!==!1;E.style.display=te?"":"none"}if(Pe.clearChatButtonWrapper){let te=ot.showClearChat;if(te!==void 0){Pe.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Xe}=Pe;Xe&&!Xe.classList.contains("persona-absolute")&&(te?Xe.classList.remove("persona-ml-auto"):Xe.classList.add("persona-ml-auto"))}}}let Et=o.layout?.showHeader!==!1;O&&(O.style.display=Et?"":"none");let It=o.layout?.showFooter!==!1;U&&(U.style.display=It?"":"none"),ar(),nn(),S!==w?S?ut(I,"auto"):(N=!0,is()):I!==q&&ut(I,"auto"),q=I,w=S,ds(),Qd();let je=JSON.stringify(o.toolCall)!==JSON.stringify(f),Te=JSON.stringify(o.messageActions)!==JSON.stringify(h),Mt=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),ft=o.loadingIndicator?.render!==R?.render||o.loadingIndicator?.renderIdle!==R?.renderIdle||o.loadingIndicator?.showBubble!==R?.showBubble,Vt=o.iterationDisplay!==X,mt=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(J??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(je||Te||Mt||ft||Vt||mt)&&$&&(al++,os(xe,$.getMessages(),Me));let Wt=o.features?.streamAnimation?.type;if(Wt!==re&&Wt&&Wt!=="none"){let te=Or(Wt,o.features?.streamAnimation?.plugins);te&&xi(te,e)}let We=o.launcher??{},Ue=We.headerIconHidden??!1,Ft=o.layout?.header?.showIcon,_t=Ue||Ft===!1,St=We.headerIconName,pt=We.headerIconSize??"48px";if(L){let te=ge.querySelector(".persona-border-b-persona-divider"),Xe=te?.querySelector(".persona-flex-col");if(_t)L.style.display="none",te&&Xe&&!te.contains(Xe)&&te.insertBefore(Xe,te.firstChild);else{if(L.style.display="",L.style.height=pt,L.style.width=pt,te&&Xe&&(te.contains(L)?L.nextSibling!==Xe&&(L.remove(),te.insertBefore(L,Xe)):te.insertBefore(L,Xe)),St){let rt=parseFloat(pt)||24,at=ne(St,rt*.6,"currentColor",1);at?L.replaceChildren(at):L.textContent=We.agentIconText??"\u{1F4AC}"}else if(We.iconUrl){let rt=L.querySelector("img");if(rt)rt.src=We.iconUrl,rt.style.height=pt,rt.style.width=pt;else{let at=document.createElement("img");at.src=We.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=pt,at.style.width=pt,L.replaceChildren(at)}}else{let rt=L.querySelector("svg"),at=L.querySelector("img");(rt||at)&&L.replaceChildren(),L.textContent=We.agentIconText??"\u{1F4AC}"}let bt=L.querySelector("img");bt&&(bt.style.height=pt,bt.style.width=pt)}}let yt=o.layout?.header?.showTitle,tt=o.layout?.header?.showSubtitle;if(B&&(B.style.display=yt===!1?"none":""),K&&(K.style.display=tt===!1?"none":""),E){let te=D()&&o.layout?.header?.showCloseButton!==!1;E.style.display=te?"":"none";let Xe=We.closeButtonSize??"32px",bt=We.closeButtonPlacement??"inline";E.style.height=Xe,E.style.width=Xe;let{closeButtonWrapper:rt}=Pe,at=bt==="top-right",jt=rt?.classList.contains("persona-absolute");if(rt&&at!==jt)if(rt.remove(),at)rt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ge.style.position="relative",ge.appendChild(rt);else{let co=We.clearChat?.placement??"inline",fs=We.clearChat?.enabled??!0;rt.className=fs&&co==="inline"?"":"persona-ml-auto";let cp=ge.querySelector(".persona-border-b-persona-divider");cp&&cp.appendChild(rt)}if(E.style.color=We.closeButtonColor||Gt.actionIconColor,We.closeButtonBackgroundColor?(E.style.backgroundColor=We.closeButtonBackgroundColor,E.classList.remove("hover:persona-bg-gray-100")):(E.style.backgroundColor="",E.classList.add("hover:persona-bg-gray-100")),We.closeButtonBorderWidth||We.closeButtonBorderColor){let co=We.closeButtonBorderWidth||"0px",fs=We.closeButtonBorderColor||"transparent";E.style.border=`${co} solid ${fs}`,E.classList.remove("persona-border-none")}else E.style.border="",E.classList.add("persona-border-none");We.closeButtonBorderRadius?(E.style.borderRadius=We.closeButtonBorderRadius,E.classList.remove("persona-rounded-full")):(E.style.borderRadius="",E.classList.add("persona-rounded-full")),We.closeButtonPaddingX?(E.style.paddingLeft=We.closeButtonPaddingX,E.style.paddingRight=We.closeButtonPaddingX):(E.style.paddingLeft="",E.style.paddingRight=""),We.closeButtonPaddingY?(E.style.paddingTop=We.closeButtonPaddingY,E.style.paddingBottom=We.closeButtonPaddingY):(E.style.paddingTop="",E.style.paddingBottom="");let rn=We.closeButtonIconName??"x",Cn=We.closeButtonIconText??"\xD7";E.innerHTML="";let Dt=ne(rn,"28px","currentColor",1);Dt?(Dt.style.display="block",E.appendChild(Dt)):E.textContent=Cn;let Ut=We.closeButtonTooltipText??"Close chat",_n=We.closeButtonShowTooltip??!0;E.setAttribute("aria-label",Ut),rt&&Nt({anchor:E,trigger:rt,text:()=>E?.getAttribute("aria-label")??Ut,enabled:_n})}let{clearChatButton:Fe,clearChatButtonWrapper:vt}=Pe;if(Fe){let te=We.clearChat??{},Xe=te.enabled??!0,bt=o.layout?.header?.showClearChat,rt=bt!==void 0?bt:Xe,at=te.placement??"inline";if(vt){vt.style.display=rt?"":"none";let{closeButtonWrapper:jt}=Pe;!Y()&&jt&&!jt.classList.contains("persona-absolute")&&(rt?jt.classList.remove("persona-ml-auto"):jt.classList.add("persona-ml-auto"));let rn=at==="top-right",Cn=vt.classList.contains("persona-absolute");if(!Y()&&rn!==Cn&&rt){if(vt.remove(),rn)vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px",ge.style.position="relative",ge.appendChild(vt);else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let Ut=ge.querySelector(".persona-border-b-persona-divider"),_n=Pe.closeButtonWrapper;Ut&&_n&&_n.parentElement===Ut?Ut.insertBefore(vt,_n):Ut&&Ut.appendChild(vt)}let Dt=Pe.closeButtonWrapper;Dt&&!Dt.classList.contains("persona-absolute")&&(rn?Dt.classList.add("persona-ml-auto"):Dt.classList.remove("persona-ml-auto"))}}if(rt){if(!Y()){let co=te.size??"32px";Fe.style.height=co,Fe.style.width=co}let jt=te.iconName??"refresh-cw",rn=te.iconColor??"";Fe.style.color=rn||Gt.actionIconColor,Fe.innerHTML="";let Cn=Y()?"14px":"20px",Dt=ne(jt,Cn,"currentColor",1);if(Dt&&(Dt.style.display="block",Fe.appendChild(Dt)),te.backgroundColor?(Fe.style.backgroundColor=te.backgroundColor,Fe.classList.remove("hover:persona-bg-gray-100")):(Fe.style.backgroundColor="",Fe.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let co=te.borderWidth||"0px",fs=te.borderColor||"transparent";Fe.style.border=`${co} solid ${fs}`,Fe.classList.remove("persona-border-none")}else Fe.style.border="",Fe.classList.add("persona-border-none");te.borderRadius?(Fe.style.borderRadius=te.borderRadius,Fe.classList.remove("persona-rounded-full")):(Fe.style.borderRadius="",Fe.classList.add("persona-rounded-full")),te.paddingX?(Fe.style.paddingLeft=te.paddingX,Fe.style.paddingRight=te.paddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),te.paddingY?(Fe.style.paddingTop=te.paddingY,Fe.style.paddingBottom=te.paddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom="");let Ut=te.tooltipText??"Clear chat",_n=te.showTooltip??!0;Fe.setAttribute("aria-label",Ut),vt&&Nt({anchor:Fe,trigger:vt,text:()=>Fe?.getAttribute("aria-label")??Ut,enabled:_n})}}let $t=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Gs],un=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[sr.message,sr.messageAndClick];W=Js({parsers:$t,handlers:un,getSessionMetadata:y,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null}),Me=sf(o,W,Ae),$.updateConfig(o),os(xe,$.getMessages(),Me),sl(),Wd(),hl($.isStreaming());let us=o.voiceRecognition?.enabled===!0,Ca=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),kt=o.voiceRecognition?.provider?.type==="runtype";if(us&&(Ca||kt))if(!G||!qe){let te=Im(o.voiceRecognition,o.sendButton);te&&(G=te.micButton,qe=te.micButtonWrapper,Je.insertBefore(qe,mn),G.addEventListener("click",va),G.disabled=$.isStreaming())}else{let te=o.voiceRecognition??{},Xe=o.sendButton??{},bt=te.iconName??"mic",rt=Xe.size??"40px",at=te.iconSize??rt,jt=parseFloat(at)||24;G.style.width=at,G.style.height=at,G.style.minWidth=at,G.style.minHeight=at;let rn=te.iconColor??Xe.textColor;G.innerHTML="";let Cn=ne(bt,jt,rn||"currentColor",1.5);Cn?G.appendChild(Cn):G.textContent="\u{1F3A4}";let Dt=te.backgroundColor??Xe.backgroundColor;Dt?G.style.backgroundColor=Dt:G.style.backgroundColor="",rn?G.style.color=rn:G.style.color="var(--persona-text, #111827)",te.borderWidth?(G.style.borderWidth=te.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),te.borderColor?G.style.borderColor=te.borderColor:G.style.borderColor="",te.paddingX?(G.style.paddingLeft=te.paddingX,G.style.paddingRight=te.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),te.paddingY?(G.style.paddingTop=te.paddingY,G.style.paddingBottom=te.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let Ut=te.tooltipText??"Start voice recognition",_n=te.showTooltip??!1;G.setAttribute("aria-label",Ut),qe&&Nt({anchor:G,trigger:qe,text:()=>G?.getAttribute("aria-label")??Ut,enabled:_n}),qe.style.display="",G.disabled=$.isStreaming()}else G&&qe&&(qe.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()&&$.toggleVoice():Ln&&ao());if(o.attachments?.enabled===!0){if(!He||!Se){let te=o.attachments??{},bt=(o.sendButton??{}).size??"40px";Ze||(Ze=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ze.style.display="none",Q.insertBefore(Ze,Ce)),Re||(Re=document.createElement("input"),Re.type="file",Re.accept=(te.allowedTypes??Vn).join(","),Re.multiple=(te.maxFiles??4)>1,Re.style.display="none",Re.setAttribute("aria-label","Attach files"),Q.insertBefore(Re,Ce)),He=m("div","persona-send-button-wrapper"),Se=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Se.type="button",Se.setAttribute("aria-label",te.buttonTooltipText??"Attach file");let rt=te.buttonIconName??"paperclip",at=bt,jt=parseFloat(at)||40,rn=Math.round(jt*.6);Se.style.width=at,Se.style.height=at,Se.style.minWidth=at,Se.style.minHeight=at,Se.style.fontSize="18px",Se.style.lineHeight="1";let Cn=ne(rt,rn,"currentColor",1.5);Cn?Se.appendChild(Cn):Se.textContent="\u{1F4CE}",Se.addEventListener("click",Ut=>{Ut.preventDefault(),Re?.click()}),He.appendChild(Se);let Dt=te.buttonTooltipText??"Attach file";Nt({anchor:Se,trigger:He,text:()=>Se?.getAttribute("aria-label")??Dt}),Ee?Ee.append(He):Q.appendChild(He),!Tt&&Re&&Ze&&(Tt=Qo.fromConfig(te),Tt.setPreviewsContainer(Ze),Re.addEventListener("change",async()=>{Tt&&Re?.files&&(await Tt.handleFileSelect(Re.files),Re.value="")}))}else{He.style.display="";let te=o.attachments??{};Re&&(Re.accept=(te.allowedTypes??Vn).join(","),Re.multiple=(te.maxFiles??4)>1),Tt&&Tt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}if(ge.querySelector(".persona-attachment-drop-overlay")?.remove(),ge.appendChild(af(o.attachments?.dropOverlay)),Se){let te=o.attachments??{},Xe=te.buttonTooltipText??"Attach file";Se.setAttribute("aria-label",Xe),Se.textContent="";let bt=parseFloat(o.sendButton?.size??"40px")||40,rt=ne(te.buttonIconName??"paperclip",Math.round(bt*.6),"currentColor",1.5);rt?Se.appendChild(rt):Se.textContent="\u{1F4CE}",He&&Nt({anchor:Se,trigger:He,text:()=>Se?.getAttribute("aria-label")??Xe})}}else He&&(He.style.display="none"),Tt&&Tt.clearAttachments(),ge.querySelector(".persona-attachment-drop-overlay")?.remove();let Bt=o.sendButton??{},gs=Bt.useIcon??!1,Aa=Bt.iconText??"\u2191",yr=Bt.iconName,Sa=Bt.tooltipText??"Send message",Ll=Bt.showTooltip??!1,Uo=Bt.size??"40px",Fn=Bt.backgroundColor,zo=Bt.textColor;if(gs){if(ue.style.width=Uo,ue.style.height=Uo,ue.style.minWidth=Uo,ue.style.minHeight=Uo,ue.style.fontSize="18px",ue.style.lineHeight="1",zo?ue.style.color=zo:ue.style.color="var(--persona-button-primary-fg, #ffffff)",!$.isStreaming())if(ue.innerHTML="",yr){let te=parseFloat(Uo)||24,Xe=zo?.trim()||"currentColor",bt=ne(yr,te,Xe,2);bt?ue.appendChild(bt):ue.textContent=Aa}else ue.textContent=Aa;ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Fn?(ue.style.backgroundColor=Fn,ue.classList.remove("persona-bg-persona-primary")):(ue.style.backgroundColor="",ue.classList.add("persona-bg-persona-primary"))}else ue.textContent=o.copy?.sendButtonLabel??"Send",ue.style.width="",ue.style.height="",ue.style.minWidth="",ue.style.minHeight="",ue.style.fontSize="",ue.style.lineHeight="",ue.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Fn?(ue.style.backgroundColor=Fn,ue.classList.remove("persona-bg-persona-accent")):ue.classList.add("persona-bg-persona-accent"),zo?ue.style.color=zo:ue.classList.add("persona-text-white");Bt.borderWidth?(ue.style.borderWidth=Bt.borderWidth,ue.style.borderStyle="solid"):(ue.style.borderWidth="",ue.style.borderStyle=""),Bt.borderColor?ue.style.borderColor=Bt.borderColor:ue.style.borderColor="",Bt.paddingX?(ue.style.paddingLeft=Bt.paddingX,ue.style.paddingRight=Bt.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),Bt.paddingY?(ue.style.paddingTop=Bt.paddingY,ue.style.paddingBottom=Bt.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom=""),$.isStreaming()||ue.setAttribute("aria-label",Sa),mn&&Nt({anchor:ue,trigger:mn,text:()=>ue.getAttribute("aria-label")??Sa,enabled:Ll});let Ta=o.layout?.contentMaxWidth??(Y()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Ta?(xe.style.maxWidth=Ta,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",Q&&(Q.style.maxWidth=Ta,Q.style.marginLeft="auto",Q.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=Ta,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",Q&&(Q.style.maxWidth="",Q.style.marginLeft="",Q.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let lo=o.statusIndicator??{},Fm=lo.visible??!0;if(M.style.display=Fm?"":"none",$){let te=$.getStatus();ht(M,(bt=>bt==="idle"?lo.idleText??Ht.idle:bt==="connecting"?lo.connectingText??Ht.connecting:bt==="connected"?lo.connectedText??Ht.connected:bt==="error"?lo.errorText??Ht.error:Ht[bt])(te),lo,te)}M.classList.remove("persona-text-left","persona-text-center","persona-text-right");let _m=lo.align==="left"?"persona-text-left":lo.align==="center"?"persona-text-center":"persona-text-right";M.classList.add(_m)},open(){D()&&ut(!0,"api")},close(){D()&&ut(!1,"api")},toggle(){D()&&ut(!N,"api")},reconnect(){$.reconnectNow()},clearChat(){Hn=!1,$.clearMessages(),Do.clear(),ro();try{localStorage.removeItem(zr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zr}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==zr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),d?.clear&&ul(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},W.syncFromMetadata(),Ne?.clear(),$e?.reset(),Be?.update()},setMessage(l){return!Ce||$.isStreaming()?!1:(!N&&D()&&ut(!0,"system"),Ce.value=l,Ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let f=l?.trim()||Ce.value.trim();return f?(!N&&D()&&ut(!0,"system"),Ce.value="",Ce.style.height="auto",$.sendMessage(f),!0):!1},startVoiceRecognition(){return $.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()||(!N&&D()&&ut(!0,"system"),Ye.manuallyDeactivated=!1,xn(),$.toggleVoice().then(()=>{Ye.active=$.isVoiceActive(),On("user"),$.isVoiceActive()&&mr()})),!0):Ln?!0:$d()?(!N&&D()&&ut(!0,"system"),Ye.manuallyDeactivated=!1,xn(),ya("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,xn(),On("user"),Nn()}),!0):!1:Ln?(Ye.manuallyDeactivated=!0,xn(),ao("user"),!0):!1},injectMessage(l){return!N&&D()&&ut(!0,"system"),$.injectMessage(l)},injectAssistantMessage(l){!N&&D()&&ut(!0,"system");let f=$.injectAssistantMessage(l);return le&&(le=!1,he&&(clearTimeout(he),he=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),f},injectUserMessage(l){return!N&&D()&&ut(!0,"system"),$.injectUserMessage(l)},injectSystemMessage(l){return!N&&D()&&ut(!0,"system"),$.injectSystemMessage(l)},injectMessageBatch(l){return!N&&D()&&ut(!0,"system"),$.injectMessageBatch(l)},injectComponentDirective(l){return!N&&D()&&ut(!0,"system"),$.injectComponentDirective(l)},injectTestMessage(l){!N&&D()&&ut(!0,"system"),$.injectTestEvent(l)},async connectStream(l,f){return $.connectStream(l,f)},__pushEventStreamEvent(l){Ne&&($e?.processEvent(l.type,l.payload),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Z||!Ne||Zi()},hideEventStream(){ze&&Kr()},isEventStreamVisible(){return ze},showArtifacts(){Jt(o)&&(Hn=!1,ir=!0,Bn(),et?.setMobileOpen(!0))},hideArtifacts(){Jt(o)&&(Hn=!0,Bn())},upsertArtifact(l){return Jt(o)?(Vo(o.features?.artifacts,l.artifactType)==="panel"&&(Hn=!1,ir=!0),$.upsertArtifact(l)):null},selectArtifact(l){Jt(o)&&$.selectArtifact(l)},clearArtifacts(){Jt(o)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return S&&!N&&!Y()||!Ce?!1:(Ce.focus(),!0)},async resolveApproval(l,f,h){let A=$.getMessages().find(R=>R.variant==="approval"&&R.approval?.id===l);if(!A?.approval)throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){$.resolveWebMcpApproval(A.id,f);return}return $.resolveApproval(A.approval,f,h)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){C(l)},on(l,f){return i.on(l,f)},off(l,f){i.off(l,f)},isOpen(){return D()&&N},isVoiceActive(){return Ye.active},toggleReadAloud(l){$.toggleReadAloud(l)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(l){return $.getReadAloudState(l)},onReadAloudChange(l){return $.onReadAloudChange(l)},getState(){return{open:D()&&N,launcherEnabled:S,voiceActive:Ye.active,streaming:$.isStreaming()}},showCSATFeedback(l){!N&&D()&&ut(!0,"system");let f=xe.querySelector(".persona-feedback-container");f&&f.remove();let h=Fi({onSubmit:async(x,A)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!N&&D()&&ut(!0,"system");let f=xe.querySelector(".persona-feedback-container");f&&f.remove();let h=_i({onSubmit:async(x,A)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,f){return $.submitCSATFeedback(l,f)},async submitNPSFeedback(l,f){return $.submitNPSFeedback(l,f)},destroy(){xl(),$o!=null&&(clearInterval($o),$o=null),Ve.forEach(l=>l()),De.remove(),Qe?.remove(),Ot?.destroy(),qt?.remove(),Oo&&E.removeEventListener("click",Oo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,f={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:h=>h?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=f,Ve.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&Rt.focusInput()};if(window.addEventListener("persona:focusInput",f),Ve.push(()=>{window.removeEventListener("persona:focusInput",f)}),Z){let F=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===l)&&Rt.showEventStream()},J=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===l)&&Rt.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",J),Ve.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",J)})}let h=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&Rt.showArtifacts()},x=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&Rt.hideArtifacts()},A=F=>{let J=F.detail;J?.instanceId&&J.instanceId!==l||J?.artifact&&Rt.upsertArtifact(J.artifact)},R=F=>{let J=F.detail;J?.instanceId&&J.instanceId!==l||typeof J?.id=="string"&&Rt.selectArtifact(J.id)},X=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&Rt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",X),Ve.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",X)})}let pn=Lv(o.persistState);if(pn&&D()){let l=Pv(pn.storage),f=`${pn.keyPrefix}widget-open`,h=`${pn.keyPrefix}widget-voice`,x=`${pn.keyPrefix}widget-voice-mode`;if(l){let A=pn.persist?.openState&&l.getItem(f)==="true",R=pn.persist?.voiceState&&l.getItem(h)==="true",X=pn.persist?.voiceState&&l.getItem(x)==="true";if(A&&setTimeout(()=>{Rt.open(),setTimeout(()=>{if(R||X)Rt.startVoiceRecognition();else if(pn.persist?.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),pn.persist?.openState&&(i.on("widget:opened",()=>{l.setItem(f,"true")}),i.on("widget:closed",()=>{l.setItem(f,"false")})),pn.persist?.voiceState&&(i.on("voice:state",F=>{l.setItem(h,F.active?"true":"false")}),i.on("user:message",F=>{l.setItem(x,F.viaVoice?"true":"false")})),pn.clearOnChatClear){let F=()=>{l.removeItem(f),l.removeItem(h),l.removeItem(x)},J=()=>F();window.addEventListener("persona:clear-chat",J),Ve.push(()=>{window.removeEventListener("persona:clear-chat",J)})}}}if(b&&D()&&setTimeout(()=>{Rt.open()},0),ur(),!om){let l=xr(()=>{$&&(al++,Do.clear(),os(xe,$.getMessages(),Me))});Ve.push(l)}return Rt};var lf=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Wv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Hv=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Bv=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&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.")},cf=(e,t)=>{let n=t?.launcher?.enabled??!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",e.style.minWidth=n?"":"0"},jc=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=""},df=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",jc(e)},Fc=e=>{e.style.transition=""},_c=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=""},$c=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ui=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ov=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},Dv=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Nv=e=>{let t=Co(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Kt(t,r)??r;return{inset:o(n?.inset,ti),canvasBackground:o(n?.canvasBackground,ni)}},pf=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},Fv=(e,t,n,o,r,s,a,i)=>{let p=Zt(s),d=p.reveal==="push",c=i!=null,u=i?.inset??"",b=i?.canvasBackground??"";Ov(e,t,n,o,d),Dv(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.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",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=e.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,k=g!=null?g.innerWidth<=C:!1;if(y&&k&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),_c(t),Fc(o),df(o),$c(n),Ui(r,o),pf(o,!1,"",""),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",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??zt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.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"),df(o),Wv(o,p.maxHeight),pf(o,c&&a,u,b),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",_c(t),Fc(o),$c(n),Ui(r,o);let W=p.animate?"transform 180ms ease":"none",S=p.side==="right"?"translateX(100%)":"translateX(-100%)",I=a?"translateX(0)":S;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=W,o.style.transform=I,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Fc(o),jc(o),Ui(r,o);let W=lf(p.width,e.clientWidth),S=Math.max(0,e.clientWidth),I=p.animate?"margin-left 180ms ease":"none",j=p.side==="right"?a?-W:0:a?0:-W;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${S+W}px`,t.style.transition=I,t.style.marginLeft=`${j}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${S}px`,n.style.maxWidth=`${S}px`,n.style.minWidth=`${S}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",_c(t),jc(o),$c(n),Ui(r,o);let W=p.reveal==="emerge";W?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=a?p.width:"0px",I=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",j=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",Hv(o,p.maxHeight),o.style.overflow=W||j?"hidden":"visible",o.style.transition=I,W){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let q=c?`calc(${lf(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=q,r.style.minWidth=q,r.style.maxWidth=q,r.style.boxSizing="border-box"}}},_v=(e,t)=>{let n=e.ownerDocument.createElement("div");return cf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){cf(n,o)},destroy(){n.remove()}}},$v=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let b=null,g=()=>{b?.disconnect(),b=null},y=null,C=()=>{y=t?.launcher?.detachedPanel===!0?Nv(t):null};C();let k=()=>{Fv(a,i,p,d,c,t,u,y)},P=null,W=()=>{P?.(),P=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(P=Ir(()=>{C(),k()}))},S=()=>{g(),Zt(t).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{k()}),b.observe(a)))},I=!1,j=()=>{k(),S(),u&&!I&&a.dataset.personaDockMobileFullscreen!=="true"&&(I=!0,Bv(a,Zt(t)))},q=a.ownerDocument.defaultView,w=()=>{j()};return q?.addEventListener("resize",w),Zt(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),j(),W(),{mode:"docked",host:c,shell:a,syncWidgetState(z){let V=z.launcherEnabled?z.open:!0;u!==V&&(u=V,j())},updateConfig(z){t=z,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),j(),W()},destroy(){q?.removeEventListener("resize",w),P?.(),P=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Qs=(e,t)=>Lt(t)?$v(e,t):_v(e,t);var jv=e=>{if(typeof window>"u"||typeof document>"u")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},uf=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},Uc=e=>{let t=jv(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=Qs(t,r),a,i=[],p=(k,P)=>{let S=!(P?.launcher?.enabled??!0)||Lt(P),I=o.createElement("div");if(I.setAttribute("data-persona-root","true"),S&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0",I.style.minWidth="0"),n){let j=k.attachShadow({mode:"open"});j.appendChild(I),uf(j,o)}else k.appendChild(I),uf(k,o);return t.id&&I.setAttribute("data-persona-instance",t.id),I},d=()=>{s.syncWidgetState(a.getState())},c=()=>{i.forEach(k=>k()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},u=()=>{let k=p(s.host,r);a=ji(k,r,{debugTools:e.debugTools}),c()},b=()=>{i.forEach(k=>k()),i=[],a.destroy()};u(),e.onChatReady?.();let g=k=>{b(),s.destroy(),s=Qs(t,k),r=k,u()},y={update(k){let P=Hi(r??{},k),W=Lt(r),S=Lt(P),I=ko(r),j=ko(P);if(W!==S||I!==j){g(P);return}r=P,s.updateConfig(r),a.update(k),d()},destroy(){b(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(y,{get(k,P,W){if(P==="host")return s.host;if(P in k)return Reflect.get(k,P,W);let S=a[P];return typeof S=="function"?S.bind(a):S}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function Uv(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function zv(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:Uv(o,n)?2:3}function gf(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function zi(e,t){let n=t.trim();if(!n)return[...e].sort(gf);let o=[];for(let r of e){let s=zv(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:gf(r.item,s.item)),o.map(r=>r.item)}function qv(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function ff(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>zi(e.items,t),resolve:e.resolve}}function mf(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>zi(t,qv(r).name),resolve:(r,s)=>{let a=n.get(r.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(s.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(s.args):a.prompt??""}:{}}}}var xf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Vv=new Set(["button","a","input","select","textarea","details","summary"]),Kv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),zc=/\b(product|card|item|listing|result)\b/i,Vc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Gv=3e3,Jv=100;function Cf(e){let t=typeof e.className=="string"?e.className:"";if(zc.test(t)||e.id&&zc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&zc.test(o.value))return!0}return!1}function wf(e){return Vc.test((e.textContent??"").trim())}function Af(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Xv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function hf(e){let t=e.match(Vc);return t?t[0]:null}function yf(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Qv(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var Yv="commerce-card",Zv="result-card";function bf(e){return!Cf(e)||!wf(e)||!Af(e)&&!Xv(e)?0:5200}function vf(e){return!Cf(e)||wf(e)||!Af(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Kc=[{id:Yv,scoreElement(e){return bf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Vc.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(bf(e)===0)return null;let{title:n,href:o}=yf(e),r=hf((e.textContent??"").trim())??hf(t.text)??"",s=Qv(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
143
- `)}},{id:Zv,scoreElement(e){return vf(e)},formatSummary(e,t){if(vf(e)===0)return null;let{title:n,href:o}=yf(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
144
- `)}}];function ex(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function tx(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,i=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??Kc;return i==="simple"&&e.rules&&e.rules.length>0?(ex(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:d}}function qc(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var nx=["data-testid","data-product","data-action","data-id","data-name","data-type"];function ox(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"||Vv.has(t)||n&&Kv.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 rx(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function Gc(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${qc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of nx){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${qc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(a=>qc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${r}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function sx(e){return e==="static"?Jv:Gv}function Tf(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Gc(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:ox(e),attributes:rx(e)}}function ax(e,t,n,o){let r=sx(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,o);i>0&&(r+=i,a.formatSummary&&!s&&(s=a))}return{score:r,formattingRule:s}}function ix(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function lx(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&r.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,c=d.tagName.toLowerCase();if(xf.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Sf(d)){i=a.nextNode();continue}let u=Tf(d,e.maxTextLength),b=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(k=>k==="role");if(!b&&!g){i=a.nextNode();continue}if(o.has(u.selector)){i=a.nextNode();continue}o.add(u.selector);let{score:y,formattingRule:C}=ax(d,u,e.rules,n);r.push({el:d,domIndex:s,enriched:u,score:y,formattingRule:C}),s+=1}i=a.nextNode()}r.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return u!==b?u-b:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of r){if(p.length>=e.maxElements)break;ix(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return u!==b?u-b:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let b=d.formattingRule.formatSummary(d.el,d.enriched,n);b&&(c=b)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function cx(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let p=s,d=p.tagName.toLowerCase();if(xf.has(d)){s=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Sf(p)){s=r.nextNode();continue}let c=Tf(p,e.maxTextLength),u=c.text.length>0,b=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(g=>g==="role");if(!u&&!b){s=r.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}s=r.nextNode()}let a=[],i=[];for(let p of n)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function Ef(e={}){let t=tx(e),n=t.root??document.body;return n?t.mode==="simple"?cx(t,n):lx(t,n):[]}var qi=100;function Mf(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);s.length>0&&o.push(`Structured summaries:
142
+ `}if(!x&&!l){let kt="max-height: -moz-available !important; max-height: stretch !important;",Yt=f?"":"padding-top: 1.25em !important;",ka=f?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;De.style.cssText+=kt+Yt+ka}un()};da(),Zo(e,o),Ks(e,o),Gs(e,o),Xr=()=>{da(),Zo(e,o),Ks(e,o),Gs(e,o),oa?e.style.setProperty("--persona-artifact-welded-outer-radius",oa):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",xd)}),Ve.push(()=>{Kr!==null&&clearTimeout(Kr)});let En=null,Mn=null;Ve.push(()=>{En?.(),En=null,Mn?.(),Mn=null}),Jr&&Ve.push(()=>{Jr?.disconnect(),Jr=null}),Ve.push(()=>{Zr?.(),Zr=null,dl(),wt&&(wt.remove(),wt=null),et?.element.style.removeProperty("width"),et?.element.style.removeProperty("maxWidth")}),Z&&Ve.push(()=>{Ke!==null&&(cancelAnimationFrame(Ke),Ke=null),Be?.destroy(),Be=null,Ne?.destroy(),Ne=null,pe=null});let Bo=null,Ad=()=>{Bo&&(Bo(),Bo=null),o.colorScheme==="auto"&&(Bo=Wr(()=>{Zo(e,o)}))};Ad(),Ve.push(()=>{Bo&&(Bo(),Bo=null)}),Ve.push(a);let pa=o.features?.streamAnimation;if(pa?.type&&pa.type!=="none"){let l=Dr(pa.type,pa.plugins);l&&(Ei(l,e),Ve.push(()=>Tg(e)))}let ua=Vg(Ct),Oo=null,$,pl=l=>{if(!$)return;let f=l??$.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?ja(f):null;h?ua.render(h,$,Ce,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(x=>x.role==="user")?ua.render([],$,Ce,f):ua.render(o.suggestionChips,$,Ce,f,o.suggestionChipsConfig)},yn=!1,Do=ug(),pr=new Map,No=new Map,to=new Map,ul=0,cm=_n()!==null,tn=xi(),ln=0,no=null,cn=!1,ga=!1,oo=0,bn=null,Fo=null,gl=!1,fa=!1,es=null,ts=!0,ma=!1,ha=null,ya=!1,_o=()=>{ya=!0},fl=null,dm=4,ba=24,pm=80,ml=new Map,Ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Sd=o.voiceRecognition?.autoResume??!1,Bn=l=>{i.emit("voice:state",{active:Ye.active,source:l,timestamp:Date.now()})},vn=()=>{C(l=>({...l,voiceState:{active:Ye.active,timestamp:Date.now(),manuallyDeactivated:Ye.manuallyDeactivated}}))},um=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=$c(c.voiceState),f=!!l.active,h=Number(l.timestamp??0);Ye.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-h<Rv&&setTimeout(()=>{Ye.active||(Ye.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Ye.active=$.isVoiceActive(),Bn("restore"),$.isVoiceActive()&&hr()}):Aa("restore"))},1e3)},gm=()=>$?pf($.getMessages()).filter(l=>!l.__skipPersist):[],va=null,Td=(l,f)=>{typeof console<"u"&&console.error(l,f)},hl=(l,f)=>{let h=()=>{try{let X=l();return!X||typeof X.then!="function"?null:Promise.resolve(X).catch(F=>{Td(f,F)})}catch(X){return Td(f,X),null}},x=va,A=x?x.then(()=>h()??void 0):h();if(!A)return;let R=A.finally(()=>{va===R&&(va=null)});va=R};function yl(l){if(!d?.save)return;let h={messages:l?pf(l):$?gm():[],metadata:c,artifacts:mn.artifacts,selectedArtifactId:mn.selectedId};hl(()=>d.save(h),"[AgentWidget] Failed to persist state:")}let ur=null,Ed=()=>De.querySelector("#persona-scroll-container")||le,ns=()=>{ur!==null&&(cancelAnimationFrame(ur),ur=null),cn=!1},Md=()=>{no!==null&&(cancelAnimationFrame(no),no=null),ga=!1,ns()},fm=()=>yn&&vl()&&(qt()!=="anchor-top"||id()),bl=()=>{let l=Ro()||"Jump to latest",f=fm();Pt.toggleAttribute("data-persona-scroll-to-bottom-streaming",f),oo>0?(Io.textContent=String(oo),Io.style.display="",Pt.setAttribute("aria-label",`${l} (${oo} new)`)):(Io.textContent="",Io.style.display="none",Pt.setAttribute("aria-label",f?`${l} (response streaming below)`:l))},kd=()=>{oo!==0&&(oo=0,bl())},vl=()=>Qn()?!tn.isFollowing():!Eo(le,ba),nn=()=>{if(!ta()||ze){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==ge&&ge.appendChild(Pt),ir();let f=Rn(le)>0&&vl();f?bl():kd(),Pt.style.display=f?"":"none"},os=()=>{tn.pause()&&(Md(),nn())},ro=()=>{tn.resume(),kd(),nn()},so=(l=!1)=>{Qn()&&tn.isFollowing()&&(!l&&!yn||(no!==null&&(cancelAnimationFrame(no),no=null),ga=!0,no=requestAnimationFrame(()=>{no=null,ga=!1,tn.isFollowing()&&mm(Ed(),l?220:140)})))},Ld=(l,f,h,x=()=>!0)=>{let A=l.scrollTop,R=f(),X=R-A;if(ns(),Math.abs(X)<1){cn=!0,l.scrollTop=R,ln=l.scrollTop,cn=!1;return}let F=performance.now();cn=!0;let J=fe=>1-Math.pow(1-fe,3),se=fe=>{if(!x()){ns();return}let re=f();re!==R&&(R=re,X=R-A);let we=fe-F,Ge=Math.min(we/h,1),gt=J(Ge),ot=A+X*gt;l.scrollTop=ot,ln=l.scrollTop,Ge<1?ur=requestAnimationFrame(se):(l.scrollTop=R,ln=l.scrollTop,ur=null,cn=!1)};ur=requestAnimationFrame(se)},mm=(l,f=500)=>{let h=Rn(l)-l.scrollTop;if(Math.abs(h)<1){ln=l.scrollTop;return}if(Math.abs(h)>=pm){ns(),cn=!0,l.scrollTop=Rn(l),ln=l.scrollTop,cn=!1;return}Ld(l,()=>Rn(l),f,()=>tn.isFollowing())},Pd=()=>{let l=Ed();cn=!0,l.scrollTop=Rn(l),ln=l.scrollTop,cn=!1,nn()},Rd=l=>{let f=0,h=l;for(;h&&h!==le;)f+=h.offsetTop,h=h.offsetParent;return f},hm=()=>{let l=le.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??le.ownerDocument.getSelection()},xa=()=>yg(hm(),le),Id=()=>{if(nm()!=="last-user-turn")return!1;let l=$?.getMessages()??[];if(l.length<2)return!1;let f=[...l].reverse().find(R=>R.role==="user");if(!f)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(f.id):f.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=le.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let A=Math.min(Math.max(0,Rd(x)-sd()),Rn(le));return cn=!0,le.scrollTop=A,ln=le.scrollTop,cn=!1,qt()==="follow"&&!Eo(le,ba)&&tn.pause(),nn(),!0},Wd=l=>{Yn.style.height=`${Math.max(0,Math.round(l))}px`,bn&&(bn.spacerHeight=Math.max(0,l))},rs=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null),ns(),bn=null,Yn.style.height="0px"},Hd=l=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=requestAnimationFrame(()=>{Fo=null;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=le.querySelector(`[data-message-id="${f}"]`);if(!h)return;let x=Rd(h),A=bn?.spacerHeight??0,R=le.scrollHeight-A,{targetScrollTop:X,spacerHeight:F}=bg({anchorOffsetTop:x,topOffset:sd(),viewportHeight:le.clientHeight,contentHeight:R});bn={initialSpacerHeight:F,contentHeightAtAnchor:R,spacerHeight:F},Wd(F),Ld(le,()=>X,220)})},ym=()=>{if(Qn()){if(!tn.isFollowing()||Eo(le,1))return;so(!yn);return}if(bn&&bn.initialSpacerHeight>0){let l=le.scrollHeight-bn.spacerHeight,f=vg({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:l});f!==bn.spacerHeight&&Wd(f)}nn()},bm=l=>{let f=qt();f==="follow"?(ro(),so(!0)):f==="anchor-top"&&(ts=!1,ma=!0,ya=!1,ha=l,Hd(l))},vm=()=>{if(qt()==="anchor-top"){if(ma){ts=!1;return}ts=!0,rs(),ro(),so(!0)}},xm=l=>{if(qt()!=="anchor-top"||!ma||ya||xa())return;let f=es===null;for(let h of l){if(!f){h.id===es&&(f=!0);continue}if(hg(h)){if(h.id===ha)return;ha=h.id,Hd(h.id);return}}},Cm=l=>{let f=new Map;l.forEach(h=>{let x=ml.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(i.emit("assistant:message",h),!fa&&(qt()!=="anchor-top"||id())&&vl()&&(oo+=1,bl(),nn(),cd(oo===1?"1 new message below.":`${oo} new messages below.`))),h.role==="assistant"&&x?.streaming&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),ml.clear(),f.forEach((h,x)=>{ml.set(x,h)})},Ca=(l,f)=>{let h=f==="user"?"user":"assistant",x=o.layout?.messages?.[h],A=x?.width??"content",R=x?.maxWidth??(A==="full"?"100%":"85%");l.classList.add("persona-message-row"),l.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),l.classList.add(`persona-message-row-${f}`,`persona-message-width-${A}`),l.classList.toggle("persona-justify-end",f==="user"),l.setAttribute("data-message-role",f),l.setAttribute("data-message-width",A),l.style.setProperty("--persona-message-row-max-width",R)},$o=(l,f)=>{let h=document.createElement("div");return h.className="persona-flex",h.id=`wrapper-${l}`,h.setAttribute("data-wrapper-id",l),Ca(h,f),h},wm=(l,f,h)=>{let x=document.createElement("div"),R=(()=>{let H=r.find(Ie=>Ie.renderLoadingIndicator);if(H?.renderLoadingIndicator)return H.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),X=(H,Ie)=>Ie==null?!1:typeof Ie=="string"?(H.textContent=Ie,!0):(H.appendChild(Ie),!0),F=new Set,J=new Map,se=new Set,fe=r.some(H=>H.renderAskUserQuestion),re=[],we=[],Ge=o.enableComponentStreaming!==!1,gt=o.approval!==!1,ot=[];if(f.forEach(H=>{F.add(H.id),J.set(H.id,H.role);let Ie=fe&&jn(H),je=gt&&H.variant==="approval"&&!!H.approval,Te=!Ie&&H.role==="assistant"&&!H.variant&&Ge&&Ys(H);!je&&to.has(H.id)&&(l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),to.delete(H.id)),!Te&&No.has(H.id)&&(l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),No.delete(H.id));let Mt=jn(H)?`:${H.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${H.agentMetadata?.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",ft=pg(H,ul)+Mt,Kt=Ie||je||Te?null:gg(Do,H.id,ft);if(Kt){x.appendChild(Kt.cloneNode(!0)),jn(H)&&H.toolCall?.id&&H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(se.add(H.toolCall.id),Er(H,o,Pe.composerOverlay));return}let mt=null,Qt=r.find(Ue=>!!(H.variant==="reasoning"&&Ue.renderReasoning||H.variant==="tool"&&Ue.renderToolCall||!H.variant&&Ue.renderMessage)),Wt=o.layout?.messages;if(jn(H)&&H.agentMetadata?.askUserQuestionAnswered===!0){pr.delete(H.id),l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime");return}if(As(H)&&o.features?.suggestReplies?.enabled!==!1)return;if(jn(H)&&o.features?.askUserQuestion?.enabled!==!1){let Ue=r.find(Ft=>typeof Ft.renderAskUserQuestion=="function");if(Ue&&dt.current){let Ft=pr.get(H.id),_t=Ft!==ft,St=null;if(_t){let{payload:tt,complete:Fe}=Un(H),vt=H.id,$t=()=>dt.current?.getMessages().find(un=>un.id===vt);St=Ue.renderAskUserQuestion({message:H,payload:tt,complete:Fe,resolve:un=>{let fs=$t();fs&&dt.current?.resolveAskUserQuestion(fs,un)},dismiss:()=>{let un=$t();un?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(un),dt.current?.resolveAskUserQuestion(un,"(dismissed)"))},config:o})}let pt=Ft!=null;if(_t&&St===null&&!pt){H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(se.add(H.toolCall.id),Er(H,o,Pe.composerOverlay));return}let yt=$o(H.id,H.role);yt.setAttribute("data-ask-plugin-stub","true"),yt.setAttribute("data-preserve-runtime","true"),x.appendChild(yt),re.push({messageId:H.id,fingerprint:ft,bubble:St});return}else{H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(se.add(H.toolCall.id),Er(H,o,Pe.composerOverlay));return}}else if(je){let Ue=r.find(pt=>typeof pt.renderApproval=="function")??s,_t=to.get(H.id)!==ft,St=null;if(_t&&Ue?.renderApproval){let pt=H.id,yt=(tt,Fe)=>{let vt=dt.current?.getMessages().find($t=>$t.id===pt);vt?.approval&&(vt.approval.toolType==="webmcp"?dt.current?.resolveWebMcpApproval(vt.id,tt):dt.current?.resolveApproval(vt.approval,tt,Fe))};St=Ue.renderApproval({message:H,defaultRenderer:()=>Di(H,o),config:o,approve:tt=>yt("approved",tt),deny:tt=>yt("denied",tt)})}if(_t&&St===null)l.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),to.delete(H.id),mt=Di(H,o);else{let pt=$o(H.id,H.role);pt.setAttribute("data-approval-plugin-stub","true"),pt.setAttribute("data-preserve-runtime","true"),x.appendChild(pt),ot.push({messageId:H.id,fingerprint:ft,bubble:St});return}}else if(Qt)if(H.variant==="reasoning"&&H.reasoning&&Qt.renderReasoning){if(!ae)return;mt=Qt.renderReasoning({message:H,defaultRenderer:()=>Lc(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&Qt.renderToolCall){if(!me)return;mt=Qt.renderToolCall({message:H,defaultRenderer:()=>Rc(H,o),config:o})}else Qt.renderMessage&&(mt=Qt.renderMessage({message:H,defaultRenderer:()=>{let Ue=_r(H,h,Wt,o.messageActions,oe,{loadingIndicatorRenderer:R,widgetConfig:o});return H.role!=="user"&&Nc(Ue,H,o,$),Ue},config:o}));if(!mt&&Te){let Ue=zi(H);if(Ue){let Ft=No.get(H.id),_t=Ft!==ft,St=o.wrapComponentDirectiveInBubble!==!1&&Sn.getOptions(Ue.component)?.bubbleChrome!==!1,pt=null;if(_t){let yt=Ui(Ue,{config:o,message:H,transform:h});if(yt&&Ue.component==="PersonaArtifactInline"){let tt=yt.hasAttribute("data-artifact-inline")?yt:yt.querySelector("[data-artifact-inline]"),Fe=tt?.getAttribute("data-artifact-inline")??"",vt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Fe):Fe,$t=Fe?l.querySelector(`#wrapper-${H.id}`)?.querySelector(`[data-artifact-inline="${vt}"]`)??null:null;tt&&$t&&$t!==tt&&sg($t)&&(tt===yt?yt=$t:tt.replaceWith($t))}if(yt)if(St){let tt=document.createElement("div");if(tt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),tt.id=`bubble-${H.id}`,tt.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Fe=document.createElement("div");Fe.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Fe.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),tt.appendChild(Fe)}tt.appendChild(yt),pt=tt}else{let tt=document.createElement("div");if(tt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",tt.id=`bubble-${H.id}`,tt.setAttribute("data-message-id",H.id),tt.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Fe=document.createElement("div");Fe.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Fe.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),tt.appendChild(Fe)}tt.appendChild(yt),pt=tt}}if(pt||Ft!=null){let yt=$o(H.id,H.role);yt.setAttribute("data-component-directive-stub","true"),yt.setAttribute("data-preserve-runtime","true"),x.appendChild(yt),we.push({messageId:H.id,fingerprint:ft,bubble:pt});return}}}if(!mt)if(H.variant==="reasoning"&&H.reasoning){if(!ae)return;mt=Lc(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!me)return;mt=Rc(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;mt=Di(H,o)}else{let Ue=o.layout?.messages;Ue?.renderUserMessage&&H.role==="user"?mt=Ue.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):Ue?.renderAssistantMessage&&H.role==="assistant"?mt=Ue.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):mt=_r(H,h,Ue,o.messageActions,oe,{loadingIndicatorRenderer:R,widgetConfig:o}),H.role!=="user"&&mt&&Nc(mt,H,o,$)}let We=$o(H.id,H.role);We.appendChild(mt),fg(Do,H.id,ft,We),x.appendChild(We)}),Pe.composerOverlay&&Pe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ie=>{let je=Ie.getAttribute("data-persona-ask-sheet-for");je&&!se.has(je)&&fo(Pe.composerOverlay,je)}),o.features?.toolCallDisplay?.grouped){let H=[],Ie=[],je=o.features.toolCallDisplay.groupedMode==="summary";f.forEach(Te=>{if(Te.variant==="tool"&&Te.toolCall&&me){Ie.push(Te);return}Te.variant==="reasoning"&&!ae||((Ie.length>1||je&&Ie.length>0)&&H.push(Ie),Ie=[])}),(Ie.length>1||je&&Ie.length>0)&&H.push(Ie),H.forEach(Te=>{let Mt=Te.map(Ue=>Array.from(x.children).find(Ft=>Ft instanceof HTMLElement&&Ft.getAttribute("data-wrapper-id")===Ue.id)).filter(Ue=>!!Ue);if(Mt.length<(je?1:2))return;let ft=$o(`tool-group-${Te[0].id}`,"assistant");ft.setAttribute("data-persona-tool-group-row","true");let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let mt=document.createElement("div");mt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mt.id=`tool-group-summary-${Te[0].id}`;let Qt=`Called ${Te.length} ${Te.length===1?"tool":"tools"}`,Wt=o.toolCall?.renderGroupedSummary?.({messages:Te,toolCalls:Te.map(Ue=>Ue.toolCall).filter(Ue=>!!Ue),defaultSummary:Qt,config:o});X(mt,Wt)||(mt.textContent=Qt);let We=document.createElement("div");We.className="persona-tool-group-stack persona-flex persona-flex-col",We.id=`tool-group-stack-${Te[0].id}`,We.setAttribute("data-persona-tool-group-stack","true"),Kt.appendChild(mt),je||Kt.appendChild(We),ft.appendChild(Kt),Mt[0].before(ft),Mt.forEach((Ue,Ft)=>{if(je){Ue.remove();return}Ue.style.setProperty("--persona-message-row-max-width","100%");let _t=document.createElement("div");_t.className="persona-tool-group-item persona-relative",_t.setAttribute("data-persona-tool-group-item","true"),Ft<Mt.length-1&&_t.setAttribute("data-persona-tool-group-connector","true"),_t.appendChild(Ue),We.appendChild(_t)})})}mg(Do,F);let on=f.some(H=>H.role==="assistant"&&H.streaming),Et=f[f.length-1],It=Et?.role==="assistant"&&!Et.streaming&&Et.variant!=="approval";if(yn&&f.some(H=>H.role==="user")&&!on&&!It){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:nr},Ie=r.find(Te=>Te.renderLoadingIndicator),je=null;if(Ie?.renderLoadingIndicator&&(je=Ie.renderLoadingIndicator(H)),je===null&&o.loadingIndicator?.render&&(je=o.loadingIndicator.render(H)),je===null&&(je=nr()),je){let Te=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1;Te.className=Mt?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Te.setAttribute("data-typing-indicator","true"),Te.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Te.appendChild(je);let ft=$o("typing-indicator","assistant");ft.appendChild(Te),x.appendChild(ft)}}if(!yn&&f.length>0){let H=f[f.length-1],Ie={config:o,lastMessage:H,messageCount:f.length},je=r.find(Mt=>Mt.renderIdleIndicator),Te=null;if(je?.renderIdleIndicator&&(Te=je.renderIdleIndicator(Ie)),Te===null&&o.loadingIndicator?.renderIdle&&(Te=o.loadingIndicator.renderIdle(Ie)),Te){let Mt=document.createElement("div"),ft=o.loadingIndicator?.showBubble!==!1;Mt.className=ft?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild(Te);let Kt=$o("idle-indicator","assistant");Kt.appendChild(Mt),x.appendChild(Kt)}}if(Op(x),vi(l,x),Dl(l),re.length>0)for(let{messageId:H,fingerprint:Ie,bubble:je}of re){let Te=l.querySelector(`#wrapper-${H}`);Te&&(Ca(Te,J.get(H)??"assistant"),je!==null&&(Te.replaceChildren(je),Te.setAttribute("data-bubble-fp",Ie),pr.set(H,Ie)))}if(pr.size>0)for(let H of pr.keys())F.has(H)||pr.delete(H);if(we.length>0)for(let{messageId:H,fingerprint:Ie,bubble:je}of we){let Te=l.querySelector(`#wrapper-${H}`);Te&&(Ca(Te,J.get(H)??"assistant"),je!==null&&(Te.replaceChildren(je),Te.setAttribute("data-bubble-fp",Ie),No.set(H,Ie)))}if(No.size>0)for(let H of No.keys())F.has(H)||No.delete(H);if(ot.length>0)for(let{messageId:H,fingerprint:Ie,bubble:je}of ot){let Te=l.querySelector(`#wrapper-${H}`);Te&&(Ca(Te,J.get(H)??"assistant"),je!==null&&(Te.replaceChildren(je),Te.setAttribute("data-bubble-fp",Ie),to.set(H,Ie)))}if(to.size>0)for(let H of to.keys())F.has(H)||to.delete(H)},ss=(l,f,h)=>{wm(l,f,h),yd()},as=null,Am=()=>{if(as)return;let l=h=>{let x=h.composedPath();x.includes(De)||Qe&&x.includes(Qe)||ut(!1,"user")};as=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},Bd=()=>{if(!as)return;(e.ownerDocument??document).removeEventListener("pointerdown",as,!0),as=null};Ve.push(()=>Bd());let is=null,Sm=()=>{if(is)return;let l=h=>{h.key==="Escape"&&(h.isComposing||ut(!1,"user"))};is=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},Od=()=>{if(!is)return;(e.ownerDocument??document).removeEventListener("keydown",is,!0),is=null};Ve.push(()=>Od());let ls=!1,Dd=new Set,Tm=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},gr=()=>{if(!Y())return;let l=Pe.peekBanner,f=Pe.peekTextNode;if(!l||!f)return;if(N){l.classList.remove("persona-pill-peek--visible");return}let h=$?.getMessages()??[],x;for(let Et=h.length-1;Et>=0;Et--){let It=h[Et];if(It.role==="assistant"&&It.content){x=It;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let A=x.content,R=!!x.streaming,X=Tm(),F=Ai(X),J=F.type!=="none"?Dr(F.type,X?.plugins):null,se=J?.isAnimating?.(x)===!0,fe=J!==null&&(R||se);fe&&J&&!Dd.has(J.name)&&(Ei(J,e),Dd.add(J.name));let re=fe&&J?.containerClass?J.containerClass:null,we=f.dataset.personaPeekStreamClass??null;we&&we!==re&&(f.classList.remove(we),delete f.dataset.personaPeekStreamClass),re&&we!==re&&(f.classList.add(re),f.dataset.personaPeekStreamClass=re),fe?(f.style.setProperty("--persona-stream-step",`${F.speed}ms`),f.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Ge=fe?Si(A,F.buffer,J,x,R):A;if(fe&&F.placeholder==="skeleton"&&R&&(!Ge||!Ge.trim())){let Et=document.createElement("div"),It=$s();It.classList.add("persona-pill-peek__skeleton"),Et.appendChild(It),vi(f,Et)}else{let Et=Math.max(0,Ge.length-100),It=Ge.length>100?Ge.slice(-100):Ge,H=Ln(It);if(!fe||!J){let Ie=Ge.length>100?`\u2026${It}`:It;f.textContent!==Ie&&(f.textContent=Ie)}else{let Ie=H;(J.wrap==="char"||J.wrap==="word")&&(Ie=_s(H,J.wrap,`peek-${x.id}`,{skipTags:J.skipTags,startIndex:Et}));let je=document.createElement("div");if(je.innerHTML=Ie,J.useCaret&&It.length>0){let Te=Ti(),Mt=je.querySelectorAll(".persona-stream-char, .persona-stream-word"),ft=Mt[Mt.length-1];ft?.parentNode?ft.parentNode.insertBefore(Te,ft.nextSibling):je.appendChild(Te)}vi(f,je),J.onAfterRender?.({container:f,bubble:l,messageId:x.id,message:x,speed:F.speed,duration:F.duration})}}let on=yn||ls;l.classList.toggle("persona-pill-peek--visible",on)};if(Y()){let l=Pe.peekBanner;if(l){let x=A=>{A.preventDefault(),A.stopPropagation(),ut(!0,"user")};l.addEventListener("pointerdown",x),Ve.push(()=>{l.removeEventListener("pointerdown",x)})}let f=()=>{ls||(ls=!0,gr())},h=()=>{ls&&(ls=!1,gr())};be.addEventListener("pointerenter",f),be.addEventListener("pointerleave",h),Ve.push(()=>{be.removeEventListener("pointerenter",f),be.removeEventListener("pointerleave",h)}),Qe&&(Qe.addEventListener("pointerenter",f),Qe.addEventListener("pointerleave",h),Ve.push(()=>{Qe.removeEventListener("pointerenter",f),Qe.removeEventListener("pointerleave",h)}))}let Em=l=>{let f=o.launcher?.composerBar??{},h=f.expandedSize??"anchored",x=f.bottomOffset??"16px",A=f.collapsedMaxWidth,R=f.expandedMaxWidth??"880px",X=f.expandedTopOffset??"5vh",F=f.modalMaxWidth??"880px",J=f.modalMaxHeight??"min(90vh, 800px)",se="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",re=De.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",Qe){let we=Qe.style;we.bottom=x,we.width=A??""}if(l&&h!=="fullscreen"){if(h==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=F,re.maxWidth=se,re.maxHeight=J,re.height=J;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${x} + ${fe})`,re.top=X,re.width=R,re.maxWidth=se}},cs=()=>{if(!D())return;if(Y()){let se=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=N?"expanded":"collapsed";De.dataset.state=fe,De.dataset.expandedSize=se,Qe&&(Qe.dataset.state=fe,Qe.dataset.expandedSize=se),De.style.removeProperty("display"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Em(N),ge.style.display=N?"flex":"none",da(),N?(Am(),Sm()):(Bd(),Od()),gr();return}let l=Lt(o),f=e.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,A=f.innerWidth<=h,R=x&&A&&S,X=Zt(o).reveal;N?(De.style.removeProperty("display"),De.style.display=l?"flex":"",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0"),be.classList.add("persona-scale-100","persona-opacity-100"),Ot?Ot.element.style.display="none":Vt&&(Vt.style.display="none")):(l?l&&(X==="overlay"||X==="push")&&!R?(De.style.removeProperty("display"),De.style.display="flex",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.setProperty("display","none","important"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.display="",De.classList.add("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100"),be.classList.add("persona-scale-95","persona-opacity-0")),Ot?Ot.element.style.display=l?"none":"":Vt&&(Vt.style.display=l?"none":""))},ut=(l,f="user")=>{if(!D()||N===l)return;let h=N;N=l,cs();let x=(()=>{let R=o.launcher?.sidebarMode??!1,X=e.ownerDocument.defaultView??window,F=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,se=X.innerWidth<=J,fe=Lt(o)&&F&&se,re=Y()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return R||F&&se&&S||fe||re})();if(N&&x){if(!En){let R=e.getRootNode(),X=R instanceof ShadowRoot?R.host:e.closest(".persona-host");X&&(En=bc(X,o.launcher?.zIndex??zt))}Mn||(Mn=vc(e.ownerDocument))}else N||(En?.(),En=null,Mn?.(),Mn=null);N&&(us(),Id()||(qt()==="follow"?so(!0):Pd()));let A={open:N,source:f,timestamp:Date.now()};N&&!h?i.emit("widget:opened",A):!N&&h&&i.emit("widget:closed",A),i.emit("widget:state",{open:N,launcherEnabled:S,voiceActive:Ye.active,streaming:$.isStreaming()})},xl=l=>{st(l?"stop":"send"),G&&(G.disabled=l),ua.buttons.forEach(f=>{f.disabled=l}),U.dataset.personaComposerStreaming=l?"true":"false",U.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},Cl=()=>{Ye.active||Ce&&Ce.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Cl(),200)});let Nd=()=>{_.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",v.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",Ce.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=le.querySelector("[data-persona-intro-card]");if(l){let h=o.copy?.showWelcomeCard!==!1;l.style.display=h?"":"none",h?(le.classList.remove("persona-gap-3"),le.classList.add("persona-gap-6")):(le.classList.remove("persona-gap-6"),le.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!$?.isStreaming()&&(ue.textContent=o.copy?.sendButtonLabel??"Send"),Ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{C(f=>({...f,sessionId:l}))}});let jo=null,Mm=()=>{jo==null&&(jo=setInterval(()=>{let l=xe.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(jo),jo=null;return}let f=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=za(f-x))})},100))},wl=(l,f)=>{if(Object.is(l,f))return!0;if(l===null||f===null||typeof l!="object"||typeof f!="object")return!1;if(Array.isArray(l)||Array.isArray(f))return!Array.isArray(l)||!Array.isArray(f)||l.length!==f.length?!1:l.every((X,F)=>wl(X,f[F]));let h=l,x=f,A=Object.keys(h),R=Object.keys(x);return A.length===R.length&&A.every(X=>Object.prototype.hasOwnProperty.call(x,X)&&wl(h[X],x[X]))},Fd=l=>{let{content:f,rawContent:h,llmContent:x,...A}=l;return A},Al=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!Ys(l),km=(l,f,h)=>{if(l.length!==f.length)return!1;let x=l[h.index],A=f[h.index];return!x||!A||x.id!==h.id||A.id!==h.id?!1:(!Object.is(x.content,A.content)||!Object.is(x.rawContent,A.rawContent)||!Object.is(x.llmContent,A.llmContent))&&Al(x)&&Al(A)&&wl(Fd(x),Fd(A))},_d=null,fr=null,Uo=null,On=null,wa=l=>{_d=l;let f,h;fr=null;for(let A=l.length-1;A>=0;A-=1){let R=l[A];if(!f&&R.role==="user"&&(f=R),!h&&R.role==="assistant"&&(h=R),!fr&&Al(R)&&(fr={index:A,id:R.id}),f&&h&&fr)break}ss(xe,l,Me),uc(xe,mn.artifacts,{suppressTransition:yn}),Mm(),pl(l),so(!yn),Cm(l),l.length===0&&(rs(),ts=!0,ma=!1,ha=null,ya=!1),!gl||fa?(gl=!0,es=f?.id??null,fl=h?.id??null):f&&f.id!==es?(es=f.id,bm(f.id)):h&&h.id!==fl&&vm(),h&&(fl=h.id),xm(l);let x=Ye.lastUserMessageId;f&&f.id!==x&&(Ye.lastUserMessageId=f.id,i.emit("user:message",f)),Ye.lastUserMessageWasVoice=!!f?.viaVoice,yl(l),gr()},Sl=()=>{On!==null&&(cancelAnimationFrame(On),On=null);let l=Uo;Uo=null,l&&wa(l)},$d=()=>{On!==null&&cancelAnimationFrame(On),On=null,Uo=null},Lm=l=>{let f=Uo??_d;if(yn&&f&&fr&&km(f,l,fr)){Uo=l,On===null&&(On=requestAnimationFrame(()=>{On=null;let h=Uo;Uo=null,h&&wa(h)}));return}if(l.length===0){$d(),wa(l);return}Sl(),wa(l)};$=new Rr(o,{onMessagesChanged(l){Lm(l)},onStatusChanged(l){let f=o.statusIndicator??{};ht(M,(x=>x==="idle"?f.idleText??Ht.idle:x==="connecting"?f.connectingText??Ht.connecting:x==="connected"?f.connectedText??Ht.connected:x==="error"?f.errorText??Ht.error:x==="paused"?f.pausedText??Ht.paused:x==="resuming"?f.resumingText??Ht.resuming:Ht[x])(l),f,l)},onStreamingChanged(l){l||($?.getMessages().length===0?$d():Sl()),yn=l,xl(l),$&&ss(xe,$.getMessages(),Me),l||so(!0),nn(),cd(l?"Responding\u2026":"Response complete."),gr()},onVoiceStatusChanged(l){if(i.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":Dn(),hr();break;case"processing":Dn(),_m();break;case"speaking":Dn(),$m();break;default:l==="idle"&&$.isBargeInActive()?(Dn(),hr(),G?.setAttribute("aria-label","End voice session")):(Ye.active=!1,Dn(),Bn("system"),vn());break}},onArtifactsState(l){mn=l,l.artifacts.length===0&&(lr=!1),uc(xe,l.artifacts,{suppressTransition:yn}),Hn(),yl()},onReconnect(l){let{executionId:f,lastEventId:h}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:f,after:h}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:f,after:h,attempt:l.attempt??1}):i.emit("stream:resumed",{executionId:f,after:h})}}),dt.current=$,Ve.push(()=>$.cancel());let Tl=null;if($.onReadAloudChange((l,f)=>{md=l,hd=f,yd();let h=l??Tl;l&&(Tl=l);let x=h?$.getMessages().find(A=>A.id===h)??null:null;i.emit("message:read-aloud",{messageId:h,message:x,state:f,timestamp:Date.now()}),f==="idle"&&(Tl=null)}),gl=!0,o.voiceRecognition?.provider?.type==="runtype")try{$.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&$.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Ne||o.onSSEEvent)&&$.setSSEEventCallback((l,f)=>{o.onSSEEvent?.(l,f),$e?.processEvent(l,f),Ne?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(f)})});let jd=()=>{o.resume&&typeof o.reconnectStream=="function"&&$.resumeFromHandle(o.resume)};u?u.then(l=>{if(l){if(l.metadata&&(c=$c(l.metadata),W.syncFromMetadata()),l.messages?.length){fa=!0;try{$.hydrateMessages(l.messages)}finally{fa=!1}}l.artifacts?.length&&$.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>jd()):jd();let Ud=()=>{!Y()||N||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ut(!0,"auto")},Pm=(l,f)=>l?f?{refs:[...l.refs,...f.refs],finalize:async()=>{let[h,x]=await Promise.allSettled([l.finalize(),f.finalize()]),A=[];return h.status==="fulfilled"?A.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),x.status==="fulfilled"?A.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),Nv(A)}}:l:f,Rm=()=>{let f=Ce.getInlineMessageFields?.();return f&&f.contentSegments.some(x=>x.kind==="mention")?f.contentSegments:void 0},ds=!1,Im=async l=>{let f=Ce.value.trim(),h=Tt?.hasAttachments()??!1,x=f?await(en?.takeInlineCommand(f)??Promise.resolve(null)):null;if(x?.kind==="action"){Ce.value="",Ce.style.height="auto",ps(),en?.clear();return}let A=en?.collectForSubmit()??null,R=x?.kind==="server"?x.mentions:null,X=Pm(A,R),F=x?.kind==="prompt"?x.sendText:f,J=!!A&&A.refs.length>0;if(!F&&!h&&!J&&!R)return;Ud();let se;h&&(se=[],se.push(...Tt.getContentParts()),F&&se.push(bo(F)));let fe=x?.kind==="prompt"?void 0:Rm();Ce.value="",Ce.style.height="auto",ps(),$.sendMessage(F,{contentParts:se,mentions:X??void 0,contentSegments:fe,viaVoice:l?.viaVoice}),h&&Tt.clearAttachments(),A&&en?.clear()},El=async l=>{if(!ds){ds=!0;try{await Im(l)}finally{ds=!1}}},zd=l=>{if(l.preventDefault(),$.isStreaming()){$.cancel(),$e?.reset(),Be?.update();return}ds||El()},Wm=()=>o.features?.composerHistory!==!1,Ml={...mc},kl=!1,ps=()=>{Ml={...mc}},Hm=()=>$.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),Bm=l=>{if(!Ce)return;kl=!0,Ce.value=l,Ce.dispatchEvent(new Event("input",{bubbles:!0})),kl=!1;let f=Ce.value.length;Ce.setSelectionRange(f,f)},Om=l=>{kl||(l.isComposing||en?.handleInput(l.inputType??void 0),ps())},Dm=l=>{if(Ce&&!(!l.isComposing&&en?.handleKeydown(l))){if(Wm()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=Ce.selectionStart===0&&Ce.selectionEnd===0,h=dg({direction:l.key==="ArrowUp"?"up":"down",history:Hm(),currentValue:Ce.value,atStart:f,state:Ml});if(Ml=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Bm(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if($.isStreaming()){l.preventDefault();return}if(ds){l.preventDefault();return}ps(),l.preventDefault(),ue.click()}}},qd=l=>{l.key!=="Escape"||l.isComposing||$.isStreaming()&&l.composedPath().includes(ge)&&($.cancel(),$e?.reset(),Be?.update(),ps(),l.preventDefault(),l.stopImmediatePropagation())},Nm=async l=>{if(o.attachments?.enabled!==!0||!Tt)return;let f=Hv(l.clipboardData);f.length!==0&&(l.preventDefault(),await Tt.handleFiles(f))},dn=null,kn=!1,mr=null,At=null,Vd=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Aa=(l="user")=>{if(kn||$.isStreaming())return;let f=Vd();if(!f)return;dn=new f;let x=(o.voiceRecognition??{}).pauseDuration??2e3;dn.continuous=!0,dn.interimResults=!0,dn.lang="en-US";let A=Ce.value;dn.onresult=R=>{let X="",F="";for(let se=0;se<R.results.length;se++){let fe=R.results[se],re=fe[0].transcript;fe.isFinal?X+=re+" ":F=re}let J=A+X+F;Ce.value=J,mr&&clearTimeout(mr),(X||F)&&(mr=window.setTimeout(()=>{Ce.value.trim()&&dn&&kn&&(ao(),El({viaVoice:!0}))},x))},dn.onerror=R=>{R.error!=="no-speech"&&ao()},dn.onend=()=>{if(kn){let R=Ce.value.trim();R&&R!==A.trim()&&El({viaVoice:!0}),ao()}};try{if(dn.start(),kn=!0,Ye.active=!0,l!=="system"&&(Ye.manuallyDeactivated=!1),Bn(l),vn(),G){let R=o.voiceRecognition??{};At={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:R.iconName??"mic",iconSize:parseFloat(R.iconSize??o.sendButton?.size??"40")||24};let X=R.recordingBackgroundColor,F=R.recordingIconColor,J=R.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=X??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=F??"var(--persona-voice-recording-indicator, #ffffff)",F){let se=G.querySelector("svg");se&&se.setAttribute("stroke",F)}J&&(G.style.borderColor=J),G.setAttribute("aria-label","Stop voice recognition")}}catch{ao("system")}},ao=(l="user")=>{if(kn){if(kn=!1,mr&&(clearTimeout(mr),mr=null),dn){try{dn.stop()}catch{}dn=null}if(Ye.active=!1,Bn(l),vn(),G){if(G.classList.remove("persona-voice-recording"),At){G.style.backgroundColor=At.backgroundColor,G.style.color=At.color,G.style.borderColor=At.borderColor;let f=G.querySelector("svg");f&&f.setAttribute("stroke",At.color||"currentColor"),At=null}G.setAttribute("aria-label","Start voice recognition")}}},Fm=(l,f)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=l?.provider?.type==="runtype",A=l?.provider?.type==="custom";if(!(h||x||A))return null;let X=m("div","persona-send-button-wrapper"),F=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button";let J=l?.tooltipText??"Start voice recognition";F.setAttribute("aria-label",J);let se=l?.iconName??"mic",fe=f?.size??"40px",re=l?.iconSize??fe,we=parseFloat(re)||24,Ge=l?.backgroundColor??f?.backgroundColor,gt=l?.iconColor??f?.textColor;F.style.width=re,F.style.height=re,F.style.minWidth=re,F.style.minHeight=re,F.style.fontSize="18px",F.style.lineHeight="1",gt?F.style.color=gt:F.style.color="var(--persona-text, #111827)";let on=ne(se,we,gt||"currentColor",1.5);on?F.appendChild(on):F.textContent="\u{1F3A4}",Ge?F.style.backgroundColor=Ge:F.style.backgroundColor="",l?.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l?.borderColor&&(F.style.borderColor=l.borderColor),l?.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l?.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),X.appendChild(F);let Et=l?.showTooltip??!1;return Nt({anchor:F,trigger:X,text:()=>F.getAttribute("aria-label")??J,enabled:Et}),{micButton:F,micButtonWrapper:X}},Ll=()=>{if(!G||At)return;let l=o.voiceRecognition??{};At={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},Pl=(l,f)=>{if(!G)return;let h=G.querySelector("svg");h&&h.remove();let x=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=ne(l,x,f,1.5);A&&G.appendChild(A)},Sa=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},hr=()=>{if(!G)return;Ll();let l=o.voiceRecognition??{},f=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(Sa(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=f??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let A=G.querySelector("svg");A&&A.setAttribute("stroke",h)}x&&(G.style.borderColor=x),G.setAttribute("aria-label","Stop voice recognition")},_m=()=>{if(!G)return;Ll();let l=o.voiceRecognition??{},f=$.getVoiceInterruptionMode(),h=l.processingIconName??"loader",x=l.processingIconColor??At?.color??"",A=l.processingBackgroundColor??At?.backgroundColor??"",R=l.processingBorderColor??At?.borderColor??"";Sa(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=A,G.style.borderColor=R;let X=x||"currentColor";G.style.color=X,Pl(h,X),G.setAttribute("aria-label","Processing voice input"),f==="none"&&(G.style.cursor="default")},$m=()=>{if(!G)return;Ll();let l=o.voiceRecognition??{},f=$.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",x=l.speakingIconName??h,A=l.speakingIconColor??(f==="barge-in"?l.recordingIconColor??At?.color??"":At?.color??""),R=l.speakingBackgroundColor??(f==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),X=l.speakingBorderColor??(f==="barge-in"?l.recordingBorderColor??"":At?.borderColor??"");Sa(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=R,G.style.borderColor=X;let F=A||"currentColor";G.style.color=F,Pl(x,F);let J=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",J),f==="none"&&(G.style.cursor="default"),f==="barge-in"&&G.classList.add("persona-voice-recording")},Dn=()=>{G&&(Sa(),At&&(G.style.backgroundColor=At.backgroundColor??"",G.style.color=At.color??"",G.style.borderColor=At.borderColor??"",Pl(At.iconName,At.color||"currentColor"),At=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Ta=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=$.getVoiceStatus(),f=$.getVoiceInterruptionMode();if(f==="none"&&(l==="processing"||l==="speaking"))return;if(f==="cancel"&&(l==="processing"||l==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,vn(),Bn("user"),Dn()});return}$.toggleVoice().then(()=>{Ye.active=$.isVoiceActive(),Ye.manuallyDeactivated=!$.isVoiceActive(),vn(),Bn("user"),$.isVoiceActive()?hr():Dn()});return}if(kn){let l=Ce.value.trim();Ye.manuallyDeactivated=!0,vn(),ao("user"),l&&(Ce.value="",Ce.style.height="auto",$.sendMessage(l))}else Ye.manuallyDeactivated=!1,vn(),Aa("user")};pd=Ta,G&&(G.addEventListener("click",Ta),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()&&$.toggleVoice(),Dn()):ao("system"),G&&G.removeEventListener("click",Ta)}));let jm=i.on("assistant:complete",()=>{Sd&&(Ye.active||Ye.manuallyDeactivated||Sd==="assistant"&&!Ye.lastUserMessageWasVoice||setTimeout(()=>{!Ye.active&&!Ye.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Ye.active=$.isVoiceActive(),Bn("auto"),$.isVoiceActive()&&hr()}):Aa("auto"))},600))});Ve.push(jm);let Um=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});Ve.push(Um);let Kd=()=>{ut(!N,"user")},Ot=null,Vt=null;if(S&&!Y()){let{instance:l,element:f}=Sc({config:o,plugins:r,onToggle:Kd});Ot=l,l||(Vt=f)}Ot?e.appendChild(Ot.element):Vt&&e.appendChild(Vt),cs(),pl(),Nd(),xl($.isStreaming()),Id()||(qt()==="follow"?so(!0):Pd()),um(),j&&(!S||Y()?setTimeout(()=>Cl(),0):N&&setTimeout(()=>Cl(),200));let us=()=>{if(Y()){ir(),cs();return}let l=Lt(o),f=o.launcher?.sidebarMode??!1,h=l||f||(o.launcher?.fullHeight??!1),x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640,X=x.innerWidth<=R,F=A&&X&&S;try{if(F){Xr(),Qr=ca();return}let J=!1;V&&(V=!1,Xr(),J=!0);let se=ca();if(!J&&se!==Qr&&(Xr(),J=!0),Qr=se,J&&cl(),!S&&!l){be.style.height="",be.style.width="";return}if(!f&&!l){let re=o?.launcher?.width??o?.launcherWidth??sn;be.style.width=re,be.style.maxWidth=re}if(la(),!h){let fe=x.innerHeight,re=64,we=o.launcher?.heightOffset??0,Ge=Math.max(200,fe-re),gt=Math.min(640,Ge),ot=Math.max(200,gt-we);be.style.height=`${ot}px`}}finally{if(ir(),cs(),N&&S){let se=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),fe=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,we=Lt(o)&&re&&se,Ge=fe||re&&se&&S||we;if(Ge&&!Mn){let gt=e.getRootNode(),ot=gt instanceof ShadowRoot?gt.host:e.closest(".persona-host");ot&&!En&&(En=bc(ot,o.launcher?.zIndex??zt)),Mn=vc(e.ownerDocument)}else Ge||(En?.(),En=null,Mn?.(),Mn=null)}}};us();let Gd=e.ownerDocument.defaultView??window;if(Gd.addEventListener("resize",us),Ve.push(()=>Gd.removeEventListener("resize",us)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{ir()});l.observe(U),Ve.push(()=>l.disconnect())}ln=le.scrollTop;let Jd=Rn(le),Xd=()=>{let l=le.scrollTop,f=Rn(le),h=f<Jd;if(Jd=f,!Qn()){ln=l,nn();return}let{action:x,nextLastScrollTop:A}=Ci({following:tn.isFollowing(),currentScrollTop:l,lastScrollTop:ln,nearBottom:Eo(le,ba),userScrollThreshold:dm,isAutoScrolling:cn||ga||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ln=A,x==="resume"){xa()||ro();return}x==="pause"&&os()};if(le.addEventListener("scroll",Xd,{passive:!0}),Ve.push(()=>le.removeEventListener("scroll",Xd)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{ym(),Dl(xe)});l.observe(xe),l.observe(le),Ve.push(()=>l.disconnect())}let Qd=()=>{Qn()&&tn.isFollowing()&&xa()&&os()},Yd=le.ownerDocument;Yd.addEventListener("selectionchange",Qd),Ve.push(()=>{Yd.removeEventListener("selectionchange",Qd)});let zm=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Zd=l=>{zm.has(l.key)&&(_o(),ad()&&Qn()&&tn.isFollowing()&&os())},ep=l=>{l.target?.closest("a, button, [tabindex], input, textarea, select")&&(_o(),ad()&&Qn()&&tn.isFollowing()&&os())};le.addEventListener("keydown",Zd),le.addEventListener("focusin",ep),Ve.push(()=>{le.removeEventListener("keydown",Zd),le.removeEventListener("focusin",ep)});let tp=l=>{if(l.deltaY!==0&&_o(),!Qn())return;let f=wi({following:tn.isFollowing(),deltaY:l.deltaY,nearBottom:Eo(le,ba),resumeWhenNearBottom:!0});f==="pause"?os():f==="resume"&&!xa()&&ro()};le.addEventListener("wheel",tp,{passive:!0}),le.addEventListener("touchmove",_o,{passive:!0}),le.addEventListener("pointerdown",_o,{passive:!0}),Ve.push(()=>{le.removeEventListener("touchmove",_o),le.removeEventListener("pointerdown",_o)}),Ve.push(()=>le.removeEventListener("wheel",tp)),Pt.addEventListener("click",()=>{rs(),le.scrollTop=le.scrollHeight,ln=le.scrollTop,ro(),so(!0),nn()}),Ve.push(()=>Pt.remove()),Ve.push(()=>{Md(),rs()});let np=()=>{E&&(Oo&&(E.removeEventListener("click",Oo),Oo=null),D()?(E.style.display="",Oo=()=>{ut(!1,"user")},E.addEventListener("click",Oo)):E.style.display="none")};np(),(()=>{let{clearChatButton:l}=Pe;l&&l.addEventListener("click",()=>{$.clearMessages(),Do.clear(),ro(),fo(Pe.composerOverlay);try{localStorage.removeItem(qr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(f),d?.clear&&hl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},W.syncFromMetadata(),Ne?.clear(),$e?.reset(),Be?.update()})})(),Q&&Q.addEventListener("submit",zd);let op=[["keydown",Dm],["input",Om],["paste",Nm],["focus",sm]],rp=l=>{if(l)for(let[f,h]of op)l.addEventListener(f,h)},sp=l=>{if(l)for(let[f,h]of op)l.removeEventListener(f,h)};rp(Ce),en?.onComposerSwap((l,f)=>{sp(f),Ce=l,rp(l)});let ap=e.ownerDocument??document;ap.addEventListener("keydown",qd,!0);let ip="persona-attachment-drop-active",gs=0,Rl=()=>{gs=0,ge.classList.remove(ip)},yr=()=>o.attachments?.enabled===!0&&Tt!==null,lp=l=>{!Ki(l.dataTransfer)||!yr()||(gs++,gs===1&&ge.classList.add(ip))},cp=l=>{!Ki(l.dataTransfer)||!yr()||(gs--,gs<=0&&Rl())},dp=l=>{!Ki(l.dataTransfer)||!yr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},pp=l=>{if(!Ki(l.dataTransfer)||!yr())return;l.preventDefault(),l.stopPropagation(),Rl();let f=Array.from(l.dataTransfer.files??[]);f.length!==0&&Tt.handleFiles(f)},io=!0;ge.addEventListener("dragenter",lp,io),ge.addEventListener("dragleave",cp,io),e.addEventListener("dragover",dp,io),e.addEventListener("drop",pp,io);let Ea=e.ownerDocument,up=l=>{yr()&&l.preventDefault()},gp=l=>{yr()&&l.preventDefault()};Ea.addEventListener("dragover",up),Ea.addEventListener("drop",gp),Ve.push(()=>{Q&&Q.removeEventListener("submit",zd),sp(Ce),ap.removeEventListener("keydown",qd,!0),en?.destroy()}),Ve.push(()=>{ge.removeEventListener("dragenter",lp,io),ge.removeEventListener("dragleave",cp,io),e.removeEventListener("dragover",dp,io),e.removeEventListener("drop",pp,io),Ea.removeEventListener("dragover",up),Ea.removeEventListener("drop",gp),Rl()}),Ve.push(()=>{$.cancel()}),Ot?Ve.push(()=>{Ot?.destroy()}):Vt&&Ve.push(()=>{Vt?.remove()});let Rt={update(l){let f=o.toolCall,h=o.messageActions,x=o.layout?.messages,A=o.colorScheme,R=o.loadingIndicator,X=o.iterationDisplay,F=o.features?.showReasoning,J=o.features?.showToolCalls,se=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=_i(o,l),da(),Zo(e,o),Ks(e,o),Gs(e,o),Hn(),o.colorScheme!==A&&Ad();let we=Js.getForInstance(o.plugins);r.length=0,r.push(...we),S=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,ae=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,de=o.features?.scrollToBottom??{};let Ge=qt();ee=o.features?.scrollBehavior??{},Ge!==qt()&&(rs(),ro()),dd(),nn();let gt=Z;if(Z=o.features?.showEventStreamToggle??!1,Z&&!gt){if(Ne||(pe=new qs(ye),Ne=new zs(ke,pe),$e=$e??new Vs,pe.open().then(()=>Ne?.restore()).catch(()=>{}),$.setSSEEventCallback((te,Xe)=>{o.onSSEEvent?.(te,Xe),$e?.processEvent(te,Xe),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Xe)})})),!nt&&O){let te=o.features?.eventStream?.classNames,Xe="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(te?.toggleButton?" "+te.toggleButton:"");nt=m("button",Xe),nt.style.width="28px",nt.style.height="28px",nt.style.color=Jt.actionIconColor,nt.type="button",nt.setAttribute("aria-label","Event Stream"),nt.title="Event Stream";let bt=ne("activity","18px","currentColor",1.5);bt&&nt.appendChild(bt);let rt=Pe.clearChatButtonWrapper,at=Pe.closeButtonWrapper,jt=rt||at;jt&&jt.parentNode===O?O.insertBefore(nt,jt):O.appendChild(nt),nt.addEventListener("click",()=>{ze?Gr():sl()})}}else!Z&&gt&&(Gr(),nt&&(nt.remove(),nt=null),Ne?.clear(),pe?.destroy(),Ne=null,pe=null,$e?.reset(),$e=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&Vt&&(Vt.remove(),Vt=null),o.launcher?.enabled!==!1&&!Ot&&!Vt){let{instance:te,element:Xe}=Sc({config:o,plugins:r,onToggle:Kd});Ot=te,te||(Vt=Xe),e.appendChild(Xe)}Ot&&Ot.update(o),B&&o.launcher?.title!==void 0&&(B.textContent=o.launcher.title),K&&o.launcher?.subtitle!==void 0&&(K.textContent=o.launcher.subtitle);let ot=o.layout?.header;if(ot?.layout!==z&&O){let te=ot?Nr(o,ot,{showClose:D(),onClose:()=>ut(!1,"user")}):Jn({config:o,showClose:D(),onClose:()=>ut(!1,"user")});lt.replaceHeader(te),O=lt.header.element,L=lt.header.iconHolder,B=lt.header.headerTitle,K=lt.header.headerSubtitle,E=lt.header.closeButton,z=ot?.layout}else if(ot){if(L&&(L.style.display=ot.showIcon===!1?"none":""),B&&(B.style.display=ot.showTitle===!1?"none":""),K&&(K.style.display=ot.showSubtitle===!1?"none":""),E){let te=D()&&ot.showCloseButton!==!1;E.style.display=te?"":"none"}if(Pe.clearChatButtonWrapper){let te=ot.showClearChat;if(te!==void 0){Pe.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Xe}=Pe;Xe&&!Xe.classList.contains("persona-absolute")&&(te?Xe.classList.remove("persona-ml-auto"):Xe.classList.add("persona-ml-auto"))}}}let Et=o.layout?.showHeader!==!1;O&&(O.style.display=Et?"":"none");let It=o.layout?.showFooter!==!1;U&&(U.style.display=It?"":"none"),ir(),nn(),S!==w?S?ut(I,"auto"):(N=!0,cs()):I!==q&&ut(I,"auto"),q=I,w=S,us(),np();let je=JSON.stringify(o.toolCall)!==JSON.stringify(f),Te=JSON.stringify(o.messageActions)!==JSON.stringify(h),Mt=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),ft=o.loadingIndicator?.render!==R?.render||o.loadingIndicator?.renderIdle!==R?.renderIdle||o.loadingIndicator?.showBubble!==R?.showBubble,Kt=o.iterationDisplay!==X,mt=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(J??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(je||Te||Mt||ft||Kt||mt)&&$&&(ul++,ss(xe,$.getMessages(),Me));let Wt=o.features?.streamAnimation?.type;if(Wt!==re&&Wt&&Wt!=="none"){let te=Dr(Wt,o.features?.streamAnimation?.plugins);te&&Ei(te,e)}let We=o.launcher??{},Ue=We.headerIconHidden??!1,Ft=o.layout?.header?.showIcon,_t=Ue||Ft===!1,St=We.headerIconName,pt=We.headerIconSize??"48px";if(L){let te=ge.querySelector(".persona-border-b-persona-divider"),Xe=te?.querySelector(".persona-flex-col");if(_t)L.style.display="none",te&&Xe&&!te.contains(Xe)&&te.insertBefore(Xe,te.firstChild);else{if(L.style.display="",L.style.height=pt,L.style.width=pt,te&&Xe&&(te.contains(L)?L.nextSibling!==Xe&&(L.remove(),te.insertBefore(L,Xe)):te.insertBefore(L,Xe)),St){let rt=parseFloat(pt)||24,at=ne(St,rt*.6,"currentColor",1);at?L.replaceChildren(at):L.textContent=We.agentIconText??"\u{1F4AC}"}else if(We.iconUrl){let rt=L.querySelector("img");if(rt)rt.src=We.iconUrl,rt.style.height=pt,rt.style.width=pt;else{let at=document.createElement("img");at.src=We.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=pt,at.style.width=pt,L.replaceChildren(at)}}else{let rt=L.querySelector("svg"),at=L.querySelector("img");(rt||at)&&L.replaceChildren(),L.textContent=We.agentIconText??"\u{1F4AC}"}let bt=L.querySelector("img");bt&&(bt.style.height=pt,bt.style.width=pt)}}let yt=o.layout?.header?.showTitle,tt=o.layout?.header?.showSubtitle;if(B&&(B.style.display=yt===!1?"none":""),K&&(K.style.display=tt===!1?"none":""),E){let te=D()&&o.layout?.header?.showCloseButton!==!1;E.style.display=te?"":"none";let Xe=We.closeButtonSize??"32px",bt=We.closeButtonPlacement??"inline";E.style.height=Xe,E.style.width=Xe;let{closeButtonWrapper:rt}=Pe,at=bt==="top-right",jt=rt?.classList.contains("persona-absolute");if(rt&&at!==jt)if(rt.remove(),at)rt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ge.style.position="relative",ge.appendChild(rt);else{let co=We.clearChat?.placement??"inline",hs=We.clearChat?.enabled??!0;rt.className=hs&&co==="inline"?"":"persona-ml-auto";let fp=ge.querySelector(".persona-border-b-persona-divider");fp&&fp.appendChild(rt)}if(E.style.color=We.closeButtonColor||Jt.actionIconColor,We.closeButtonBackgroundColor?(E.style.backgroundColor=We.closeButtonBackgroundColor,E.classList.remove("hover:persona-bg-gray-100")):(E.style.backgroundColor="",E.classList.add("hover:persona-bg-gray-100")),We.closeButtonBorderWidth||We.closeButtonBorderColor){let co=We.closeButtonBorderWidth||"0px",hs=We.closeButtonBorderColor||"transparent";E.style.border=`${co} solid ${hs}`,E.classList.remove("persona-border-none")}else E.style.border="",E.classList.add("persona-border-none");We.closeButtonBorderRadius?(E.style.borderRadius=We.closeButtonBorderRadius,E.classList.remove("persona-rounded-full")):(E.style.borderRadius="",E.classList.add("persona-rounded-full")),We.closeButtonPaddingX?(E.style.paddingLeft=We.closeButtonPaddingX,E.style.paddingRight=We.closeButtonPaddingX):(E.style.paddingLeft="",E.style.paddingRight=""),We.closeButtonPaddingY?(E.style.paddingTop=We.closeButtonPaddingY,E.style.paddingBottom=We.closeButtonPaddingY):(E.style.paddingTop="",E.style.paddingBottom="");let rn=We.closeButtonIconName??"x",xn=We.closeButtonIconText??"\xD7";E.innerHTML="";let Dt=ne(rn,"28px","currentColor",1);Dt?(Dt.style.display="block",E.appendChild(Dt)):E.textContent=xn;let Ut=We.closeButtonTooltipText??"Close chat",Fn=We.closeButtonShowTooltip??!0;E.setAttribute("aria-label",Ut),rt&&Nt({anchor:E,trigger:rt,text:()=>E?.getAttribute("aria-label")??Ut,enabled:Fn})}let{clearChatButton:Fe,clearChatButtonWrapper:vt}=Pe;if(Fe){let te=We.clearChat??{},Xe=te.enabled??!0,bt=o.layout?.header?.showClearChat,rt=bt!==void 0?bt:Xe,at=te.placement??"inline";if(vt){vt.style.display=rt?"":"none";let{closeButtonWrapper:jt}=Pe;!Y()&&jt&&!jt.classList.contains("persona-absolute")&&(rt?jt.classList.remove("persona-ml-auto"):jt.classList.add("persona-ml-auto"));let rn=at==="top-right",xn=vt.classList.contains("persona-absolute");if(!Y()&&rn!==xn&&rt){if(vt.remove(),rn)vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px",ge.style.position="relative",ge.appendChild(vt);else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let Ut=ge.querySelector(".persona-border-b-persona-divider"),Fn=Pe.closeButtonWrapper;Ut&&Fn&&Fn.parentElement===Ut?Ut.insertBefore(vt,Fn):Ut&&Ut.appendChild(vt)}let Dt=Pe.closeButtonWrapper;Dt&&!Dt.classList.contains("persona-absolute")&&(rn?Dt.classList.add("persona-ml-auto"):Dt.classList.remove("persona-ml-auto"))}}if(rt){if(!Y()){let co=te.size??"32px";Fe.style.height=co,Fe.style.width=co}let jt=te.iconName??"refresh-cw",rn=te.iconColor??"";Fe.style.color=rn||Jt.actionIconColor,Fe.innerHTML="";let xn=Y()?"14px":"20px",Dt=ne(jt,xn,"currentColor",1);if(Dt&&(Dt.style.display="block",Fe.appendChild(Dt)),te.backgroundColor?(Fe.style.backgroundColor=te.backgroundColor,Fe.classList.remove("hover:persona-bg-gray-100")):(Fe.style.backgroundColor="",Fe.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let co=te.borderWidth||"0px",hs=te.borderColor||"transparent";Fe.style.border=`${co} solid ${hs}`,Fe.classList.remove("persona-border-none")}else Fe.style.border="",Fe.classList.add("persona-border-none");te.borderRadius?(Fe.style.borderRadius=te.borderRadius,Fe.classList.remove("persona-rounded-full")):(Fe.style.borderRadius="",Fe.classList.add("persona-rounded-full")),te.paddingX?(Fe.style.paddingLeft=te.paddingX,Fe.style.paddingRight=te.paddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),te.paddingY?(Fe.style.paddingTop=te.paddingY,Fe.style.paddingBottom=te.paddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom="");let Ut=te.tooltipText??"Clear chat",Fn=te.showTooltip??!0;Fe.setAttribute("aria-label",Ut),vt&&Nt({anchor:Fe,trigger:vt,text:()=>Fe?.getAttribute("aria-label")??Ut,enabled:Fn})}}let $t=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Xs],un=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ar.message,ar.messageAndClick];W=Qs({parsers:$t,handlers:un,getSessionMetadata:y,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null}),Me=uf(o,W,Ae),$.updateConfig(o),ss(xe,$.getMessages(),Me),pl(),Nd(),xl($.isStreaming());let fs=o.voiceRecognition?.enabled===!0,Ma=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),kt=o.voiceRecognition?.provider?.type==="runtype";if(fs&&(Ma||kt))if(!G||!qe){let te=Fm(o.voiceRecognition,o.sendButton);te&&(G=te.micButton,qe=te.micButtonWrapper,Je.insertBefore(qe,fn),G.addEventListener("click",Ta),G.disabled=$.isStreaming())}else{let te=o.voiceRecognition??{},Xe=o.sendButton??{},bt=te.iconName??"mic",rt=Xe.size??"40px",at=te.iconSize??rt,jt=parseFloat(at)||24;G.style.width=at,G.style.height=at,G.style.minWidth=at,G.style.minHeight=at;let rn=te.iconColor??Xe.textColor;G.innerHTML="";let xn=ne(bt,jt,rn||"currentColor",1.5);xn?G.appendChild(xn):G.textContent="\u{1F3A4}";let Dt=te.backgroundColor??Xe.backgroundColor;Dt?G.style.backgroundColor=Dt:G.style.backgroundColor="",rn?G.style.color=rn:G.style.color="var(--persona-text, #111827)",te.borderWidth?(G.style.borderWidth=te.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),te.borderColor?G.style.borderColor=te.borderColor:G.style.borderColor="",te.paddingX?(G.style.paddingLeft=te.paddingX,G.style.paddingRight=te.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),te.paddingY?(G.style.paddingTop=te.paddingY,G.style.paddingBottom=te.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let Ut=te.tooltipText??"Start voice recognition",Fn=te.showTooltip??!1;G.setAttribute("aria-label",Ut),qe&&Nt({anchor:G,trigger:qe,text:()=>G?.getAttribute("aria-label")??Ut,enabled:Fn}),qe.style.display="",G.disabled=$.isStreaming()}else G&&qe&&(qe.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()&&$.toggleVoice():kn&&ao());if(o.attachments?.enabled===!0){if(!He||!Se){let te=o.attachments??{},bt=(o.sendButton??{}).size??"40px";Ze||(Ze=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ze.style.display="none",Q.insertBefore(Ze,Ce)),Re||(Re=document.createElement("input"),Re.type="file",Re.accept=(te.allowedTypes??Vn).join(","),Re.multiple=(te.maxFiles??4)>1,Re.style.display="none",Re.setAttribute("aria-label","Attach files"),Q.insertBefore(Re,Ce)),He=m("div","persona-send-button-wrapper"),Se=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Se.type="button",Se.setAttribute("aria-label",te.buttonTooltipText??"Attach file");let rt=te.buttonIconName??"paperclip",at=bt,jt=parseFloat(at)||40,rn=Math.round(jt*.6);Se.style.width=at,Se.style.height=at,Se.style.minWidth=at,Se.style.minHeight=at,Se.style.fontSize="18px",Se.style.lineHeight="1";let xn=ne(rt,rn,"currentColor",1.5);xn?Se.appendChild(xn):Se.textContent="\u{1F4CE}",Se.addEventListener("click",Ut=>{Ut.preventDefault(),Re?.click()}),He.appendChild(Se);let Dt=te.buttonTooltipText??"Attach file";Nt({anchor:Se,trigger:He,text:()=>Se?.getAttribute("aria-label")??Dt}),Ee?Ee.append(He):Q.appendChild(He),!Tt&&Re&&Ze&&(Tt=Yo.fromConfig(te),Tt.setPreviewsContainer(Ze),Re.addEventListener("change",async()=>{Tt&&Re?.files&&(await Tt.handleFileSelect(Re.files),Re.value="")}))}else{He.style.display="";let te=o.attachments??{};Re&&(Re.accept=(te.allowedTypes??Vn).join(","),Re.multiple=(te.maxFiles??4)>1),Tt&&Tt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}if(ge.querySelector(".persona-attachment-drop-overlay")?.remove(),ge.appendChild(gf(o.attachments?.dropOverlay)),Se){let te=o.attachments??{},Xe=te.buttonTooltipText??"Attach file";Se.setAttribute("aria-label",Xe),Se.textContent="";let bt=parseFloat(o.sendButton?.size??"40px")||40,rt=ne(te.buttonIconName??"paperclip",Math.round(bt*.6),"currentColor",1.5);rt?Se.appendChild(rt):Se.textContent="\u{1F4CE}",He&&Nt({anchor:Se,trigger:He,text:()=>Se?.getAttribute("aria-label")??Xe})}}else He&&(He.style.display="none"),Tt&&Tt.clearAttachments(),ge.querySelector(".persona-attachment-drop-overlay")?.remove();let Bt=o.sendButton??{},ms=Bt.useIcon??!1,La=Bt.iconText??"\u2191",br=Bt.iconName,Pa=Bt.tooltipText??"Send message",Il=Bt.showTooltip??!1,zo=Bt.size??"40px",Nn=Bt.backgroundColor,qo=Bt.textColor;if(ms){if(ue.style.width=zo,ue.style.height=zo,ue.style.minWidth=zo,ue.style.minHeight=zo,ue.style.fontSize="18px",ue.style.lineHeight="1",qo?ue.style.color=qo:ue.style.color="var(--persona-button-primary-fg, #ffffff)",!$.isStreaming())if(ue.innerHTML="",br){let te=parseFloat(zo)||24,Xe=qo?.trim()||"currentColor",bt=ne(br,te,Xe,2);bt?ue.appendChild(bt):ue.textContent=La}else ue.textContent=La;ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nn?(ue.style.backgroundColor=Nn,ue.classList.remove("persona-bg-persona-primary")):(ue.style.backgroundColor="",ue.classList.add("persona-bg-persona-primary"))}else ue.textContent=o.copy?.sendButtonLabel??"Send",ue.style.width="",ue.style.height="",ue.style.minWidth="",ue.style.minHeight="",ue.style.fontSize="",ue.style.lineHeight="",ue.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Nn?(ue.style.backgroundColor=Nn,ue.classList.remove("persona-bg-persona-accent")):ue.classList.add("persona-bg-persona-accent"),qo?ue.style.color=qo:ue.classList.add("persona-text-white");Bt.borderWidth?(ue.style.borderWidth=Bt.borderWidth,ue.style.borderStyle="solid"):(ue.style.borderWidth="",ue.style.borderStyle=""),Bt.borderColor?ue.style.borderColor=Bt.borderColor:ue.style.borderColor="",Bt.paddingX?(ue.style.paddingLeft=Bt.paddingX,ue.style.paddingRight=Bt.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),Bt.paddingY?(ue.style.paddingTop=Bt.paddingY,ue.style.paddingBottom=Bt.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom=""),$.isStreaming()||ue.setAttribute("aria-label",Pa),fn&&Nt({anchor:ue,trigger:fn,text:()=>ue.getAttribute("aria-label")??Pa,enabled:Il});let Ra=o.layout?.contentMaxWidth??(Y()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Ra?(xe.style.maxWidth=Ra,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",Q&&(Q.style.maxWidth=Ra,Q.style.marginLeft="auto",Q.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=Ra,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",Q&&(Q.style.maxWidth="",Q.style.marginLeft="",Q.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let lo=o.statusIndicator??{},qm=lo.visible??!0;if(M.style.display=qm?"":"none",$){let te=$.getStatus();ht(M,(bt=>bt==="idle"?lo.idleText??Ht.idle:bt==="connecting"?lo.connectingText??Ht.connecting:bt==="connected"?lo.connectedText??Ht.connected:bt==="error"?lo.errorText??Ht.error:Ht[bt])(te),lo,te)}M.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Vm=lo.align==="left"?"persona-text-left":lo.align==="center"?"persona-text-center":"persona-text-right";M.classList.add(Vm)},open(){D()&&ut(!0,"api")},close(){D()&&ut(!1,"api")},toggle(){D()&&ut(!N,"api")},reconnect(){$.reconnectNow()},clearChat(){Wn=!1,$.clearMessages(),Do.clear(),ro();try{localStorage.removeItem(qr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qr}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),d?.clear&&hl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},W.syncFromMetadata(),Ne?.clear(),$e?.reset(),Be?.update()},setMessage(l){return!Ce||$.isStreaming()?!1:(!N&&D()&&ut(!0,"system"),Ce.value=l,Ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let f=l?.trim()||Ce.value.trim();return f?(!N&&D()&&ut(!0,"system"),Ce.value="",Ce.style.height="auto",$.sendMessage(f),!0):!1},startVoiceRecognition(){return $.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()||(!N&&D()&&ut(!0,"system"),Ye.manuallyDeactivated=!1,vn(),$.toggleVoice().then(()=>{Ye.active=$.isVoiceActive(),Bn("user"),$.isVoiceActive()&&hr()})),!0):kn?!0:Vd()?(!N&&D()&&ut(!0,"system"),Ye.manuallyDeactivated=!1,vn(),Aa("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,vn(),Bn("user"),Dn()}),!0):!1:kn?(Ye.manuallyDeactivated=!0,vn(),ao("user"),!0):!1},injectMessage(l){return!N&&D()&&ut(!0,"system"),$.injectMessage(l)},injectAssistantMessage(l){!N&&D()&&ut(!0,"system");let f=$.injectAssistantMessage(l);return ce&&(ce=!1,he&&(clearTimeout(he),he=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),f},injectUserMessage(l){return!N&&D()&&ut(!0,"system"),$.injectUserMessage(l)},injectSystemMessage(l){return!N&&D()&&ut(!0,"system"),$.injectSystemMessage(l)},injectMessageBatch(l){return!N&&D()&&ut(!0,"system"),$.injectMessageBatch(l)},injectComponentDirective(l){return!N&&D()&&ut(!0,"system"),$.injectComponentDirective(l)},injectTestMessage(l){!N&&D()&&ut(!0,"system"),$.injectTestEvent(l)},async connectStream(l,f){return $.connectStream(l,f)},__pushEventStreamEvent(l){Ne&&($e?.processEvent(l.type,l.payload),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Z||!Ne||sl()},hideEventStream(){ze&&Gr()},isEventStreamVisible(){return ze},showArtifacts(){Xt(o)&&(Wn=!1,lr=!0,Hn(),et?.setMobileOpen(!0))},hideArtifacts(){Xt(o)&&(Wn=!0,Hn())},upsertArtifact(l){return Xt(o)?(Ko(o.features?.artifacts,l.artifactType)==="panel"&&(Wn=!1,lr=!0),$.upsertArtifact(l)):null},selectArtifact(l){Xt(o)&&$.selectArtifact(l)},clearArtifacts(){Xt(o)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return S&&!N&&!Y()||!Ce?!1:(Ce.focus(),!0)},async resolveApproval(l,f,h){let A=$.getMessages().find(R=>R.variant==="approval"&&R.approval?.id===l);if(!A?.approval)throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){$.resolveWebMcpApproval(A.id,f);return}return $.resolveApproval(A.approval,f,h)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){C(l)},on(l,f){return i.on(l,f)},off(l,f){i.off(l,f)},isOpen(){return D()&&N},isVoiceActive(){return Ye.active},toggleReadAloud(l){$.toggleReadAloud(l)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(l){return $.getReadAloudState(l)},onReadAloudChange(l){return $.onReadAloudChange(l)},getState(){return{open:D()&&N,launcherEnabled:S,voiceActive:Ye.active,streaming:$.isStreaming()}},showCSATFeedback(l){!N&&D()&&ut(!0,"system");let f=xe.querySelector(".persona-feedback-container");f&&f.remove();let h=qi({onSubmit:async(x,A)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!N&&D()&&ut(!0,"system");let f=xe.querySelector(".persona-feedback-container");f&&f.remove();let h=Vi({onSubmit:async(x,A)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,f){return $.submitCSATFeedback(l,f)},async submitNPSFeedback(l,f){return $.submitNPSFeedback(l,f)},destroy(){Sl(),jo!=null&&(clearInterval(jo),jo=null),Ve.forEach(l=>l()),De.remove(),Qe?.remove(),Ot?.destroy(),Vt?.remove(),Oo&&E.removeEventListener("click",Oo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,f={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:h=>h?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=f,Ve.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&Rt.focusInput()};if(window.addEventListener("persona:focusInput",f),Ve.push(()=>{window.removeEventListener("persona:focusInput",f)}),Z){let F=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===l)&&Rt.showEventStream()},J=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===l)&&Rt.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",J),Ve.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",J)})}let h=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&Rt.showArtifacts()},x=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&Rt.hideArtifacts()},A=F=>{let J=F.detail;J?.instanceId&&J.instanceId!==l||J?.artifact&&Rt.upsertArtifact(J.artifact)},R=F=>{let J=F.detail;J?.instanceId&&J.instanceId!==l||typeof J?.id=="string"&&Rt.selectArtifact(J.id)},X=F=>{let J=F.detail;(!J?.instanceId||J.instanceId===l)&&Rt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",X),Ve.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",X)})}let pn=Bv(o.persistState);if(pn&&D()){let l=Ov(pn.storage),f=`${pn.keyPrefix}widget-open`,h=`${pn.keyPrefix}widget-voice`,x=`${pn.keyPrefix}widget-voice-mode`;if(l){let A=pn.persist?.openState&&l.getItem(f)==="true",R=pn.persist?.voiceState&&l.getItem(h)==="true",X=pn.persist?.voiceState&&l.getItem(x)==="true";if(A&&setTimeout(()=>{Rt.open(),setTimeout(()=>{if(R||X)Rt.startVoiceRecognition();else if(pn.persist?.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),pn.persist?.openState&&(i.on("widget:opened",()=>{l.setItem(f,"true")}),i.on("widget:closed",()=>{l.setItem(f,"false")})),pn.persist?.voiceState&&(i.on("voice:state",F=>{l.setItem(h,F.active?"true":"false")}),i.on("user:message",F=>{l.setItem(x,F.viaVoice?"true":"false")})),pn.clearOnChatClear){let F=()=>{l.removeItem(f),l.removeItem(h),l.removeItem(x)},J=()=>F();window.addEventListener("persona:clear-chat",J),Ve.push(()=>{window.removeEventListener("persona:clear-chat",J)})}}}if(b&&D()&&setTimeout(()=>{Rt.open()},0),gr(),!cm){let l=Cr(()=>{$&&(ul++,Do.clear(),ss(xe,$.getMessages(),Me))});Ve.push(l)}return Rt};var ff=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Fv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},_v=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},$v=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&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.")},mf=(e,t)=>{let n=t?.launcher?.enabled??!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",e.style.minWidth=n?"":"0"},qc=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=""},hf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",qc(e)},jc=e=>{e.style.transition=""},Uc=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=""},zc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ji=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},jv=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},Uv=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},zv=e=>{let t=Co(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Gt(t,r)??r;return{inset:o(n?.inset,ii),canvasBackground:o(n?.canvasBackground,li)}},yf=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},qv=(e,t,n,o,r,s,a,i)=>{let p=Zt(s),d=p.reveal==="push",c=i!=null,u=i?.inset??"",b=i?.canvasBackground??"";jv(e,t,n,o,d),Uv(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.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",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=e.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,k=g!=null?g.innerWidth<=C:!1;if(y&&k&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Uc(t),jc(o),hf(o),zc(n),Ji(r,o),yf(o,!1,"",""),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",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??zt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.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"),hf(o),Fv(o,p.maxHeight),yf(o,c&&a,u,b),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Uc(t),jc(o),zc(n),Ji(r,o);let W=p.animate?"transform 180ms ease":"none",S=p.side==="right"?"translateX(100%)":"translateX(-100%)",I=a?"translateX(0)":S;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=W,o.style.transform=I,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",jc(o),qc(o),Ji(r,o);let W=ff(p.width,e.clientWidth),S=Math.max(0,e.clientWidth),I=p.animate?"margin-left 180ms ease":"none",j=p.side==="right"?a?-W:0:a?0:-W;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${S+W}px`,t.style.transition=I,t.style.marginLeft=`${j}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${S}px`,n.style.maxWidth=`${S}px`,n.style.minWidth=`${S}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Uc(t),qc(o),zc(n),Ji(r,o);let W=p.reveal==="emerge";W?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=a?p.width:"0px",I=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",j=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",_v(o,p.maxHeight),o.style.overflow=W||j?"hidden":"visible",o.style.transition=I,W){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let q=c?`calc(${ff(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=q,r.style.minWidth=q,r.style.maxWidth=q,r.style.boxSizing="border-box"}}},Vv=(e,t)=>{let n=e.ownerDocument.createElement("div");return mf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){mf(n,o)},destroy(){n.remove()}}},Kv=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let b=null,g=()=>{b?.disconnect(),b=null},y=null,C=()=>{y=t?.launcher?.detachedPanel===!0?zv(t):null};C();let k=()=>{qv(a,i,p,d,c,t,u,y)},P=null,W=()=>{P?.(),P=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(P=Wr(()=>{C(),k()}))},S=()=>{g(),Zt(t).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{k()}),b.observe(a)))},I=!1,j=()=>{k(),S(),u&&!I&&a.dataset.personaDockMobileFullscreen!=="true"&&(I=!0,$v(a,Zt(t)))},q=a.ownerDocument.defaultView,w=()=>{j()};return q?.addEventListener("resize",w),Zt(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),j(),W(),{mode:"docked",host:c,shell:a,syncWidgetState(z){let V=z.launcherEnabled?z.open:!0;u!==V&&(u=V,j())},updateConfig(z){t=z,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),j(),W()},destroy(){q?.removeEventListener("resize",w),P?.(),P=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Zs=(e,t)=>Lt(t)?Kv(e,t):Vv(e,t);var Gv=e=>{if(typeof window>"u"||typeof document>"u")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},bf=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},Vc=e=>{let t=Gv(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=Zs(t,r),a,i=[],p=(k,P)=>{let S=!(P?.launcher?.enabled??!0)||Lt(P),I=o.createElement("div");if(I.setAttribute("data-persona-root","true"),S&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0",I.style.minWidth="0"),n){let j=k.attachShadow({mode:"open"});j.appendChild(I),bf(j,o)}else k.appendChild(I),bf(k,o);return t.id&&I.setAttribute("data-persona-instance",t.id),I},d=()=>{s.syncWidgetState(a.getState())},c=()=>{i.forEach(k=>k()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},u=()=>{let k=p(s.host,r);a=Gi(k,r,{debugTools:e.debugTools}),c()},b=()=>{i.forEach(k=>k()),i=[],a.destroy()};u(),e.onChatReady?.();let g=k=>{b(),s.destroy(),s=Zs(t,k),r=k,u()},y={update(k){let P=_i(r??{},k),W=Lt(r),S=Lt(P),I=ko(r),j=ko(P);if(W!==S||I!==j){g(P);return}r=P,s.updateConfig(r),a.update(k),d()},destroy(){b(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(y,{get(k,P,W){if(P==="host")return s.host;if(P in k)return Reflect.get(k,P,W);let S=a[P];return typeof S=="function"?S.bind(a):S}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function Jv(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function Xv(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:Jv(o,n)?2:3}function vf(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Xi(e,t){let n=t.trim();if(!n)return[...e].sort(vf);let o=[];for(let r of e){let s=Xv(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:vf(r.item,s.item)),o.map(r=>r.item)}function Qv(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function xf(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Xi(e.items,t),resolve:e.resolve}}function Cf(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>Xi(t,Qv(r).name),resolve:(r,s)=>{let a=n.get(r.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(s.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(s.args):a.prompt??""}:{}}}}var Ef=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Yv=new Set(["button","a","input","select","textarea","details","summary"]),Zv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Kc=/\b(product|card|item|listing|result)\b/i,Jc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,ex=3e3,tx=100;function Mf(e){let t=typeof e.className=="string"?e.className:"";if(Kc.test(t)||e.id&&Kc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Kc.test(o.value))return!0}return!1}function kf(e){return Jc.test((e.textContent??"").trim())}function Lf(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function nx(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function wf(e){let t=e.match(Jc);return t?t[0]:null}function Af(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function ox(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var rx="commerce-card",sx="result-card";function Sf(e){return!Mf(e)||!kf(e)||!Lf(e)&&!nx(e)?0:5200}function Tf(e){return!Mf(e)||kf(e)||!Lf(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Xc=[{id:rx,scoreElement(e){return Sf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Jc.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Sf(e)===0)return null;let{title:n,href:o}=Af(e),r=wf((e.textContent??"").trim())??wf(t.text)??"",s=ox(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
143
+ `)}},{id:sx,scoreElement(e){return Tf(e)},formatSummary(e,t){if(Tf(e)===0)return null;let{title:n,href:o}=Af(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
144
+ `)}}];function ax(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function ix(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,i=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??Xc;return i==="simple"&&e.rules&&e.rules.length>0?(ax(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:d}}function Gc(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var lx=["data-testid","data-product","data-action","data-id","data-name","data-type"];function cx(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"||Yv.has(t)||n&&Zv.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Pf(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 dx(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function Qc(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Gc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of lx){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${Gc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(a=>Gc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${r}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function px(e){return e==="static"?tx:ex}function Rf(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Qc(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:cx(e),attributes:dx(e)}}function ux(e,t,n,o){let r=px(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,o);i>0&&(r+=i,a.formatSummary&&!s&&(s=a))}return{score:r,formattingRule:s}}function gx(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function fx(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&r.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,c=d.tagName.toLowerCase();if(Ef.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Pf(d)){i=a.nextNode();continue}let u=Rf(d,e.maxTextLength),b=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(k=>k==="role");if(!b&&!g){i=a.nextNode();continue}if(o.has(u.selector)){i=a.nextNode();continue}o.add(u.selector);let{score:y,formattingRule:C}=ux(d,u,e.rules,n);r.push({el:d,domIndex:s,enriched:u,score:y,formattingRule:C}),s+=1}i=a.nextNode()}r.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return u!==b?u-b:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of r){if(p.length>=e.maxElements)break;gx(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return u!==b?u-b:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let b=d.formattingRule.formatSummary(d.el,d.enriched,n);b&&(c=b)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function mx(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let p=s,d=p.tagName.toLowerCase();if(Ef.has(d)){s=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Pf(p)){s=r.nextNode();continue}let c=Rf(p,e.maxTextLength),u=c.text.length>0,b=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(g=>g==="role");if(!u&&!b){s=r.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}s=r.nextNode()}let a=[],i=[];for(let p of n)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function If(e={}){let t=ix(e),n=t.root??document.body;return n?t.mode==="simple"?mx(t,n):fx(t,n):[]}var Qi=100;function Wf(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);s.length>0&&o.push(`Structured summaries:
145
145
  ${s.map(a=>`- ${a.split(`
146
146
  `).join(`
147
147
  `)}`).join(`
148
- `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,qi)}" (clickable)`);o.push(`Interactive elements:
148
+ `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,Qi)}" (clickable)`);o.push(`Interactive elements:
149
149
  ${s.join(`
150
- `)}`)}if(r.navigable.length>0){let s=r.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,qi)}" (navigable)`);o.push(`Navigation links:
150
+ `)}`)}if(r.navigable.length>0){let s=r.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,Qi)}" (navigable)`);o.push(`Navigation links:
151
151
  ${s.join(`
152
- `)}`)}if(r.input.length>0){let s=r.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,qi)}" (input)`);o.push(`Form inputs:
152
+ `)}`)}if(r.input.length>0){let s=r.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,Qi)}" (input)`);o.push(`Form inputs:
153
153
  ${s.join(`
154
- `)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,qi)}"`);o.push(`Content:
154
+ `)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,Qi)}"`);o.push(`Content:
155
155
  ${s.join(`
156
156
  `)}`)}return o.join(`
157
157
 
158
- `)}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){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:Wn(e.colors.primary,.95),100:Wn(e.colors.primary,.9),200:Wn(e.colors.primary,.8),300:Wn(e.colors.primary,.7),400:Wn(e.colors.primary,.6),500:e.colors.primary,600:Wn(e.colors.primary,.8),700:Wn(e.colors.primary,.7),800:Wn(e.colors.primary,.6),900:Wn(e.colors.primary,.5),950:Wn(e.colors.primary,.45)}}),{...t,palette:n}}}}function Rf(){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 If(){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 Wn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),i=Math.round(r+(255-r)*(1-t));return`#${s.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 dx={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"}}},Jc={id:"shop",label:"Shopping Assistant",config:{theme:dx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:sn},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?"]}},Xc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Hf}},Qc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Hf}},Yc={shop:Jc,minimal:Xc,fullscreen:Qc};function Bf(e){return Yc[e]}var Of=Uc;function Xn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function px(e){if(e)return{getHeaders:Xn(e.getHeaders),onFeedback:Xn(e.onFeedback),onCopy:Xn(e.onCopy),requestMiddleware:Xn(e.requestMiddleware),actionHandlers:Xn(e.actionHandlers),actionParsers:Xn(e.actionParsers),postprocessMessage:Xn(e.postprocessMessage),contextProviders:Xn(e.contextProviders),streamParser:Xn(e.streamParser)}}var Df=`({ text, message }: any) => {
158
+ `)}function Hf(){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 Bf(){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 Of(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:In(e.colors.primary,.95),100:In(e.colors.primary,.9),200:In(e.colors.primary,.8),300:In(e.colors.primary,.7),400:In(e.colors.primary,.6),500:e.colors.primary,600:In(e.colors.primary,.8),700:In(e.colors.primary,.7),800:In(e.colors.primary,.6),900:In(e.colors.primary,.5),950:In(e.colors.primary,.45)}}),{...t,palette:n}}}}function Df(){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 Nf(){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 In(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),i=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Ff(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var hx={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"}}},_f={components:{panel:{borderRadius:"0",shadow:"none"}}},Yc={id:"shop",label:"Shopping Assistant",config:{theme:hx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:sn},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?"]}},Zc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:_f}},ed={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:_f}},td={shop:Yc,minimal:Zc,fullscreen:ed};function $f(e){return td[e]}var jf=Vc;function nd(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${qn}/dist`}function Xn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function yx(e){if(e)return{getHeaders:Xn(e.getHeaders),onFeedback:Xn(e.onFeedback),onCopy:Xn(e.onCopy),requestMiddleware:Xn(e.requestMiddleware),actionHandlers:Xn(e.actionHandlers),actionParsers:Xn(e.actionParsers),postprocessMessage:Xn(e.postprocessMessage),contextProviders:Xn(e.contextProviders),streamParser:Xn(e.streamParser)}}var Uf=`({ text, message }: any) => {
159
159
  const jsonSource = (message as any).rawContent || text || message.content;
160
160
  if (!jsonSource || typeof jsonSource !== 'string') return null;
161
161
  let cleanJson = jsonSource
@@ -168,7 +168,7 @@ ${s.join(`
168
168
  if (parsed.action) return { type: parsed.action, payload: parsed };
169
169
  } catch (e) { return null; }
170
170
  return null;
171
- }`,Nf=`function(ctx) {
171
+ }`,zf=`function(ctx) {
172
172
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
173
173
  if (!jsonSource || typeof jsonSource !== 'string') return null;
174
174
  var cleanJson = jsonSource
@@ -181,7 +181,7 @@ ${s.join(`
181
181
  if (parsed.action) return { type: parsed.action, payload: parsed };
182
182
  } catch (e) { return null; }
183
183
  return null;
184
- }`,Ff=`(action: any, context: any) => {
184
+ }`,qf=`(action: any, context: any) => {
185
185
  if (action.type !== 'nav_then_click') return;
186
186
  const payload = action.payload || action.raw || {};
187
187
  const url = payload?.page;
@@ -198,7 +198,7 @@ ${s.join(`
198
198
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
199
199
  window.location.href = targetUrl;
200
200
  return { handled: true, displayText: text };
201
- }`,_f=`function(action, context) {
201
+ }`,Vf=`function(action, context) {
202
202
  if (action.type !== 'nav_then_click') return;
203
203
  var payload = action.payload || action.raw || {};
204
204
  var url = payload.page;
@@ -215,26 +215,26 @@ ${s.join(`
215
215
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
216
216
  window.location.href = targetUrl;
217
217
  return { handled: true, displayText: text };
218
- }`,ux=`(parsed: any) => {
218
+ }`,bx=`(parsed: any) => {
219
219
  if (!parsed || typeof parsed !== 'object') return null;
220
220
  if (parsed.action === 'nav_then_click') return 'Navigating...';
221
221
  if (parsed.action === 'message') return parsed.text || '';
222
222
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
223
223
  return parsed.text || null;
224
- }`,gx=`function(parsed) {
224
+ }`,vx=`function(parsed) {
225
225
  if (!parsed || typeof parsed !== 'object') return null;
226
226
  if (parsed.action === 'nav_then_click') return 'Navigating...';
227
227
  if (parsed.action === 'message') return parsed.text || '';
228
228
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
229
229
  return parsed.text || null;
230
- }`;function fx(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 Vi(e){return e.parserType??fx(e.streamParser)??"plain"}function Ki(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function Gi(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?o.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${a}: ${i},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function Ji(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Xi(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,p])=>{typeof p=="string"?n.push(`${t} ${i}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${i}: ${p},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${t} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${p}: ${d},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Zc(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(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),$f(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Lo(e,t,n,o){n&&(e.push(`${o}${t}: {`),$f(e,n,`${o} `),e.push(`${o}},`))}function Ys(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function jf(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:px(n.hooks)}:void 0;return t==="esm"?mx(o,r):t==="script-installer"?bx(o,r):t==="script-advanced"?xx(o,r):t==="react-component"?hx(o,r):t==="react-advanced"?yx(o,r):vx(o,r)}function mx(e,t){let n=t?.hooks,o=Vi(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ys(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lo(s,"theme",e.theme," "),e.launcher&&Lo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ki(e," ")),s.push(...Gi(e," ",n)),s.push(...Ji(e," ")),s.push(...Xi(e," ")),s.push(...Zc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
231
- `)}function hx(e,t){let n=t?.hooks,o=Vi(e),r=o!=="plain",s=["// 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: '${Ys(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lo(s,"theme",e.theme," "),e.launcher&&Lo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ki(e," ")),s.push(...Gi(e," ",n)),s.push(...Ji(e," ")),s.push(...Xi(e," ")),s.push(...Zc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
232
- `)}function yx(e,t){let n=t?.hooks,o=["// 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: '${Ys(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lo(o,"theme",e.theme," "),e.launcher&&Lo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),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(...Ki(e," ")),o.push(...Gi(e," ",n)),o.push(...Ji(e," ")),o.push(...Xi(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${ux}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Df}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Df}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${Ff}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${Ff}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),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: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
233
- `)}function Uf(e){let t=Vi(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)s.avatar=i;else if(a==="timestamp"&&typeof i=="object"&&i!==null){let p={};Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(p[d]=c)}),Object.keys(p).length>0&&(s.timestamp=p)}else(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function bx(e,t){let n=Uf(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fn}/dist/install.global.js" data-config='${s}'></script>`}function vx(e,t){let n=t?.hooks,o=Vi(e),r=o!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ys(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lo(s,"theme",e.theme," "),e.launcher&&Lo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ki(e," ")),s.push(...Gi(e," ",n)),s.push(...Ji(e," ")),s.push(...Xi(e," ")),s.push(...Zc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
234
- `)}function xx(e,t){let n=t?.hooks,o=Uf(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
230
+ }`;function xx(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 Yi(e){return e.parserType??xx(e.streamParser)??"plain"}function Zi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function el(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?o.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${a}: ${i},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function tl(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function nl(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,p])=>{typeof p=="string"?n.push(`${t} ${i}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${i}: ${p},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${t} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${p}: ${d},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function od(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 Kf(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),Kf(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Lo(e,t,n,o){n&&(e.push(`${o}${t}: {`),Kf(e,n,`${o} `),e.push(`${o}},`))}function ea(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Gf(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:yx(n.hooks)}:void 0;return t==="esm"?Cx(o,r):t==="script-installer"?Sx(o,r):t==="script-advanced"?Ex(o,r):t==="react-component"?wx(o,r):t==="react-advanced"?Ax(o,r):Tx(o,r)}function Cx(e,t){let n=t?.hooks,o=Yi(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${ea(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lo(s,"theme",e.theme," "),e.launcher&&Lo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Zi(e," ")),s.push(...el(e," ",n)),s.push(...tl(e," ")),s.push(...nl(e," ")),s.push(...od(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
231
+ `)}function wx(e,t){let n=t?.hooks,o=Yi(e),r=o!=="plain",s=["// 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: '${ea(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lo(s,"theme",e.theme," "),e.launcher&&Lo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Zi(e," ")),s.push(...el(e," ",n)),s.push(...tl(e," ")),s.push(...nl(e," ")),s.push(...od(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
232
+ `)}function Ax(e,t){let n=t?.hooks,o=["// 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: '${ea(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lo(o,"theme",e.theme," "),e.launcher&&Lo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),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(...Zi(e," ")),o.push(...el(e," ",n)),o.push(...tl(e," ")),o.push(...nl(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${bx}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Uf}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Uf}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${qf}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${qf}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),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: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
233
+ `)}function Jf(e){let t=Yi(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)s.avatar=i;else if(a==="timestamp"&&typeof i=="object"&&i!==null){let p={};Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(p[d]=c)}),Object.keys(p).length>0&&(s.timestamp=p)}else(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function Sx(e,t){let n=Jf(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="${nd(t)}/install.global.js" data-config='${s}'></script>`}function Tx(e,t){let n=t?.hooks,o=Yi(e),r=o!=="plain",s=nd(t),a=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${ea(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),r&&a.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lo(a,"theme",e.theme," "),e.launcher&&Lo(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([i,p])=>{a.push(` ${i}: "${p}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"?a.push(` ${i}: ${p},`):typeof p=="number"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([i,p])=>{a.push(` ${i}: ${p},`)}),a.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{a.push(` "${i}",`)}),a.push(" ],")),e.suggestionChipsConfig&&(a.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(" },")),a.push(...Zi(e," ")),a.push(...el(e," ",n)),a.push(...tl(e," ")),a.push(...nl(e," ")),a.push(...od(n," ")),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push("</script>"),a.join(`
234
+ `)}function Ex(e,t){let n=t?.hooks,o=Jf(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
235
235
  `).map((a,i)=>i===0?a:" "+a).join(`
236
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fn}/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?.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${gx});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Nf}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Nf}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${_f}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${_f}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.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: '${Ys(t)}',`," useShadowDom: false,",...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>"),s.join(`
237
- `)}var zf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},qf=.1,Vf=.15,Kf=1.5,ed=24,Gf=40,Cx=`
236
+ `)};`,""," // Constants",` var CDN_BASE = '${nd(t)}';`," 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?.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${vx});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${zf}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${zf}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Vf}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Vf}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.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: '${ea(t)}',`," useShadowDom: false,",...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>"),s.join(`
237
+ `)}var Xf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Qf=.1,Yf=.15,Zf=1.5,rd=24,em=40,Mx=`
238
238
  /* \u2500\u2500 Root \u2500\u2500 */
239
239
  .persona-dc-root {
240
240
  display: flex;
@@ -385,7 +385,7 @@ ${s.join(`
385
385
  .persona-dc-stage {
386
386
  height: 550px;
387
387
  min-height: 400px;
388
- padding: ${ed}px;
388
+ padding: ${rd}px;
389
389
  overflow: auto;
390
390
  background: #f0f1f3;
391
391
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -475,5 +475,5 @@ ${s.join(`
475
475
  min-height: 300px;
476
476
  }
477
477
  }
478
- `;function wx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Cx,document.head.appendChild(e)}function Ax(e,t){let n=e.clientWidth-ed*2-Gf,o=e.clientHeight-ed*2-Gf;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function Sx(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function Jf(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:d}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");wx();let c=Math.max(0,Math.min(o,n.length-1)),u=r,b=s,g=null,y=1,C=!1,k=m("div","persona-dc-root"),P=m("div","persona-dc-toolbar"),W=m("div","persona-dc-toolbar-lead"),S=m("div","persona-dc-toolbar-trail"),I=ct({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>$e(-1)}),j=m("div");j.style.position="relative";let q=m("button","persona-dc-title-btn");q.type="button",q.setAttribute("aria-expanded","false"),q.setAttribute("aria-haspopup","listbox");let w=m("span","persona-dc-title-text"),z=m("span","persona-dc-title-chevron"),V=ne("chevron-down",12,"currentColor",2);V&&z.appendChild(V),q.append(w,z);let Y=m("div","persona-dc-dropdown");Y.setAttribute("role","listbox"),Y.style.display="none";let D=!1;function N(){Y.innerHTML="";for(let oe=0;oe<n.length;oe++){let Oe=n[oe],xt=m("button","persona-dc-dropdown-item");xt.type="button",xt.setAttribute("role","option"),xt.setAttribute("aria-current",oe===c?"true":"false");let ht=m("span");if(ht.textContent=Oe.title,xt.appendChild(ht),Oe.description){let lt=m("span","persona-dc-dropdown-desc");lt.textContent=Oe.description,xt.appendChild(lt)}xt.addEventListener("click",()=>{he(),Be(oe)}),Y.appendChild(xt)}}function le(){D=!D,Y.style.display=D?"":"none",q.setAttribute("aria-expanded",D?"true":"false"),D&&N()}function he(){D&&(D=!1,Y.style.display="none",q.setAttribute("aria-expanded","false"))}q.addEventListener("click",oe=>{oe.stopPropagation(),le()});let Ae=()=>he();document.addEventListener("click",Ae),j.append(q,Y);let Me=ct({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>$e(1)}),ae=m("span","persona-dc-counter");W.append(I,j,Me,ae);let me=null;i&&(me=Gn({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:oe=>{u=oe,ye.dataset.device=u,g=null,ze()}}),S.appendChild(me.element));let Z=null;if(a){let oe=m("div","persona-dc-zoom-controls"),Oe=ct({icon:"minus",label:"Zoom out",size:14,onClick:()=>{g=Math.max(Vf,(g??y)-qf),ze()}});Z=m("span","persona-dc-zoom-level"),Z.title="Reset to 100%",Z.style.cursor="pointer",Z.addEventListener("click",()=>{g=1,ze()});let xt=ct({icon:"plus",label:"Zoom in",size:14,onClick:()=>{g=Math.min(Kf,(g??y)+qf),ze()}}),ht=ct({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,ze()}});oe.append(Oe,Z,xt,ht),S.appendChild(oe)}if(p){let oe=m("div","persona-dc-separator");S.appendChild(oe);let Oe=Gn({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:b,onSelect:xt=>{b=xt,ye.dataset.colorScheme=b,ke()}});S.appendChild(Oe.element)}let de=m("div","persona-dc-separator");S.appendChild(de);let ee=ct({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});S.appendChild(ee),P.append(W,S);let ve=m("div","persona-dc-stage"),ye=m("div","persona-dc-iframe-wrapper");ye.dataset.device=u,ye.dataset.colorScheme=b;let pe=m("iframe","persona-dc-iframe");pe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),pe.setAttribute("loading","lazy"),pe.title=n[c].title,ye.appendChild(pe),ve.appendChild(ye),k.append(P,ve),e.appendChild(k);function ke(){try{let oe=pe.contentDocument?.body;if(!oe)return;b==="dark"?oe.classList.add("theme-dark"):oe.classList.remove("theme-dark")}catch{}}pe.addEventListener("load",()=>ke());function Ne(){let oe=n[c];w.textContent=oe.title,ae.textContent=`${c+1} / ${n.length}`,pe.title=oe.title}function $e(oe){let Oe=((c+oe)%n.length+n.length)%n.length;Be(Oe)}function Be(oe){oe<0||oe>=n.length||(c=oe,pe.src=n[c].url,Ne(),d?.(c,n[c]))}function ze(){if(C)return;let oe=zf[u]??zf.desktop;y=Ax(ve,oe);let Oe=Math.max(Vf,Math.min(Kf,g??y));Sx(ye,pe,oe,Oe,u),Z&&(Z.textContent=`${Math.round(Oe*100)}%`)}let Ke=new ResizeObserver(()=>ze());Ke.observe(ve),Ne(),pe.src=n[c].url,requestAnimationFrame(()=>ze());function Le(){C||(C=!0,Ke.disconnect(),document.removeEventListener("click",Ae),k.remove())}return{element:k,goTo:Be,next:()=>$e(1),prev:()=>$e(-1),getIndex:()=>c,setDevice(oe){u=oe,ye.dataset.device=oe,me?.setSelected(oe),g=null,ze()},setColorScheme(oe){b=oe,ye.dataset.colorScheme=oe},setZoom(oe){g=oe,ze()},destroy:Le}}0&&(module.exports={ASK_USER_QUESTION_CLIENT_TOOL,ASK_USER_QUESTION_PARAMETERS_SCHEMA,ASK_USER_QUESTION_TOOL_NAME,AgentWidgetClient,AgentWidgetSession,AttachmentManager,BrowserSpeechEngine,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,ReadAloudController,SUGGEST_REPLIES_CLIENT_TOOL,SUGGEST_REPLIES_PARAMETERS_SCHEMA,SUGGEST_REPLIES_TOOL_NAME,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,builtInClientToolsForDispatch,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createAskUserQuestionBubble,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createRovingTablist,createSlashCommandsSource,createStandardBubble,createStaticMentionSource,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultMentionFilter,defaultParseRules,detectColorScheme,directivePostprocessor,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isSuggestRepliesMessage,isVoiceSupported,isWebMcpToolName,latestAgentSuggestions,listRegisteredStreamAnimations,loadMarkdownParsers,markdownPostprocessor,mergeWithDefaults,normalizeContent,onMarkdownParsersReady,parseAskUserQuestionPayload,parseSuggestRepliesPayload,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveDockConfig,resolveSanitizer,resolveTokens,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
478
+ `;function kx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Mx,document.head.appendChild(e)}function Lx(e,t){let n=e.clientWidth-rd*2-em,o=e.clientHeight-rd*2-em;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function Px(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function tm(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:d}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");kx();let c=Math.max(0,Math.min(o,n.length-1)),u=r,b=s,g=null,y=1,C=!1,k=m("div","persona-dc-root"),P=m("div","persona-dc-toolbar"),W=m("div","persona-dc-toolbar-lead"),S=m("div","persona-dc-toolbar-trail"),I=ct({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>$e(-1)}),j=m("div");j.style.position="relative";let q=m("button","persona-dc-title-btn");q.type="button",q.setAttribute("aria-expanded","false"),q.setAttribute("aria-haspopup","listbox");let w=m("span","persona-dc-title-text"),z=m("span","persona-dc-title-chevron"),V=ne("chevron-down",12,"currentColor",2);V&&z.appendChild(V),q.append(w,z);let Y=m("div","persona-dc-dropdown");Y.setAttribute("role","listbox"),Y.style.display="none";let D=!1;function N(){Y.innerHTML="";for(let oe=0;oe<n.length;oe++){let Oe=n[oe],xt=m("button","persona-dc-dropdown-item");xt.type="button",xt.setAttribute("role","option"),xt.setAttribute("aria-current",oe===c?"true":"false");let ht=m("span");if(ht.textContent=Oe.title,xt.appendChild(ht),Oe.description){let lt=m("span","persona-dc-dropdown-desc");lt.textContent=Oe.description,xt.appendChild(lt)}xt.addEventListener("click",()=>{he(),Be(oe)}),Y.appendChild(xt)}}function ce(){D=!D,Y.style.display=D?"":"none",q.setAttribute("aria-expanded",D?"true":"false"),D&&N()}function he(){D&&(D=!1,Y.style.display="none",q.setAttribute("aria-expanded","false"))}q.addEventListener("click",oe=>{oe.stopPropagation(),ce()});let Ae=()=>he();document.addEventListener("click",Ae),j.append(q,Y);let Me=ct({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>$e(1)}),ae=m("span","persona-dc-counter");W.append(I,j,Me,ae);let me=null;i&&(me=Gn({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:oe=>{u=oe,ye.dataset.device=u,g=null,ze()}}),S.appendChild(me.element));let Z=null;if(a){let oe=m("div","persona-dc-zoom-controls"),Oe=ct({icon:"minus",label:"Zoom out",size:14,onClick:()=>{g=Math.max(Yf,(g??y)-Qf),ze()}});Z=m("span","persona-dc-zoom-level"),Z.title="Reset to 100%",Z.style.cursor="pointer",Z.addEventListener("click",()=>{g=1,ze()});let xt=ct({icon:"plus",label:"Zoom in",size:14,onClick:()=>{g=Math.min(Zf,(g??y)+Qf),ze()}}),ht=ct({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,ze()}});oe.append(Oe,Z,xt,ht),S.appendChild(oe)}if(p){let oe=m("div","persona-dc-separator");S.appendChild(oe);let Oe=Gn({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:b,onSelect:xt=>{b=xt,ye.dataset.colorScheme=b,ke()}});S.appendChild(Oe.element)}let de=m("div","persona-dc-separator");S.appendChild(de);let ee=ct({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});S.appendChild(ee),P.append(W,S);let ve=m("div","persona-dc-stage"),ye=m("div","persona-dc-iframe-wrapper");ye.dataset.device=u,ye.dataset.colorScheme=b;let pe=m("iframe","persona-dc-iframe");pe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),pe.setAttribute("loading","lazy"),pe.title=n[c].title,ye.appendChild(pe),ve.appendChild(ye),k.append(P,ve),e.appendChild(k);function ke(){try{let oe=pe.contentDocument?.body;if(!oe)return;b==="dark"?oe.classList.add("theme-dark"):oe.classList.remove("theme-dark")}catch{}}pe.addEventListener("load",()=>ke());function Ne(){let oe=n[c];w.textContent=oe.title,ae.textContent=`${c+1} / ${n.length}`,pe.title=oe.title}function $e(oe){let Oe=((c+oe)%n.length+n.length)%n.length;Be(Oe)}function Be(oe){oe<0||oe>=n.length||(c=oe,pe.src=n[c].url,Ne(),d?.(c,n[c]))}function ze(){if(C)return;let oe=Xf[u]??Xf.desktop;y=Lx(ve,oe);let Oe=Math.max(Yf,Math.min(Zf,g??y));Px(ye,pe,oe,Oe,u),Z&&(Z.textContent=`${Math.round(Oe*100)}%`)}let Ke=new ResizeObserver(()=>ze());Ke.observe(ve),Ne(),pe.src=n[c].url,requestAnimationFrame(()=>ze());function Le(){C||(C=!0,Ke.disconnect(),document.removeEventListener("click",Ae),k.remove())}return{element:k,goTo:Be,next:()=>$e(1),prev:()=>$e(-1),getIndex:()=>c,setDevice(oe){u=oe,ye.dataset.device=oe,me?.setSelected(oe),g=null,ze()},setColorScheme(oe){b=oe,ye.dataset.colorScheme=oe},setZoom(oe){g=oe,ze()},destroy:Le}}0&&(module.exports={ASK_USER_QUESTION_CLIENT_TOOL,ASK_USER_QUESTION_PARAMETERS_SCHEMA,ASK_USER_QUESTION_TOOL_NAME,AgentWidgetClient,AgentWidgetSession,AttachmentManager,BrowserSpeechEngine,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,ReadAloudController,SUGGEST_REPLIES_CLIENT_TOOL,SUGGEST_REPLIES_PARAMETERS_SCHEMA,SUGGEST_REPLIES_TOOL_NAME,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,builtInClientToolsForDispatch,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createAskUserQuestionBubble,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createRovingTablist,createSlashCommandsSource,createStandardBubble,createStaticMentionSource,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultMentionFilter,defaultParseRules,detectColorScheme,directivePostprocessor,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isSuggestRepliesMessage,isVoiceSupported,isWebMcpToolName,latestAgentSuggestions,listRegisteredStreamAnimations,loadMarkdownParsers,markdownPostprocessor,mergeWithDefaults,normalizeContent,onMarkdownParsersReady,parseAskUserQuestionPayload,parseSuggestRepliesPayload,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveDockConfig,resolveSanitizer,resolveTokens,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
479
479
  //# sourceMappingURL=index.cjs.map